<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
<?php
namespace SoftAI;

/*
 * SoftWP AI Chat - Standalone Entry Point
 * 
 * This file loads WordPress and renders the AI coding assistant
 * in a new tab without any WP admin header/footer.
 */
 
 
die();
 
$softwp_wp_load_paths = array(
	dirname(__FILE__, 4) . '/wp-load.php',
	dirname(__FILE__, 5) . '/wp-load.php',
);

$softwp_wp_loaded = false;
foreach($softwp_wp_load_paths as $path){
	if(file_exists($path)){
		require_once $path;
		$softwp_wp_loaded = true;
		break;
	}
}

if(!$softwp_wp_loaded){
	wp_die('Could not find wp-load.php. Please ensure WordPress is installed.');
}

if(!defined('ABSPATH')){
	die('HACKING ATTEMPT');
}

// Let them go ASAP.
if(!is_user_logged_in()){
	reporterror('Authentication Required', 'Please log in to access the AI Assistant.');
	return;
}

if(!current_user_can('activate_plugins')){
	reporterror('Access Denied', 'You do not have permission to access the AI Assistant.');
	return;
}

if(is_multisite()){
	reporterror('Access Denied', 'Multisite setup are not supported.');
	return;
}

include_once dirname(__FILE__, 2) . '/softaculous-pro.php';

define('SOFTACULOUS_PRO_AI_DIR', SOFTACULOUS_PRO_DIR . '/lib/ai');
define('SOFTACULOUS_PRO_AI_NONCE', 'softaculous_pro_ai_chat');
define('SOFTACULOUS_PRO_AI_STORAGE', WP_CONTENT_DIR .'/softaculous-pro/ai');

include_once dirname(__FILE__, 2) . '/lib/ai/ai_launcher.php';

function spro_ai_protect_storage(){
	$dir = rtrim(SOFTACULOUS_PRO_AI_STORAGE, '/');
	if(!is_dir($dir)){
		return;
	}

	$htaccess = $dir . '/.htaccess';
	if(!file_exists($htaccess)){
		$htaccess_content = 'deny from all';
		@file_put_contents($htaccess, $htaccess_content);
	}

	$webconfig = $dir . '/web.config';
	if(!file_exists($webconfig)){
		$webconfig_content = '<configuration>
<system.webServer>
<authorization>
<deny users="*" />
</authorization>
</system.webServer>
</configuration>';
		@file_put_contents($webconfig, $webconfig_content);
	}
}

spro_ai_protect_storage();

function GET($key, $default = ''){
	return softaculous_pro_optGET($key, $default);
}

function optGET($key){
	return softaculous_pro_optGET($key);
}

function cleanpath($path){
	if(empty($path)) return '';
	$path = str_replace('\\', '/', $path);
	while(strpos($path, '//') !== false){
		$path = str_replace('//', '/', $path);
	}
	while(strpos($path, '/./') !== false){
		$path = str_replace('/./', '/', $path);
	}
	$parts = explode('/', $path);
	$normalized = array();
	foreach($parts as $part){
		if($part === '..'){
			if(!empty($normalized)){
				array_pop($normalized);
			}
		}elseif($part !== '' && $part !== '.'){
			$normalized[] = $part;
		}
	}
	return '/' . implode('/', $normalized);
}

function reporterror($title, $msg){
	softheader($title);

	echo '<div style="max-width:600px;margin:80px auto;padding:40px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;text-align:center;">';
	echo '<div style="font-size:48px;margin-bottom:20px;">&#9888;</div>';
	echo '<h2 style="color:#dc3232;margin:0 0 10px;">' . esc_html($title) . '</h2>';
	echo '<p style="color:#666;line-height:1.6;">' . esc_html($msg) . '</p>';
	echo '</div>';

	softfooter();
	die();
}

function softheader($title = ''){
	echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>' . esc_html($title) . '</title></head><body>';
}

function softfooter(){
	echo '</body></html>';
}

function csrf_display(){
	echo '<input type="hidden" name="csrf_token" value="' . esc_attr(wp_create_nonce(SOFTACULOUS_PRO_AI_NONCE)) . '">';
}

function __($str, $args = array()){
	if(is_array($args)){
		foreach($args as $k => $v){
			$str = str_replace('$' . $k, $v, $str);
		}
	}
	return $str;
}

function get_sid_by_version($ver, $sid){
	return $sid;
}

function validate_path_within_home($path, $home_dir){
	if(empty($path)) return false;
	$resolved = realpath($path);
	if($resolved === false) return false;
	$home_dir = rtrim($home_dir, '/');
	$pos = strpos($resolved . '/', $home_dir . '/');
	if($pos !== 0){
		return false;
	}
	return $resolved;
}

function has_active_license(){
	global $softaculous_pro;

	if(empty($softaculous_pro['license'])){
		if(function_exists('softaculous_pro_load_license')){
			softaculous_pro_load_license();
		}
	}
	return !empty($softaculous_pro['license']['active']);
}

function bootstrap(){
	if(!defined('SOFTACULOUS_AI')){
		define('SOFTACULOUS_AI', true);
	}

	if(!defined('SOFT_AI_APP')){
		define('SOFT_AI_APP', 'SoftWP AI');
	}

	$current_user = wp_get_current_user();
	$username = $current_user->user_login;
	$home_dir = rtrim(ABSPATH, '/');

	$custom_path_get = isset($_GET['path']) ? wp_normalize_path(wp_unslash($_GET['path'])) : '';
	$base_url = SOFTACULOUS_PRO_PLUGIN_URL . 'main/ai-chat.php?';

	global $user, $globals, $l, $theme, $softpanel, $error, $insid, $software, $soft;
	global $edited, $settings, $iscripts, $catwise, $scripts, $noheader;
	global $custom_path;

	$softpanel = new \stdClass();
	$softpanel->user = array(
		'name' => $username,
		'homedir' => $home_dir,
	);

	$user = array(
		'username' => $username,
		'ins' => array(),
	);
	
	$charset = get_bloginfo('charset');

	$globals = array(
		'charset' => $charset ?? 'UTF-8',
		'index' => $base_url,
		'ind' => $base_url,
	);

	$iscripts = array(
		'wp' => array(
			'name' => 'WordPress',
			'ver' => get_bloginfo('version'),
		),
	);

	$software = array('name' => 'WordPress');
	$soft = 'wp';
	$insid = '';
	$custom_path = $custom_path_get;
	$l = array();
	$error = '';
	$edited = '';
	$settings = '';
	$catwise = '';
	$scripts = '';
	$noheader = '';
	$theme = array();

	include_once(SOFTACULOUS_PRO_AI_DIR . '/ai_launcher.php');
}

function verify_nonce(){
	$csrf_token = isset($_GET['csrf_token']) ? $_GET['csrf_token'] : (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : '');
	$result = wp_verify_nonce($csrf_token, SOFTACULOUS_PRO_AI_NONCE);
	if(empty($result)){
		wp_send_json_error(array('error' => 'Security check failed. Please refresh the page.'), 403);
	}
}

function handle_request(){
	if(!has_active_license()){
		reporterror('License Required', 'An active Softaculous Pro license is required to use the AI Assistant.');
		return;
	}

	$home_dir = rtrim(ABSPATH, '/');
	$current_user = wp_get_current_user();
	$username = $current_user->user_login;

	$incoming_path = isset($_GET['path']) ? $_GET['path'] : '';
	$incoming_path_post = isset($_POST['path']) ? $_POST['path'] : '';
	if(empty($incoming_path) && !empty($incoming_path_post)){
		$incoming_path = $incoming_path_post;
	}

	if(!empty($incoming_path_post) && empty($incoming_path)){
		verify_nonce();
	}

	$project_id = isset($_GET['project_id']) ? $_GET['project_id'] : (isset($_POST['project_id']) ? $_POST['project_id'] : '');
	if(!empty($project_id)){
		ai_php_init_classes();

		require_once(SOFTACULOUS_PRO_AI_DIR . '/core/class_project.php');

		$_proj = AIProject::load($username, $project_id);
		if(empty($_proj) || empty($_proj['path'])){
			reporterror('Invalid Project', 'Project not found.');
			return;
		}

		$proj_path = $_proj['path'];
		if(strpos($proj_path, '/') !== 0){
			$proj_path = $home_dir . '/' . ltrim($proj_path, '/');
		}

		$resolved_proj = validate_path_within_home($proj_path, $home_dir);
		if($resolved_proj === false){
			reporterror('Invalid Project', 'Project path is outside your home directory.');
			return;
		}
		$incoming_path = $proj_path;
	}

	if(empty($incoming_path) && empty($project_id)){
		$_GET['path'] = $home_dir;
	}

	$api_action = isset($_GET['ai_php_api']) ? sanitize_text_field(wp_unslash($_GET['ai_php_api'])) : '';
	$stream = isset($_GET['ai_chat_stream']) ? sanitize_text_field(wp_unslash($_GET['ai_chat_stream'])) : '';

	if(!empty($stream)){
		verify_nonce();
		bootstrap();
		while(ob_get_level()){
			ob_end_clean();
		}
		include_once(SOFTACULOUS_PRO_AI_DIR . '/ai.php');
		ai();
		return;
	}

	if(!empty($api_action)){
		verify_nonce();
		bootstrap();
		include_once(SOFTACULOUS_PRO_AI_DIR . '/ai.php');
		ai();
		return;
	}

	bootstrap();
	include_once(SOFTACULOUS_PRO_AI_DIR . '/ai.php');
	ai();

	include_once(SOFTACULOUS_PRO_AI_DIR . '/theme/ai_theme.php');
	ai_theme();
}

function is_safe_file($file_path, $base_dir = ''){
	if(empty($base_dir)){
		$base_dir = rtrim(ABSPATH, '/');
	}

	if(empty($base_dir) || !is_dir($base_dir)) {
		return false;
	}

	$real_base = realpath($base_dir);
	
	if($real_base === false) return false;

	$real_file = realpath(dirname($file_path));
	if($real_file === false) {			
		return false;
	}

	return strpos($real_file, $real_base . '/') === 0 || $real_file === $real_base;
}

handle_request();
