'15096', 'slug' => 'ai-auto-tool', 'premium_slug' => 'ai-auto-tool-pay', 'type' => 'plugin', 'public_key' => 'pk_a1bb06b76f38f9ff1132089d99b21', 'is_premium' => false, 'has_premium_version' => false, 'has_addons' => false, 'has_paid_plans' => true, 'has_affiliation' => 'all', 'menu' => array( 'slug' => 'ai_auto_tool', 'contact' => true, 'support' => false, 'network' => true, ), ) ); } return $aiautotool_premium; } aiautotool_premium(); do_action( 'aiautotool_premium_loaded' ); } aiautotool_premium()->add_filter( 'hide_freemius_powered_by', '__return_true' ); /* translators: %s là đường dẫn tới trang nâng cấp lên bản Pro của AI Auto Tool.*/ $Upgrade_notifice = sprintf('AI Auto Tool Limit Quota. Please Upgrade Pro', aiautotool_premium()->get_upgrade_url()); define('AIAUTOTOOL_TITLE_UPGRADE', $Upgrade_notifice); function aiautotool_activate() { require_once esc_html( plugin_dir_path( __FILE__ ) ) . 'vendor/aiautotool/class-ai-auto-tool-activator.php'; Ai_auto_tool_Activator::activate(); } function aiautotool_deactivate() { require_once esc_html( plugin_dir_path( __FILE__ ) ) . 'vendor/aiautotool/class-ai-auto-tool-deactivator.php'; Ai_auto_tool_Deactivator::deactivate(); } register_activation_hook( __FILE__, 'aiautotool_activate' ); register_deactivation_hook( __FILE__, 'aiautotool_deactivate' ); // Load textdomain immediately before loading any other files that might use translations // This must happen before bootstrap.php is loaded to prevent WordPress 6.7.0 warnings if (function_exists('load_plugin_textdomain')) { load_plugin_textdomain('ai-auto-tool', false, dirname(plugin_basename(__FILE__)) . '/languages/'); } // Load Extra Config Module (MANDATORY - always loads, not dependent on active/disable) // Must load BEFORE class instantiation to ensure class exists when registering $extra_config_bootstrap = plugin_dir_path(__FILE__) . 'inc/extra-config/bootstrap.php'; if (file_exists($extra_config_bootstrap)) { require_once $extra_config_bootstrap; } // Load Floating Robot Widget EARLY to ensure admin_enqueue_scripts hook is registered // This must be loaded before AI_Auto_Tool class is instantiated to catch admin_enqueue_scripts hook if( ! class_exists( 'AI_Auto_Tool' ) ) { class AI_Auto_Tool { protected $subclasses = []; private $aiautotool_config_settings; public function __construct() { // Initialize Professional Autoloader System $this->init_autoloader_system(); // Textdomain is now loaded early in the plugin file (line ~61) before any code runs // This prevents WordPress 6.7.0 translation loading warnings // Menu registration now handled by Menu Manager // add_action( 'admin_menu', array( $this, 'add_menu_page' ) , 10, 2); add_action( 'admin_init', array( $this, 'register_settings' ) ); add_action( 'rest_api_init', array($this,'create_post_route')); add_action('wp_ajax_aiautotool_insert_post', array( $this, 'aiautotool_insert_post_ajax' )); add_action( 'wp_ajax_aiautotool_get_cate', array( $this, 'aiautotool_get_cate' )); add_action( 'wp_ajax_get_all_media', array( $this, 'get_all_media_callback' )); add_action( 'wp_ajax_aiautotool_save_image', array( $this, 'aiautotool_save_image' )); // AJAX handlers for Bard API to avoid CORS issues add_action( 'wp_ajax_aiautotool_bard_contentmore', array( $this, 'aiautotool_bard_contentmore_callback' )); add_action( 'wp_ajax_aiautotool_bard_content', array( $this, 'aiautotool_bard_content_callback' )); add_action( 'wp_ajax_aiautotool_bard_rewrite', array( $this, 'aiautotool_bard_rewrite_callback' )); // Legacy loading methods (now handled by autoloader) // DEBUG MODE: Track memory during initialization if (defined('WP_DEBUG') && WP_DEBUG && (defined('AIAUTOTOOL_DEBUG_LOADING') && AIAUTOTOOL_DEBUG_LOADING)) { $init_memory = round(memory_get_usage(true) / 1024 / 1024, 2); error_log("AI Auto Tool DEBUG: [INIT] Starting plugin initialization - Memory: {$init_memory} MB"); } self::load_lib(); if (defined('WP_DEBUG') && WP_DEBUG && (defined('AIAUTOTOOL_DEBUG_LOADING') && AIAUTOTOOL_DEBUG_LOADING)) { $after_lib_memory = round(memory_get_usage(true) / 1024 / 1024, 2); error_log("AI Auto Tool DEBUG: [AFTER load_lib] Memory: {$after_lib_memory} MB"); } // self::load_inc(); self::aiautotool_new_object(); if (defined('WP_DEBUG') && WP_DEBUG && (defined('AIAUTOTOOL_DEBUG_LOADING') && AIAUTOTOOL_DEBUG_LOADING)) { $after_new_object_memory = round(memory_get_usage(true) / 1024 / 1024, 2); error_log("AI Auto Tool DEBUG: [AFTER aiautotool_new_object] Memory: {$after_new_object_memory} MB"); } // Assets are now managed by Asset Manager (inc/asset-manager.php) // Old method add_aiautotool_button_js() is kept for backward compatibility // but Asset Manager handles it more efficiently with conditional loading // Register AJAX handlers for all features add_action( 'init', array( $this, 'register_all_ajax_handlers' ) ); add_filter('plugin_action_links', array( $this, 'add_ai_auto_tool_settings_link' ), 10, 2); // SSL Management AJAX handlers are registered in SSL Manager class (inc/features/ssl-manager/ssl.php) // No need to register here to avoid duplicates register_activation_hook(__FILE__, array($this, 'activate')); register_deactivation_hook(__FILE__, array($this, 'deactivate')); $aiautotool_Warning_Notice = new aiautotool_Warning_Notice(array( 'icon_url' => plugins_url('/images/logo.svg', __FILE__), 'title' => 'Aiautotool Plugin ', 'content' => 'The plugin is available for free so if it benefits you. Join the plugin support group here.', 'button_text' => 'Join group support Ai auto Tool Plugin', 'button_url' => 'https://t.me/aiautotoolchat', )); } public function init_settings() { } private function aiautotool_getdata() { return rendersetting::aiautotool_getdata(); } public function load_textdomain() { load_plugin_textdomain('ai-auto-tool', false, dirname(plugin_basename(__FILE__)) . '/languages/'); } public function activate() { if (class_exists('activeCallBack')) { $activeCallBack = new activeCallBack(); $activeCallBack->activate(); } } public function deactivate(){ $siteurl = get_option('siteurl'); $siteurl = str_replace('https://', 'http://', $siteurl); update_option('siteurl', $siteurl); // } $home = get_option('home'); $home = str_replace('https://', 'http://', $home); update_option('home', $home); if (class_exists('activeCallBack')) { $activeCallBack = new activeCallBack(); $activeCallBack->deactivate(); } global $wpdb; $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'aiautotool_%'" ); $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'fs_%'" ); } function add_ai_auto_tool_settings_link($links, $file) { if (false !== strpos($file, 'ai-auto-tool/Ai-Auto-Tool.php')) { $settings_link = 'Settings'; array_unshift($links, $settings_link); } return $links; } public function addSubclass($subclass) { // Prevent duplicate instances foreach ($this->subclasses as $existing) { if (get_class($existing) === get_class($subclass)) { return; // Already added, skip duplicate } } $this->subclasses[] = $subclass; } public function aiautotool_new_object(){ // Static flag to prevent multiple executions static $new_object_loaded = false; if ($new_object_loaded) { return; } // CRITICAL FIX: Don't instantiate all classes immediately! // This causes memory exhaustion. Most classes will be loaded on-demand // via load_all_inc_features() when actually needed (lazy loading). // Only load essential classes that must register hooks immediately. // Extra Config - New Architecture (required for settings) if (class_exists('Aiautotool_Extra_Config_Manager')) { $extra_config_manager = Aiautotool_Extra_Config_Manager::instance(); $this->addSubclass($extra_config_manager); } // AI Provider Settings UI - Always loaded (mandatory) if (class_exists('AIAutotool_AI_Provider_Settings_UI')) { $ai_provider_settings_ui = new AIAutotool_AI_Provider_Settings_UI(); $this->addSubclass($ai_provider_settings_ui); } // NOTE: All other class instantiations are now handled by load_all_inc_features() // which is called on-demand via render_list_feature() - lazy loading approach // COMMENTED OUT to prevent memory exhaustion - these will be loaded on-demand: // AIAutotool_API_Manager is now replaced by AIAutotool_AI_Provider_Settings_UI // Old API Manager is kept only for backward compatibility (alias in aiautotool_ai_provider_api_keys.php) // if (class_exists('AIAutotool_API_Manager')) { // $AIAutotool_API_Manager = new AIAutotool_API_Manager(); // $this->addSubclass($AIAutotool_API_Manager); // } // SSL Manager - Always load to enable tab settings (class will check active status internally) $ssl_manager_file = plugin_dir_path(__FILE__) . 'inc/features/ssl-manager/ssl-manager.php'; if (file_exists($ssl_manager_file)) { require_once $ssl_manager_file; if (class_exists('AIAutoTool\\Features\\SSLManager\\SSLManager')) { try { $ssl_manager = new \AIAutoTool\Features\SSLManager\SSLManager(); $this->addSubclass($ssl_manager); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load SSLManager: ' . $e->getMessage()); } } } } // Autoblogging - Only load if active (default is false) $autoblogging_active = get_option('AI_AutoTool_Autoblogging_active', 'false'); if ($autoblogging_active === 'true' || $autoblogging_active === true) { $autoblogging_file = plugin_dir_path(__FILE__) . 'inc/features/autoblogging/autoblogging.php'; if (file_exists($autoblogging_file)) { require_once $autoblogging_file; if (class_exists('AIAutoTool\\Features\\Autoblogging\\Autoblogging')) { try { $autoblogging = new \AIAutoTool\Features\Autoblogging\Autoblogging(); $this->addSubclass($autoblogging); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load Autoblogging: ' . $e->getMessage()); } } } } } // Image Scanner - Always load to enable tab settings (class will check active status internally) $image_scanner_file = plugin_dir_path(__FILE__) . 'inc/features/image-scanner/image-scanner.php'; if (file_exists($image_scanner_file)) { require_once $image_scanner_file; if (class_exists('AIAutoTool\\Features\\ImageScanner\\ImageScanner')) { try { $image_scanner = new \AIAutoTool\Features\ImageScanner\ImageScanner(); $this->addSubclass($image_scanner); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load ImageScanner: ' . $e->getMessage()); } } } } // Bot Security - Always load to enable tab settings (class will check active status internally) $bot_security_file = plugin_dir_path(__FILE__) . 'inc/features/bot-security/bot-security.php'; if (file_exists($bot_security_file)) { require_once $bot_security_file; if (class_exists('AIAutoTool\\Features\\BotSecurity\\BotSecurity')) { try { $bot_security = new \AIAutoTool\Features\BotSecurity\BotSecurity(); $this->addSubclass($bot_security); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load BotSecurity: ' . $e->getMessage()); } } } } // Auto Comment - Always load to enable tab settings (class will check active status internally) $auto_comment_file = plugin_dir_path(__FILE__) . 'inc/features/auto-comment/auto-comment.php'; if (file_exists($auto_comment_file)) { require_once $auto_comment_file; if (class_exists('AIAutoTool\\Features\\AutoComment\\AutoComment')) { try { $auto_comment = new \AIAutoTool\Features\AutoComment\AutoComment(); $this->addSubclass($auto_comment); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load AutoComment: ' . $e->getMessage()); } } } } // Auto Create Tags - Always load to enable tab settings (class will check active status internally) $auto_create_tags_file = plugin_dir_path(__FILE__) . 'inc/features/auto-create-tags/auto-create-tags.php'; if (file_exists($auto_create_tags_file)) { require_once $auto_create_tags_file; if (class_exists('AIAutoTool\\Features\\AutoCreateTags\\AutoCreateTags')) { try { $auto_create_tags = new \AIAutoTool\Features\AutoCreateTags\AutoCreateTags(); $this->addSubclass($auto_create_tags); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load AutoCreateTags: ' . $e->getMessage()); } } } } // Canonical Manager - Always load to enable tab settings (class will check active status internally) $canonical_manager_file = plugin_dir_path(__FILE__) . 'inc/features/canonical-manager/canonical-manager.php'; if (file_exists($canonical_manager_file)) { require_once $canonical_manager_file; if (class_exists('AIAutoTool\\Features\\CanonicalManager\\CanonicalManager')) { try { $canonical_manager = new \AIAutoTool\Features\CanonicalManager\CanonicalManager(); $this->addSubclass($canonical_manager); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load CanonicalManager: ' . $e->getMessage()); } } } } // External Links - Always load to enable tab settings (class will check active status internally) $external_links_file = plugin_dir_path(__FILE__) . 'inc/features/external-links/external-links.php'; if (file_exists($external_links_file)) { require_once $external_links_file; if (class_exists('AIAutoTool\\Features\\ExternalLinks\\ExternalLinks')) { try { $external_links = new \AIAutoTool\Features\ExternalLinks\ExternalLinks(); $this->addSubclass($external_links); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load ExternalLinks: ' . $e->getMessage()); } } } } // Cloudflare AI - Always load to enable tab settings (class will check active status internally) $cloudflare_ai_file = plugin_dir_path(__FILE__) . 'inc/features/cloudflare-ai/cloudflare-ai.php'; if (file_exists($cloudflare_ai_file)) { require_once $cloudflare_ai_file; if (class_exists('AIAutoTool\\Features\\CloudflareAI\\CloudflareAI')) { try { $cloudflare_ai = new \AIAutoTool\Features\CloudflareAI\CloudflareAI(); $this->addSubclass($cloudflare_ai); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load CloudflareAI: ' . $e->getMessage()); } } } } // Submit Index - Always load to enable tab settings (class will check active status internally) $submit_index_file = plugin_dir_path(__FILE__) . 'inc/features/submit-index/submit-index.php'; if (file_exists($submit_index_file)) { require_once $submit_index_file; if (class_exists('AIAutoTool\\Features\\SubmitIndex\\SubmitIndex')) { try { $submit_index = new \AIAutoTool\Features\SubmitIndex\SubmitIndex(); $this->addSubclass($submit_index); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load SubmitIndex: ' . $e->getMessage()); } } } } // Suggest Auto - Always load to enable tab settings (class will check active status internally) $suggest_auto_file = plugin_dir_path(__FILE__) . 'inc/features/suggest-auto/suggest-auto.php'; if (file_exists($suggest_auto_file)) { require_once $suggest_auto_file; if (class_exists('AIAutoTool\\Features\\SuggestAuto\\SuggestAuto')) { try { $suggest_auto = new \AIAutoTool\Features\SuggestAuto\SuggestAuto(); $this->addSubclass($suggest_auto); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load SuggestAuto: ' . $e->getMessage()); } } } } // Username Generator - Always load to enable tab settings (class will check active status internally) $username_generator_file = plugin_dir_path(__FILE__) . 'inc/features/username-generator/username-generator.php'; if (file_exists($username_generator_file)) { require_once $username_generator_file; if (class_exists('AIAutoTool\\Features\\UsernameGenerator\\UsernameGenerator')) { try { $username_generator = new \AIAutoTool\Features\UsernameGenerator\UsernameGenerator(); $this->addSubclass($username_generator); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load UsernameGenerator: ' . $e->getMessage()); } } } } // Web Stories - Always load to enable tab settings (class will check active status internally) $web_stories_file = plugin_dir_path(__FILE__) . 'inc/features/web-stories/web-stories.php'; if (file_exists($web_stories_file)) { require_once $web_stories_file; if (class_exists('AIAutoTool\\Features\\WebStories\\WebStories')) { try { $web_stories = new \AIAutoTool\Features\WebStories\WebStories(); $this->addSubclass($web_stories); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load WebStories: ' . $e->getMessage()); } } } } // Footer Base - Always load to enable tab settings (class will check active status internally) $footer_base_file = plugin_dir_path(__FILE__) . 'inc/features/footer-base/footer-base.php'; if (file_exists($footer_base_file)) { require_once $footer_base_file; if (class_exists('AIAutoTool\\Features\\FooterBase\\FooterBase')) { try { $footer_base = new \AIAutoTool\Features\FooterBase\FooterBase(); $this->addSubclass($footer_base); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load FooterBase: ' . $e->getMessage()); } } } } // Prompt CPT - Always load to enable tab settings (class will check active status internally) $prompt_cpt_file = plugin_dir_path(__FILE__) . 'inc/features/prompt-cpt/prompt-cpt.php'; if (file_exists($prompt_cpt_file)) { require_once $prompt_cpt_file; if (class_exists('AIAutoTool\\Features\\PromptCPT\\PromptCPT')) { try { $prompt_cpt = new \AIAutoTool\Features\PromptCPT\PromptCPT(); $this->addSubclass($prompt_cpt); } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Failed to load PromptCPT: ' . $e->getMessage()); } } } } if (class_exists('URL_Scanner_Plugin')) { $url_scanner_plugin = new URL_Scanner_Plugin(); $this->addSubclass($url_scanner_plugin); } if (class_exists('AIAutoToolsinglepost')) { $AIAutoToolsinglepost = new AIAutoToolsinglepost(); $this->addSubclass($AIAutoToolsinglepost); } if (class_exists('AIautotool_autocomment')) { $AIautotool_autocomment = new AIautotool_autocomment(); $this->addSubclass($AIautotool_autocomment); } if (class_exists('AIautotool_autocreatetags')) { $AIautotool_autocreatetags = new AIautotool_autocreatetags(); $this->addSubclass($AIautotool_autocreatetags); } if (class_exists('AI_AutoTool_cloudflareAI')) { $AI_AutoTool_cloudflareAI = new AI_AutoTool_cloudflareAI (); $this->addSubclass($AI_AutoTool_cloudflareAI); } if (class_exists('AI_AutoTool_suggetauto')) { $AI_AutoTool_suggetauto = new AI_AutoTool_suggetauto (); $this->addSubclass($AI_AutoTool_suggetauto); } if (class_exists('AIautotool_Prompt_CPT')) { $AIautotool_Prompt_CPT = new AIautotool_Prompt_CPT (); $this->addSubclass($AIautotool_Prompt_CPT); } if (class_exists('AIAutoTool_SubmitIndex')) { $AIAutoTool_SubmitIndex = new AIAutoTool_SubmitIndex(); $this->addSubclass($AIAutoTool_SubmitIndex); } if (class_exists('Aiautotool_exLink_backlink')) { $Aiautotool_exLink_backlink = new Aiautotool_exLink_backlink(); $this->addSubclass($Aiautotool_exLink_backlink); } if (class_exists('Aiautotool_Canonical')) { $Aiautotool_Canonical = new Aiautotool_Canonical(); $this->addSubclass($Aiautotool_Canonical); } if (class_exists('AIautotool_Web_Stories')) { $AIautotool_Web_Stories = new AIautotool_Web_Stories(); $this->addSubclass($AIautotool_Web_Stories); } // if (class_exists('AIAutoToolSecurityBot')) { // $AIAutoToolSecurityBot = new AIAutoToolSecurityBot(); // $this->addSubclass($AIAutoToolSecurityBot); // } // if (class_exists('AIAutotool_Image404Scanner')) { // $AIAutotool_Image404Scanner = new AIAutotool_Image404Scanner(); // $this->addSubclass($AIAutotool_Image404Scanner); // } // if (class_exists('aiautotool_AutoGenerateUsername')) { // $aiautotool_AutoGenerateUsername = new aiautotool_AutoGenerateUsername(); // $this->addSubclass($aiautotool_AutoGenerateUsername); // } // if (class_exists('Post_Exporter_Plugin')) { // $Post_Exporter_Plugin = new Post_Exporter_Plugin(); // $this->addSubclass($Post_Exporter_Plugin); // } // if (class_exists('Auto_Install_Plugins')) { // $Auto_Install_Plugins = new Auto_Install_Plugins(); // $this->addSubclass($Auto_Install_Plugins); // } // if (class_exists('Keyword_Autopost_Plugin')) { // $Keyword_Autopost_Plugin = new Keyword_Autopost_Plugin(); // $this->addSubclass($Keyword_Autopost_Plugin); // } // if (class_exists('Aiautotool_Footer_Base')) { // $Aiautotool_Footer_Base = new Aiautotool_Footer_Base(); // $this->addSubclass($Aiautotool_Footer_Base); // } // if (class_exists('aiautotool_SSL_active')) { // $aiautotool_SSL_active = new aiautotool_SSL_active(); // $this->addSubclass($aiautotool_SSL_active); // } // if (class_exists('activeCallBack')) { // $activeCallBack = new activeCallBack(); // } // if (class_exists('AI_AutoTool_Prompt_Customer')) { // $AI_AutoTool_Prompt_Customer = new AI_AutoTool_Prompt_Customer(); // } $new_object_loaded = true; } public function show_render_setting() { foreach ($this->subclasses as $subclass) { if (method_exists($subclass, 'render_setting')) { $subclass->render_setting(); } } } public function show_render_tab_setting() { foreach ($this->subclasses as $subclass) { if (method_exists($subclass, 'render_tab_setting')) { $subclass->render_tab_setting(); } } } public function render_list_feature(){ // Load only active features from inc directory $this->load_all_inc_features(); // Render all features (both active and inactive) using AutoToolBox $this->render_all_features(); } /** * Force load feature descriptions file */ private function ensure_feature_descriptions_loaded() { if (!class_exists('AiAutoTool_Feature_Descriptions')) { $file_path = plugin_dir_path(__FILE__) . 'lib/feature-descriptions.php'; if (file_exists($file_path)) { require_once $file_path; error_log('AI Auto Tool Debug: Force loaded feature-descriptions.php'); } else { error_log('AI Auto Tool Debug: feature-descriptions.php not found at: ' . $file_path); } } } /** * Get feature description with fallback * * @param string $feature_key Feature key * @param string $fallback_description Fallback description if class not available * @return string Description HTML */ private function get_feature_description($feature_key, $fallback_description = '') { // Ensure feature descriptions are loaded $this->ensure_feature_descriptions_loaded(); // Debug: Check if class exists if (!class_exists('AiAutoTool_Feature_Descriptions')) { error_log('AI Auto Tool Debug: AiAutoTool_Feature_Descriptions class not found for feature: ' . $feature_key); return $fallback_description; } $description = AiAutoTool_Feature_Descriptions::get_truncated_description($feature_key); if (empty($description)) { error_log('AI Auto Tool Debug: Empty description for feature: ' . $feature_key); return $fallback_description; } return $description; } /** * Render all features (active and inactive) using AutoToolBox * IMPORTANT FUNCTION: This method controls feature rendering in the main UI. */ private function render_all_features() { // Static flag to prevent multiple renders static $features_rendered = false; if ($features_rendered) { return; } // Cache for option values to prevent repeated database queries static $option_cache = array(); $inc_dir = plugin_dir_path(__FILE__) . 'inc/'; // Define all feature files with their metadata // NOTE: Descriptions are hardcoded here to avoid calling get_feature_description() // which could trigger recursive loading $feature_files = array( 'features/ssl-manager/ssl-manager.php' => array( 'class' => 'AIAutoTool\Features\SSLManager\SSLManager', 'active_option' => 'aiautotool_SSL_active', 'title' => 'SSL Manager', 'description' => $this->get_feature_description('ssl_fix', 'Manage SSL certificates and security settings'), 'icon' => '' ), 'features/canonical-manager/canonical-manager.php' => array( 'class' => 'AIAutoTool\Features\CanonicalManager\CanonicalManager', 'active_option' => 'Aiautotool_Canonical_active', 'title' => 'Canonical Manager', 'description' => $this->get_feature_description('canonical', 'Manage canonical URLs and redirects'), 'icon' => '' ), 'features/external-links/external-links.php' => array( 'class' => 'AIAutoTool\Features\ExternalLinks\ExternalLinks', 'active_option' => 'Aiautotool_exLink_backlink_active', 'title' => 'Auto External Links', 'description' => $this->get_feature_description('microsite_backlink', 'Automatically manage external links and backlinks'), 'icon' => '' ), 'features/submit-index/submit-index.php' => array( 'class' => 'AIAutoTool\Features\SubmitIndex\SubmitIndex', 'active_option' => 'AIAutoTool_SubmitIndex_active', 'title' => 'Submit Index', 'description' => $this->get_feature_description('google_index', 'Submit URLs to search engines for indexing'), 'icon' => '' ), 'features/post-exporter/post-exporter.php' => array( 'class' => 'AIAutoTool\Features\PostExporter\PostExporter', 'active_option' => 'Post_Exporter_Plugin_active', 'title' => 'Post Exporter', 'description' => $this->get_feature_description('post_exporter', 'Export posts and content to various formats'), 'icon' => '' ), 'features/keyword-autopost/keyword-autopost.php' => array( 'class' => 'AIAutoTool\Features\KeywordAutopost\KeywordAutopost', 'active_option' => 'Keyword_Autopost_Plugin_active', 'title' => 'Keyword Autopost', 'description' => $this->get_feature_description('keyword_autopost', 'Automatically create posts based on keywords'), 'icon' => '' ), 'features/single-ai/single-ai.php' => array( 'class' => 'AIAutoTool\Features\SingleAI\SingleAI', 'active_option' => 'AIAutoToolsinglepost_active', 'title' => 'Single AI Post', 'description' => $this->get_feature_description('single_ai', 'Create individual AI-powered posts'), 'icon' => '' ), 'features/image-scanner/image-scanner.php' => array( 'class' => 'AIAutoTool\Features\ImageScanner\ImageScanner', 'active_option' => 'AIAutotool_Image404Scanner_active', 'title' => 'Image Scanner', 'description' => $this->get_feature_description('thumb_fix', 'Scan and manage images for 404 errors'), 'icon' => '' ), 'features/auto-comment/auto-comment.php' => array( 'class' => 'AIAutoTool\Features\AutoComment\AutoComment', 'active_option' => 'AIautotool_autocomment_active', 'title' => 'Auto Comment', 'description' => $this->get_feature_description('auto_comment', 'Automatically generate and post comments using AI'), 'icon' => '' ), 'features/auto-create-tags/auto-create-tags.php' => array( 'class' => 'AIAutoTool\Features\AutoCreateTags\AutoCreateTags', 'active_option' => 'AIautotool_autocreatetags_active', 'title' => 'Auto Create Tags', 'description' => $this->get_feature_description('auto_create_tag', 'Automatically create and assign tags to posts'), 'icon' => '' ), 'features/cloudflare-ai/cloudflare-ai.php' => array( 'class' => 'AIAutoTool\Features\CloudflareAI\CloudflareAI', 'active_option' => 'AI_AutoTool_cloudflareAI_active', 'title' => 'Cloudflare AI', 'description' => $this->get_feature_description('cloudflare_ai', 'Integrate with Cloudflare AI services'), 'icon' => '' ), 'features/suggest-auto/suggest-auto.php' => array( 'class' => 'AIAutoTool\Features\SuggestAuto\SuggestAuto', 'active_option' => 'AI_AutoTool_suggetauto_active', 'title' => 'Suggest Auto', 'description' => $this->get_feature_description('suggest_auto', 'Automatically suggest content improvements'), 'icon' => '' ), 'features/prompt-cpt/prompt-cpt.php' => array( 'class' => 'AIAutoTool\Features\PromptCPT\PromptCPT', 'active_option' => 'AIautotool_Prompt_CPT_active', 'title' => 'Prompt CPT', 'description' => $this->get_feature_description('prompt_manager', 'Manage custom post types for prompts'), 'icon' => '' ), 'features/prompt-customer/prompt-customer.php' => array( 'class' => 'AIAutoTool\Features\PromptCustomer\PromptCustomer', 'active_option' => 'AI_AutoTool_Prompt_Customer_active', 'title' => 'Prompt Customer', 'description' => 'Manage customer-specific prompts', 'icon' => '' ), // Temporarily disabled due to HTML output issues 'features/bot-security/bot-security.php' => array( 'class' => 'AIAutoTool\Features\BotSecurity\BotSecurity', 'active_option' => 'AIAutoToolSecurityBot_active', 'title' => 'Bot Security', 'description' => 'Security features for bot protection', 'icon' => '' ), 'features/web-stories/web-stories.php' => array( 'class' => 'AIAutoTool\Features\WebStories\WebStories', 'active_option' => 'AIautotool_Web_Stories_active', 'title' => 'Web Stories', 'description' => $this->get_feature_description('webstories', 'Create and manage web stories'), 'icon' => '' ), 'features/install-plugin/install-plugin.php' => array( 'class' => 'AIAutoTool\Features\InstallPlugin\InstallPlugin', 'active_option' => 'Aiautotool_Install_Plugin_active', 'title' => 'Install Plugin', 'description' => $this->get_feature_description('install_plugin', 'Install and manage plugins'), 'icon' => '' ), 'features/footer-base/footer-base.php' => array( 'class' => 'AIAutoTool\Features\FooterBase\FooterBase', 'active_option' => 'Aiautotool_footer_base_active', 'title' => 'Footer Base', 'description' => 'Manage footer content and base elements', 'icon' => '' ), 'features/username-generator/username-generator.php' => array( 'class' => 'AIAutoTool\Features\UsernameGenerator\UsernameGenerator', 'active_option' => 'aiautotool_AutoGenerateUsername_active', 'title' => 'Auto Generate Username', 'description' => 'Automatically generate usernames', 'icon' => '' ), 'features/autoblogging/autoblogging.php' => array( 'class' => 'AIAutoTool\Features\Autoblogging\Autoblogging', 'active_option' => 'AI_AutoTool_Autoblogging_active', 'title' => 'Autoblogging', 'description' => 'Automatically create blog posts from URLs using AI', 'icon' => '' ), // 'cron-status-widget/cron-status-widget.php' => array( // 'class' => 'AIAutoTool_Cron_Status_Widget', // 'active_option' => 'AIAutoTool_Cron_Status_Widget_active', // 'title' => 'Cron Status Widget', // 'description' => 'Monitor and manage WordPress cron jobs', // 'icon' => '' // ), ); foreach ($feature_files as $file => $config) { $file_path = $inc_dir . $file; $class_name = $config['class']; $active_option = $config['active_option']; $title = $config['title']; $description = $config['description']; $icon = $config['icon']; // Check if file exists if (file_exists($file_path)) { // Check if feature is active - use cache to prevent repeated DB queries // Special handling: Cron Status Widget is always active if ($active_option === 'AIAutoTool_Cron_Status_Widget_active') { $is_active = 'true'; // Always active, cannot be disabled // Ensure option is set to true if (!isset($option_cache[$active_option])) { update_option($active_option, 'true'); $option_cache[$active_option] = 'true'; } } else { if (!isset($option_cache[$active_option])) { $option_cache[$active_option] = get_option($active_option, false); } $is_active = $option_cache[$active_option]; } $active = ($is_active === 'true' || $is_active === true); // Create AutoToolBox for this feature $box = new AutoToolBox( $icon . ' ' . $title, $description, admin_url('admin.php?page=aiautotool_integrations'), $active_option, $active, '', false ); // Render the box echo $box->generateHTML(); } } $features_rendered = true; } /** * Register AJAX handlers for all features */ public function register_all_ajax_handlers() { $active_options = array( 'aiautotool_SSL_active', 'Aiautotool_Canonical_active', 'Aiautotool_exLink_backlink_active', 'AIAutoTool_SubmitIndex_active', 'Post_Exporter_Plugin_active', 'Keyword_Autopost_Plugin_active', 'AIAutoToolsinglepost_active', 'AIAutotool_Image404Scanner_active', 'AIautotool_autocomment_active', 'AIautotool_autocreatetags_active', 'AI_AutoTool_cloudflareAI_active', 'AI_AutoTool_suggetauto_active', 'AIautotool_Prompt_CPT_active', // Temporarily disabled due to HTML output issues 'AIAutoToolSecurityBot_active', 'AIautotool_Web_Stories_active', 'Aiautotool_Install_Plugin_active', 'AI_AutoTool_Autoblogging_active', 'AIAutoTool_Cron_Status_Widget_active', 'aiautotool_AutoGenerateUsername_active', 'Aiautotool_footer_base_active', ); foreach ($active_options as $option) { // Register AJAX handler for this option (requires authentication - options modification) add_action('wp_ajax_update_active_option_canonical_' . $option, array($this, 'generic_update_active_option_callback')); } } /** * Generic AJAX callback for updating active options */ public function generic_update_active_option_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')), 403); return; } if (isset($_POST['active'])) { $active = sanitize_text_field($_POST['active']); // Get the option name from the action hook $action = current_action(); $option_name = str_replace('wp_ajax_update_active_option_canonical_', '', $action); // Update the option update_option($option_name, $active, null, 'no'); // Return the new value wp_send_json_success(array('active' => $active, 'option' => $option_name)); } wp_send_json_error('Invalid request'); } /** * Tải tất cả các tính năng từ thư mục inc và thêm vào subclasses * Chỉ tải các tính năng đang được kích hoạt * CHẾ ĐỘ DEBUG: Bao gồm từng tệp một để theo dõi mức sử dụng bộ nhớ */ private function load_all_inc_features() { // Static flag to prevent multiple loads static $features_loaded = false; if ($features_loaded) { return; } // DEBUG MODE: Enable to track memory usage per file $debug_mode = defined('WP_DEBUG') && WP_DEBUG && (defined('AIAUTOTOOL_DEBUG_LOADING') && AIAUTOTOOL_DEBUG_LOADING); // Cache for option values to prevent repeated database queries static $option_cache = array(); $inc_dir = plugin_dir_path(__FILE__) . 'inc/'; // Define all feature files, their classes, and active option names $feature_files = array( 'features/ssl-manager/ssl-manager.php' => array( 'class' => 'AIAutoTool\Features\SSLManager\SSLManager', 'active_option' => 'aiautotool_SSL_active' ), 'features/canonical-manager/canonical-manager.php' => array( 'class' => 'AIAutoTool\Features\CanonicalManager\CanonicalManager', 'active_option' => 'Aiautotool_Canonical_active' ), 'features/external-links/external-links.php' => array( 'class' => 'AIAutoTool\Features\ExternalLinks\ExternalLinks', 'active_option' => 'Aiautotool_exLink_backlink_active' ), 'features/submit-index/submit-index.php' => array( 'class' => 'AIAutoTool\Features\SubmitIndex\SubmitIndex', 'active_option' => 'AIAutoTool_SubmitIndex_active' ), 'features/post-exporter/post-exporter.php' => array( 'class' => 'AIAutoTool\Features\PostExporter\PostExporter', 'active_option' => 'Post_Exporter_Plugin_active' ), 'features/keyword-autopost/keyword-autopost.php' => array( 'class' => 'AIAutoTool\Features\KeywordAutopost\KeywordAutopost', 'active_option' => 'Keyword_Autopost_Plugin_active' ), 'features/single-ai/single-ai.php' => array( 'class' => 'AIAutoTool\Features\SingleAI\SingleAI', 'active_option' => 'AIAutoToolsinglepost_active' ), 'features/image-scanner/image-scanner.php' => array( 'class' => 'AIAutoTool\Features\ImageScanner\ImageScanner', 'active_option' => 'AIAutotool_Image404Scanner_active' ), 'features/auto-comment/auto-comment.php' => array( 'class' => 'AIAutoTool\Features\AutoComment\AutoComment', 'active_option' => 'AIautotool_autocomment_active' ), 'features/auto-create-tags/auto-create-tags.php' => array( 'class' => 'AIAutoTool\Features\AutoCreateTags\AutoCreateTags', 'active_option' => 'AIautotool_autocreatetags_active' ), 'features/cloudflare-ai/cloudflare-ai.php' => array( 'class' => 'AIAutoTool\Features\CloudflareAI\CloudflareAI', 'active_option' => 'AI_AutoTool_cloudflareAI_active' ), 'features/suggest-auto/suggest-auto.php' => array( 'class' => 'AIAutoTool\Features\SuggestAuto\SuggestAuto', 'active_option' => 'AI_AutoTool_suggetauto_active' ), 'features/prompt-cpt/prompt-cpt.php' => array( 'class' => 'AIAutoTool\Features\PromptCPT\PromptCPT', 'active_option' => 'AIautotool_Prompt_CPT_active' ), 'features/prompt-customer/prompt-customer.php' => array( 'class' => 'AIAutoTool\Features\PromptCustomer\PromptCustomer', 'active_option' => 'AI_AutoTool_Prompt_Customer_active' ), // Temporarily disabled due to HTML output issues 'features/bot-security/bot-security.php' => array( 'class' => 'AIAutoTool\Features\BotSecurity\BotSecurity', 'active_option' => 'AIAutoToolSecurityBot_active' ), 'features/web-stories/web-stories.php' => array( 'class' => 'AIAutoTool\Features\WebStories\WebStories', 'active_option' => 'AIautotool_Web_Stories_active' ), 'features/install-plugin/install-plugin.php' => array( 'class' => 'AIAutoTool\Features\InstallPlugin\InstallPlugin', 'active_option' => 'Aiautotool_Install_Plugin_active' ), 'features/footer-base/footer-base.php' => array( 'class' => 'AIAutoTool\Features\FooterBase\FooterBase', 'active_option' => 'Aiautotool_footer_base_active' ), 'features/username-generator/username-generator.php' => array( 'class' => 'AIAutoTool\Features\UsernameGenerator\UsernameGenerator', 'active_option' => 'aiautotool_AutoGenerateUsername_active' ), 'features/autoblogging/autoblogging.php' => array( 'class' => 'AIAutoTool\Features\Autoblogging\Autoblogging', 'active_option' => 'AI_AutoTool_Autoblogging_active' ), ); foreach ($feature_files as $file => $config) { $file_path = $inc_dir . $file; $class_name = $config['class']; $active_option = $config['active_option']; // Check if file exists and class is not already loaded if (file_exists($file_path) && !$this->is_class_loaded($class_name)) { // Check if feature is active - use cache to prevent repeated DB queries // Special handling: Cron Status Widget is always active if ($active_option === 'AIAutoTool_Cron_Status_Widget_active') { $is_active = 'true'; // Always active, cannot be disabled // Ensure option is set to true if (!isset($option_cache[$active_option])) { update_option($active_option, 'true'); $option_cache[$active_option] = 'true'; } } else { if (!isset($option_cache[$active_option])) { $option_cache[$active_option] = get_option($active_option, false); } $is_active = $option_cache[$active_option]; } // CRITICAL: Don't instantiate classes here to prevent memory exhaustion // Classes will be loaded on-demand when actually needed // Only require the file to ensure it's available if needed if (!class_exists($class_name)) { // DEBUG MODE: Track memory before and after loading each file if ($debug_mode) { $memory_before = memory_get_usage(true); $memory_before_mb = round($memory_before / 1024 / 1024, 2); error_log("AI Auto Tool DEBUG: [BEFORE] Loading {$file} - Memory: {$memory_before_mb} MB"); } try { require_once $file_path; if ($debug_mode) { $memory_after = memory_get_usage(true); $memory_after_mb = round($memory_after / 1024 / 1024, 2); $memory_diff = round(($memory_after - $memory_before) / 1024 / 1024, 2); $peak_memory = round(memory_get_peak_usage(true) / 1024 / 1024, 2); error_log("AI Auto Tool DEBUG: [AFTER] Loaded {$file} - Memory: {$memory_after_mb} MB (+{$memory_diff} MB) - Peak: {$peak_memory} MB"); // Warn if memory increase is significant if ($memory_diff > 5) { error_log("AI Auto Tool DEBUG: ⚠️ WARNING - {$file} increased memory by {$memory_diff} MB!"); } } } catch (Exception $e) { if ($debug_mode) { error_log("AI Auto Tool DEBUG: ❌ ERROR loading {$file}: " . $e->getMessage()); } // Continue with next file even if one fails continue; } catch (Error $e) { if ($debug_mode) { error_log("AI Auto Tool DEBUG: ❌ FATAL ERROR loading {$file}: " . $e->getMessage()); } // Continue with next file even if one fails continue; } } // DO NOT instantiate here - causes memory exhaustion // Instantiation will happen on-demand via render_all_features() or when feature is actually used /* // Check if class exists if (class_exists($class_name)) { try { $instance = new $class_name(); // Only add classes that have render_feature method if (method_exists($instance, 'render_feature')) { $this->addSubclass($instance); if (defined('WP_DEBUG') && WP_DEBUG) { error_log("AI Auto Tool: Loaded feature {$class_name} from {$file} (active: " . ($is_active ? 'yes' : 'no') . ")"); } } else { if (defined('WP_DEBUG') && WP_DEBUG) { error_log("AI Auto Tool: Skipped {$class_name} - no render_feature method"); } } } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log("AI Auto Tool: Failed to load {$class_name}: " . $e->getMessage()); } } } */ } } if ($debug_mode) { $final_memory = round(memory_get_usage(true) / 1024 / 1024, 2); $peak_memory = round(memory_get_peak_usage(true) / 1024 / 1024, 2); error_log("AI Auto Tool DEBUG: [COMPLETE] load_all_inc_features() finished - Final Memory: {$final_memory} MB - Peak: {$peak_memory} MB"); } $features_loaded = true; } /** * Check if a class is already loaded in subclasses */ private function is_class_loaded($class_name) { foreach ($this->subclasses as $subclass) { if (get_class($subclass) === $class_name) { return true; } } return false; } public function render_plan(){ foreach ($this->subclasses as $subclass) { $subclass->render_plan(); } } /** * Initialize Professional Autoloader System */ private function init_autoloader_system() { // Load Asset Manager FIRST (before other components that may need it) $asset_manager_file = plugin_dir_path(__FILE__) . 'inc/asset-manager.php'; if (file_exists($asset_manager_file)) { require_once $asset_manager_file; } // Load autoloader components $autoloader_files = array( 'inc/autoloader.php', 'inc/class-mapper.php', 'inc/lazy-loader.php', 'inc/optimized-loader.php', 'inc/feature-options.php', 'inc/feature-manager.php', 'inc/migration.php', 'inc/menu-manager.php', // Add menu manager 'inc/class-duplicate-fixer.php', // Add duplicate fixer 'inc/menu-test.php', // Add menu test ); foreach ($autoloader_files as $file) { $file_path = plugin_dir_path(__FILE__) . $file; if (file_exists($file_path)) { require_once $file_path; } } // Initialize autoloader if (class_exists('AIAutoTool_Autoloader')) { AIAutoTool_Autoloader::init(); } // Initialize lazy loader if (class_exists('AIAutoTool_LazyLoader')) { AIAutoTool_LazyLoader::init(); } // Initialize menu manager if (class_exists('AIAutoTool_MenuManager')) { AIAutoTool_MenuManager::init($this); } // Initialize feature options if (class_exists('AIAutoTool_FeatureOptions')) { AIAutoTool_FeatureOptions::init_default_options(); } // CRITICAL FIX: Defer class map generation to avoid memory exhaustion // Only generate on-demand or via admin action, not during plugin initialization // This prevents recursive file scanning that can exhaust memory // The autoloader will work without the generated map using fallback methods /* if (class_exists('AIAutoTool_ClassMapper')) { AIAutoTool_ClassMapper::generateClassMap(); } */ if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: Professional autoloader system initialized'); } } /** * Legacy load_inc method - now uses lazy loading * @deprecated Use AIAutoTool_LazyLoader instead */ public function load_inc() { // Load rendersetting class first (required by many inc classes) $rendersetting_file = plugin_dir_path(__FILE__) . 'lib/setting.php'; if (file_exists($rendersetting_file)) { require_once $rendersetting_file; } // Load essential library classes (required by many inc classes) $essential_lib_files = array( 'lib/aiautotool_notice_control.php', // aiautotool_Warning_Notice 'lib/boxf.php', // AutoToolBox 'lib/bard.php', // BardGenContent 'lib/AIautotool_logall.php', // AIautoTool_log 'lib/feature-descriptions.php', // AiAutoTool_Feature_Descriptions ); foreach ($essential_lib_files as $file) { $file_path = plugin_dir_path(__FILE__) . $file; if (file_exists($file_path)) { require_once $file_path; // Debug: Log when feature-descriptions.php is loaded if ($file === 'lib/feature-descriptions.php') { error_log('AI Auto Tool Debug: feature-descriptions.php loaded successfully'); if (class_exists('AiAutoTool_Feature_Descriptions')) { error_log('AI Auto Tool Debug: AiAutoTool_Feature_Descriptions class exists'); } else { error_log('AI Auto Tool Debug: AiAutoTool_Feature_Descriptions class NOT found after loading file'); } } } else { // Debug: Log if file doesn't exist if ($file === 'lib/feature-descriptions.php') { error_log('AI Auto Tool Debug: feature-descriptions.php file not found at: ' . $file_path); } } } // This method is now handled by the autoloader system // Only load core files immediately (excluding API manager - handled by autoloader) $core_files = array( 'inc/canonical.php', 'inc/ssl.php', ); foreach ($core_files as $file) { $file_path = plugin_dir_path(__FILE__) . $file; if (file_exists($file_path)) { require_once $file_path; } } // Load AI Providers Module (MUST load before features that use AI) $ai_providers_index = plugin_dir_path(__FILE__) . 'inc/ai-providers/index.php'; if (file_exists($ai_providers_index)) { require_once $ai_providers_index; } // Load new Extra Config architecture $extra_config_bootstrap = plugin_dir_path(__FILE__) . 'inc/extra-config/bootstrap.php'; if (file_exists($extra_config_bootstrap)) { require_once $extra_config_bootstrap; } } /** * Legacy load_lib method - now uses lazy loading * @deprecated Use AIAutoTool_LazyLoader instead * FIXED: Only load essential files, not all files in lib directory * This prevents memory exhaustion from loading unnecessary files */ public function load_lib() { // Static flag to prevent multiple loads static $lib_loaded = false; if ($lib_loaded) { return; } // Only load essential library files that are required immediately // Other files will be loaded on-demand by the autoloader $essential_files = array( 'lib/setting.php', // rendersetting class - required by many features 'lib/aiautotool_notice_control.php', // aiautotool_Warning_Notice ); foreach ($essential_files as $file) { $file_path = plugin_dir_path(__FILE__) . $file; if (file_exists($file_path)) { require_once $file_path; } } $lib_loaded = true; // Note: Other lib files will be loaded on-demand via autoloader // This prevents loading all files upfront which causes memory issues } /** * Get autoloader statistics */ public function get_autoloader_stats() { if (class_exists('AIAutoTool_Autoloader')) { return AIAutoTool_Autoloader::getStats(); } return array(); } /** * Get lazy loader statistics */ public function get_lazy_loader_stats() { if (class_exists('AIAutoTool_LazyLoader')) { return AIAutoTool_LazyLoader::getStats(); } return array(); } /** * Force load feature */ public function load_feature($feature_name) { if (class_exists('AIAutoTool_LazyLoader')) { return AIAutoTool_LazyLoader::loadFeature($feature_name); } return false; } /** * Check if feature is loaded */ public function is_feature_loaded($feature_name) { if (class_exists('AIAutoTool_LazyLoader')) { return AIAutoTool_LazyLoader::isFeatureLoaded($feature_name); } return false; } /** * Legacy method for backward compatibility * Assets are now managed by Asset Manager (inc/asset-manager.php) * This method is kept for any external code that might call it directly * * @deprecated Use AIAutoTool_Asset_Manager instead */ public function add_aiautotool_button_js() { // Asset Manager now handles this, but we keep this method for backward compatibility // Assets will be loaded automatically by Asset Manager on plugin pages if (defined('WP_DEBUG') && WP_DEBUG) { error_log('AI Auto Tool: add_aiautotool_button_js() called (deprecated - use Asset Manager)'); } } /** * Ensure scripts are loaded for integrations page * Assets are now handled by Asset Manager * * @deprecated Use AIAutoTool_Asset_Manager instead */ public function ensure_integrations_scripts($hook) { // Asset Manager now handles this automatically // This method is kept for backward compatibility } public function add_menu_page() { add_menu_page( ' Ai Auto Tool', ' Ai Auto Tool', 'manage_options', MENUSUBPARRENT, array( $this, 'menu_page' ), 'data:image/svg+xml;base64,' . base64_encode(file_get_contents(plugin_dir_path(__FILE__) . '/images/logo.svg')), 3 ); add_submenu_page( MENUSUBPARRENT, ' Integrations', ' Integrations', 'manage_options', 'aiautotool_integrations', array($this, 'aiautotool_integrations') ); } public function aiautotool_integrations(){ ?>

subclasses as $subclass) { if ($subclass instanceof aiautotool_SSL_active) { $subclass->render_setting(); return; } } echo '

SSL Settings

SSL class not found. Please check if the SSL feature is properly loaded.

'; } public function menu_page() { $this->config_page(); } function is_free_plan() { if ( ! aiautotool_premium()->is_registered() ) { return true; } if ( ! aiautotool_premium()->has_paid_plan() ) { return true; } return ( 'free' === aiautotool_premium()->get_plan_name() || ! aiautotool_premium()->has_features_enabled_license() ); } public function config_page() { if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.','ai-auto-tool')); } $api_key_list = get_option('aiautotool_api_key_list', array()); $config_img = get_option('aiautotool_config_img', false); $aiautotool_images_list = get_option('aiautotool_images_list', []); $users = get_users(); if (isset($_POST['aiautotool_add_key'])) { $new_key = 'KCT-'.uniqid(); $user_id = sanitize_text_field($_POST['aiautotool_user']); $api_key_list = get_option('aiautotool_api_key_list', array()); $api_key_list[] = array( 'key' => $new_key, 'user_id' => $user_id, ); update_option('aiautotool_api_key_list', $api_key_list,null, 'no'); echo esc_html('

New API key added.

'); } if (isset($_POST['aiautotool_save_config'])) { if(isset($_POST['aiautotool_config_img'])){ $config_img = sanitize_text_field($_POST['aiautotool_config_img']); update_option('aiautotool_config_img', $config_img,null, 'no'); } } if (isset($_POST['aiautotool_remove_api_key'])) { $remove_key = sanitize_text_field($_POST['aiautotool_remove_api_key']); unset($api_key_list[$remove_key]); update_option('aiautotool_api_key_list', $api_key_list,null, 'no'); } if (isset($_POST['aiautotool_remove_log_img'])) { update_option('aiautotool_images_list', [],null, 'no'); $aiautotool_images_list = get_option('aiautotool_images_list', []); echo esc_html('

Reset log Images Success!!!!.

'); } if (isset($_POST['aiautotool_remove_img_log_item'])) { $remove_key = sanitize_text_field($_POST['aiautotool_remove_img_log_item']); unset($aiautotool_images_list[$remove_key]); update_option('aiautotool_images_list', $aiautotool_images_list,null, 'no'); echo esc_html('

Remove log item image Success!!!!.

'); } $this->aiautotool_config_settings = get_option('aiautotool_code_settings',array()); if(isset($_POST['aiautotool_code_settings'])){ foreach($_POST['aiautotool_code_settings'] as $key => $value){ if($key!='btnall'){ $this->aiautotool_config_settings[$key] = $value; } } $result = update_option('aiautotool_code_settings',(array )$this->aiautotool_config_settings,null, 'no'); $this->aiautotool_config_settings = get_option('aiautotool_code_settings',array()); } ?>

render_subscription_info(); ?>
render_setting(); } ?>
'; echo '
'; echo "

Domain: ".esc_html($domain)."

"; echo "

Plugin Version: " . esc_html(AIAUTOTOOL_VS) . "

"; echo '
'; $dt = $this->aiautotool_getdata(); if ($this->is_free_plan()) { $accountType = 'Free'; echo '
'; echo "

Current Plan: ".esc_html($accountType)."

"; echo '
'; echo '

Total limit: ' . esc_html(AIAUTOTOOL_FREE) . ' Request (Post, Tag, Comment)

'; echo '
'; echo '
'; echo ' Total Usage:'; echo '
'; $usage_percentage = min(100, ($dt['usage'] / AIAUTOTOOL_FREE) * 100); echo '
'; echo '
'; echo '' . esc_html($dt['usage']) . ''; echo '
'; echo '
'; echo ''; echo ' Upgrade Pro'; echo ''; // Add button to open Freemius license activation modal $fs_unique_affix = aiautotool_premium()->get_unique_affix(); echo '

' . '' . esc_html__( 'Activate License', 'ai-auto-tool' ) . '' . '

'; // Ensure the activation modal is available on this page if ( function_exists( 'fs_require_once_template' ) ) { $vars = array( 'id' => aiautotool_premium()->get_id() ); fs_require_once_template( 'forms/license-activation.php', $vars ); } } else { $fs = rendersetting::is_premium(); $accountType = $fs->get_plan_title(); // Safely get plan_id with null checks $plan_id = null; try { $license = aiautotool_premium()->_get_license(); if ($license && isset($license->id)) { $subscription = aiautotool_premium()->_get_subscription($license->id); if ($subscription && isset($subscription->plan_id)) { $plan_id = $subscription->plan_id; } } } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('Error getting plan_id: ' . $e->getMessage()); } } echo '
'; echo "

Current Plan: ".esc_html($accountType)."

"; if($plan_id && $plan_id == 25184){ echo '
'; echo '

Total limit: 5000 Request (Post, Tag, Comment)

'; echo '
'; }else{ echo '
'; echo '

Total limit: Unlimited Request (Post, Tag, Comment)

'; echo '
'; } echo '
'; echo ' Total Usage:'; echo '
'; $usage_percentage = min(100, ($dt['usage'] / 100) * 100); // Adjust based on plan echo '
'; echo '
'; echo '' . esc_html($dt['usage']) . ''; echo '
'; echo '
'; } echo '
'; echo '

' . esc_html__('Subscription features Auto ', 'ai-auto-tool') . '

'; self::render_plan(); echo '
'; echo '
'; } public function create_post_route() { register_rest_route( 'aiautotool', '/createpost', array( 'methods' => 'POST', 'callback' => array($this,'aiautotool_insert_post_ajax'), 'permission_callback' => array($this, 'rest_api_permission_check') ) ); register_rest_route( 'aiautotool', '/get_cate', array( 'methods' => 'GET', 'callback' => array($this,'aiautotool_get_cate'), 'permission_callback' => array($this, 'rest_api_permission_check') )); register_rest_route( 'aiautotool', '/media', array( 'methods' => 'GET', 'callback' => array($this,'get_all_media_callback'), 'permission_callback' => array($this, 'rest_api_permission_check') )); } /** * REST API permission callback - check API key or user capability */ public function rest_api_permission_check($request) { // Check if API key is provided $api_key = $request->get_param('key') ?: $request->get_header('X-API-Key'); if (!empty($api_key)) { // Validate API key $api_key_list = get_option('aiautotool_api_key_list', array()); foreach ($api_key_list as $stored_key) { if ($api_key == $stored_key['key']) { return true; } } return false; } // Fallback: require user to be logged in with edit_posts capability return is_user_logged_in() && current_user_can('edit_posts'); } public function register_settings() { register_setting( 'ai_auto_tool_api_keys', 'ai_auto_tool_api_keys', array( 'type' => 'array', 'sanitize_callback' => array( $this, 'sanitize_array_setting' ), ) ); register_setting( 'ai_auto_tool_log', 'ai_auto_tool_log', array( 'type' => 'array', 'sanitize_callback' => array( $this, 'sanitize_array_setting' ), ) ); } /** * Sanitize array settings * * @param mixed $value Input value * @return array Sanitized array */ public function sanitize_array_setting( $value ) { if ( ! is_array( $value ) ) { return array(); } return map_deep( $value, 'sanitize_text_field' ); } public function aiautotool_insert_post_ajax() { // Check permissions for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } } else { // For REST API requests, check API key and permissions // The API key validation below will handle REST API permissions } // Lấy dữ liệu POST hoặc từ REST API request $request_data = $_POST; if (empty($request_data) && isset($_REQUEST)) { $request_data = $_REQUEST; } $name = isset($request_data['name']) ? sanitize_text_field($request_data['name']) : ''; $detail = isset($request_data['detail']) ? wp_kses_post($request_data['detail']) : ''; $category_name = isset($request_data['category']) ? sanitize_text_field($request_data['category']) : ''; $tags = isset($request_data['tags']) ? sanitize_text_field($request_data['tags']) : ''; $date = isset($request_data['date']) ? sanitize_text_field($request_data['date']) : ''; $key = isset($request_data['key']) ? sanitize_text_field($request_data['key']) : ''; // For REST API requests, validate API key first if (!defined('DOING_AJAX') || !DOING_AJAX) { if (empty($key)) { return new WP_Error('missing_api_key', __('API key is required', 'ai-auto-tool'), array('status' => 403)); } // Validate API key exists $api_key_list = get_option('aiautotool_api_key_list', array()); $valid_key = false; foreach ($api_key_list as $api_key) { if ($key == $api_key['key']) { $valid_key = true; break; } } if (!$valid_key) { return new WP_Error('invalid_api_key', __('Invalid API key', 'ai-auto-tool'), array('status' => 403)); } } $postname = AIAutoTool_Utilities::sanitize_title($name); $user_id = ''; $user_ids = get_users( array( 'fields' => 'ID', ) ); $random_user_id = $user_ids[array_rand($user_ids)]; $api_key_list = get_option('aiautotool_api_key_list', array()); if (count($api_key_list)>0) { foreach ($api_key_list as $k=>$api_key){ if ($key==$api_key['key']) { $user_id = $random_user_id;//rand(1, 11);//$api_key['user_id']; $config_img = get_option('aiautotool_config_img', false); if($config_img){ $aiautotool_images_list = get_option('aiautotool_images_list', []); $html = str_replace('\"', '"', $detail); $arrayImageUpload = preg_match_all('/]+src\s*=\s*["\']([^"\']+)["\']/i', stripslashes($html), $matches) ? $matches[1] : []; $attachThumbnail = 0; if (!empty($arrayImageUpload)){ foreach ($arrayImageUpload as $post_image_url){ $image_item = null; foreach ($aiautotool_images_list as $item) { if ($item['url_remote'] === $post_image_url) { $image_item = $item; break; } } if ($image_item !== null) { $image_url_new = $image_item['url_image_new']['url_out']; $detail = str_replace($post_image_url, $image_url_new, $detail); if ($attachThumbnail == 0) { $attachThumbnail = $image_item['url_image_new']['attach_id']; } }else{ try { $image_url_new = AIAutoTool_Utilities::save_image($post_image_url,$postname); if (!empty($image_url_new)){ $imgUploaded[] = $image_url_new; if ($attachThumbnail == 0) { $attachThumbnail = $image_url_new['attach_id']; } $aiautotool_images_list[] = [ 'url_remote' => $post_image_url, 'url_image_new' => $image_url_new, ]; update_option('aiautotool_images_list', $aiautotool_images_list,null, 'no'); } }catch (Exception $e) { } } } } foreach ($imgUploaded as $img){ $detail = str_replace($img['url'],$img['baseurl'],$detail); } } $category = get_category_by_slug($category_name); $category_id = $category->term_id; // Insert the post $post_id = wp_insert_post(array( 'post_title' => $name, 'post_content' => $detail, 'post_category' => array($category_id), 'tags_input' => $tags, 'post_status' => 'publish', 'post_author'=>$user_id, 'post_date' => $date, 'meta_input' => array( 'key' => $key, ), 'post_type' => 'post', )); // Return the URL of the new post if ($post_id) { if ($attachThumbnail != 0) { set_post_thumbnail($post_id, $attachThumbnail); } $post_url = get_permalink($post_id); echo json_encode(array('url' => $post_url)); } else { echo json_encode(array('error' => 'Failed to insert post.')); } } } } wp_die(); } public function aiautotool_get_cate() { header('Content-Type: application/json; charset=utf-8'); // Check permissions for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } } if ( isset( $_GET['key'] ) || isset( $_REQUEST['key'] ) ) { $key = isset($_GET['key']) ? sanitize_text_field($_GET['key']) : sanitize_text_field($_REQUEST['key']); $api_key_list = get_option('aiautotool_api_key_list', array()); if (count($api_key_list)>0) { foreach ($api_key_list as $k=>$api_key){ if ($key==$api_key['key']) { $categories = get_categories(); $categories_array = array(); foreach ( $categories as $category ) { $categories_array[] = array( 'id' => $category->cat_ID, 'name' => $category->name, 'slug' => $category->slug ); } echo json_encode( $categories_array ); die(); } } } } else { wp_send_json_error( ' key not in AJAX.' ); } die(); } public function get_all_media_callback() { // Check permissions for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('upload_files')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } } $key = isset($_GET['key']) ? sanitize_text_field($_GET['key']) : (isset($_REQUEST['key']) ? sanitize_text_field($_REQUEST['key']) : ''); $api_key_list = get_option('aiautotool_api_key_list', array()); if (count($api_key_list)>0) { foreach ($api_key_list as $k=>$api_key){ if ($key==$api_key['key']) { $args = array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'post_status' => 'inherit', 'posts_per_page' => - 1, ); $media_query = new WP_Query( $args ); $media = array(); if ( $media_query->have_posts() ) { while ( $media_query->have_posts() ) { $media_query->the_post(); $media[] = array( 'id' => get_the_ID(), 'title'=> get_the_title(), 'url' => wp_get_attachment_url(), 'type' => get_post_mime_type(), ); } wp_reset_postdata(); wp_send_json( $media ); die(); }else{ $arr = array('ok'=>'notfindimg'); wp_send_json( $arr ); die(); } } } } die(); } public function aiautotool_save_image(){ // Check permissions if (defined('DOING_AJAX') && DOING_AJAX) { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } } $reponse = array(); if(!empty($_POST['link_img'])){ $link_img = sanitize_text_field($_POST['link_img']); $postId = sanitize_text_field($_POST['postId']); $postTitle = sanitize_text_field($_POST['postTitle']); $i = sanitize_text_field($_POST['i']); if(strpos( $link_img,$_SERVER['HTTP_HOST']) !== false){ //echo $link_img; $av = array( 'stt'=>'ok', 'linkedit'=>$link_img ); }else{ // $imagenew = upload_image($postTitle,$link_img,$postId,$i); $imagenews = AIAutoTool_Utilities::save_image($link_img,$postTitle); $imagenew = $imagenews['url_out']; $av = array( 'stt'=>'ok', 'linkedit'=>$imagenew ); } }else{ $av = array( 'stt'=>'notok', 'linkedit'=>'' ); } header( "Content-Type: application/json" ); echo json_encode($av); exit(); } /** * SSL Management AJAX Callbacks are handled in SSL Manager class (inc/features/ssl-manager/ssl.php) * Removed duplicate implementations here to avoid conflicts */ /** * AJAX callback for bardcontentmore endpoint - avoids CORS issues */ public function aiautotool_bard_contentmore_callback() { // Verify nonce for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { // Use wp_verify_nonce instead of check_ajax_referer to avoid 403 die if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) { wp_send_json(array( 'code' => '403', 'msg' => __('Security check failed. Please refresh the page and try again.', 'ai-auto-tool'), 'result' => '' )); wp_die(); } if (!current_user_can('edit_posts')) { wp_send_json(array( 'code' => '403', 'msg' => __('Permission denied', 'ai-auto-tool'), 'result' => '' )); wp_die(); } } // Get data from WordPress AJAX (can be in 'data' field or raw POST) $data = array(); // Try to get from 'data' field (sent as JSON string) if (isset($_POST['data']) && is_string($_POST['data'])) { $data = json_decode(stripslashes($_POST['data']), true); } else { // Try raw POST data $raw_data = file_get_contents('php://input'); $data = json_decode($raw_data, true); } if (!$data || !is_array($data)) { wp_send_json(array( 'code' => '400', 'msg' => 'Invalid JSON data', 'result' => '' )); wp_die(); } // Extract parameters $question = isset($data['question']) ? sanitize_textarea_field($data['question']) : ''; $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'Vietnamese'; $domain = isset($data['domain']) ? sanitize_text_field($data['domain']) : ''; $model = isset($data['model']) ? sanitize_text_field($data['model']) : 'gemini'; $info = isset($data['info']) ? $data['info'] : array(); if (empty($question)) { wp_send_json(array( 'code' => '400', 'msg' => 'Question parameter is required', 'result' => '' )); wp_die(); } // Use BardGenContent class to make server-side request require_once plugin_dir_path(__FILE__) . 'lib/bard.php'; $bardGenContent = new BardGenContent(); try { // Debug log request info if (defined('WP_DEBUG') && WP_DEBUG) { error_log('=== aiautotool_bard_contentmore_callback() DEBUG ==='); error_log('Question: ' . $question); error_log('Language: ' . $lang); error_log('Domain: ' . $domain); error_log('Model: ' . $model); } // Call the bardcontentmore method which handles the API call $result = $bardGenContent->bardcontentmore($question, $lang); // Check if result is an array with error code (from API server) if (is_array($result) && isset($result['code']) && isset($result['msg'])) { // API returned error response (code 201-207, etc.) if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API returned error code: ' . $result['code']); error_log('API error message: ' . $result['msg']); } wp_send_json(array( 'code' => $result['code'], 'msg' => $result['msg'], 'result' => isset($result['result']) ? $result['result'] : false )); wp_die(); } // Debug log result info if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API Result Type: ' . gettype($result)); error_log('API Result Length: ' . (is_string($result) ? strlen($result) : 'N/A')); error_log('API Result Preview: ' . (is_string($result) ? substr($result, 0, 200) : json_encode($result))); } if ($result !== null && $result !== '' && $result !== false) { $response = array( 'code' => '200', 'msg' => 'Success', 'result' => $result ); // Add debug info if WP_DEBUG is enabled if (defined('WP_DEBUG') && WP_DEBUG) { $response['debug'] = array( 'question' => $question, 'lang' => $lang, 'result_length' => is_string($result) ? strlen($result) : 0, 'result_type' => gettype($result), 'timestamp' => current_time('mysql') ); } wp_send_json($response); } else { $error_response = array( 'code' => '500', 'msg' => 'Failed to generate content - API returned empty result', 'result' => '' ); if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API returned empty/null result'); $error_response['debug'] = array( 'question' => $question, 'lang' => $lang, 'error' => 'Empty result from API' ); } wp_send_json($error_response); } } catch (Exception $e) { $error_msg = 'Error: ' . $e->getMessage(); if (defined('WP_DEBUG') && WP_DEBUG) { error_log('Exception in aiautotool_bard_contentmore_callback: ' . $e->getMessage()); error_log('Stack trace: ' . $e->getTraceAsString()); } $error_response = array( 'code' => '500', 'msg' => $error_msg, 'result' => '' ); if (defined('WP_DEBUG') && WP_DEBUG) { $error_response['debug'] = array( 'exception' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ); } wp_send_json($error_response); } wp_die(); } /** * AJAX callback for bardcontent endpoint - avoids CORS issues */ public function aiautotool_bard_content_callback() { // Verify nonce for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { // Use wp_verify_nonce instead of check_ajax_referer to avoid 403 die if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) { wp_send_json(array( 'code' => '403', 'msg' => __('Security check failed. Please refresh the page and try again.', 'ai-auto-tool'), 'result' => '' )); wp_die(); } if (!current_user_can('edit_posts')) { wp_send_json(array( 'code' => '403', 'msg' => __('Permission denied', 'ai-auto-tool'), 'result' => '' )); wp_die(); } } // Get data from WordPress AJAX (can be in 'data' field or raw POST) $data = array(); // Try to get from 'data' field (sent as JSON string) if (isset($_POST['data']) && is_string($_POST['data'])) { $data = json_decode(stripslashes($_POST['data']), true); } else { // Try raw POST data $raw_data = file_get_contents('php://input'); $data = json_decode($raw_data, true); } if (!$data || !is_array($data)) { wp_send_json(array( 'code' => '400', 'msg' => 'Invalid JSON data', 'result' => '' )); wp_die(); } // Extract parameters $question = isset($data['question']) ? sanitize_textarea_field($data['question']) : ''; $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'Vietnamese'; if (empty($question)) { wp_send_json(array( 'code' => '400', 'msg' => 'Question parameter is required', 'result' => '' )); wp_die(); } // Use BardGenContent class to make server-side request require_once plugin_dir_path(__FILE__) . 'lib/bard.php'; $bardGenContent = new BardGenContent(); try { // Debug log request info if (defined('WP_DEBUG') && WP_DEBUG) { error_log('=== aiautotool_bard_content_callback() DEBUG ==='); error_log('Question: ' . $question); error_log('Language: ' . $lang); } // Call the bardcontent method $result = $bardGenContent->bardcontent($question, $lang); // Check if result is an array with error code (from API server) if (is_array($result) && isset($result['code']) && isset($result['msg'])) { // API returned error response (code 201-207, etc.) if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API returned error code: ' . $result['code']); error_log('API error message: ' . $result['msg']); } wp_send_json(array( 'code' => $result['code'], 'msg' => $result['msg'], 'result' => isset($result['result']) ? $result['result'] : false )); wp_die(); } // Debug log result info if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API Result Type: ' . gettype($result)); error_log('API Result Length: ' . (is_string($result) ? strlen($result) : 'N/A')); error_log('API Result Preview: ' . (is_string($result) ? substr($result, 0, 200) : json_encode($result))); } if ($result !== null && $result !== '' && $result !== false) { $response = array( 'code' => '200', 'msg' => 'Success', 'result' => $result ); // Add debug info if WP_DEBUG is enabled if (defined('WP_DEBUG') && WP_DEBUG) { $response['debug'] = array( 'question' => $question, 'lang' => $lang, 'result_length' => is_string($result) ? strlen($result) : 0, 'result_type' => gettype($result), 'timestamp' => current_time('mysql') ); } wp_send_json($response); } else { $error_response = array( 'code' => '500', 'msg' => 'Failed to generate content - API returned empty result', 'result' => '' ); if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API returned empty/null result'); $error_response['debug'] = array( 'question' => $question, 'lang' => $lang, 'error' => 'Empty result from API' ); } wp_send_json($error_response); } } catch (Exception $e) { $error_msg = 'Error: ' . $e->getMessage(); if (defined('WP_DEBUG') && WP_DEBUG) { error_log('Exception in aiautotool_bard_content_callback: ' . $e->getMessage()); error_log('Stack trace: ' . $e->getTraceAsString()); } $error_response = array( 'code' => '500', 'msg' => $error_msg, 'result' => '' ); if (defined('WP_DEBUG') && WP_DEBUG) { $error_response['debug'] = array( 'exception' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ); } wp_send_json($error_response); } wp_die(); } /** * AJAX callback for bardrewrite endpoint - avoids CORS issues */ public function aiautotool_bard_rewrite_callback() { // Verify nonce for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { // Use wp_verify_nonce instead of check_ajax_referer to avoid 403 die if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) { wp_send_json(array( 'code' => '403', 'msg' => __('Security check failed. Please refresh the page and try again.', 'ai-auto-tool'), 'result' => '' )); wp_die(); } if (!current_user_can('edit_posts')) { wp_send_json(array( 'code' => '403', 'msg' => __('Permission denied', 'ai-auto-tool'), 'result' => '' )); wp_die(); } } // Get data from WordPress AJAX (can be in 'data' field or raw POST) $data = array(); // Try to get from 'data' field (sent as JSON string) if (isset($_POST['data']) && is_string($_POST['data'])) { $data = json_decode(stripslashes($_POST['data']), true); } else { // Try raw POST data $raw_data = file_get_contents('php://input'); $data = json_decode($raw_data, true); } if (!$data || !is_array($data)) { wp_send_json(array( 'code' => '400', 'msg' => 'Invalid JSON data', 'result' => '' )); wp_die(); } // Extract parameters $question = isset($data['question']) ? sanitize_textarea_field($data['question']) : ''; $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'Vietnamese'; $toneOfVoice = isset($data['toneOfVoice']) ? sanitize_text_field($data['toneOfVoice']) : ''; if (empty($question)) { wp_send_json(array( 'code' => '400', 'msg' => 'Question parameter is required', 'result' => '' )); wp_die(); } // Use BardGenContent class to make server-side request require_once plugin_dir_path(__FILE__) . 'lib/bard.php'; $bardGenContent = new BardGenContent(); try { // Debug log request info if (defined('WP_DEBUG') && WP_DEBUG) { error_log('=== aiautotool_bard_rewrite_callback() DEBUG ==='); error_log('Question: ' . $question); error_log('Language: ' . $lang); error_log('Tone of Voice: ' . $toneOfVoice); } // Call the bardrewrite method $result = $bardGenContent->bardrewrite($question, $lang, $toneOfVoice); // Check if result is an array with error code (from API server) if (is_array($result) && isset($result['code']) && isset($result['msg'])) { // API returned error response (code 201-207, etc.) if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API returned error code: ' . $result['code']); error_log('API error message: ' . $result['msg']); } wp_send_json(array( 'code' => $result['code'], 'msg' => $result['msg'], 'result' => isset($result['result']) ? $result['result'] : false )); wp_die(); } // Debug log result info if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API Result Type: ' . gettype($result)); error_log('API Result Length: ' . (is_string($result) ? strlen($result) : 'N/A')); error_log('API Result Preview: ' . (is_string($result) ? substr($result, 0, 200) : json_encode($result))); } if ($result !== null && $result !== '' && $result !== false) { $response = array( 'code' => '200', 'msg' => 'Success', 'result' => $result ); // Add debug info if WP_DEBUG is enabled if (defined('WP_DEBUG') && WP_DEBUG) { $response['debug'] = array( 'question' => $question, 'lang' => $lang, 'toneOfVoice' => $toneOfVoice, 'result_length' => is_string($result) ? strlen($result) : 0, 'result_type' => gettype($result), 'timestamp' => current_time('mysql') ); } wp_send_json($response); } else { $error_response = array( 'code' => '500', 'msg' => 'Failed to rewrite content - API returned empty result', 'result' => '' ); if (defined('WP_DEBUG') && WP_DEBUG) { error_log('API returned empty/null result'); $error_response['debug'] = array( 'question' => $question, 'lang' => $lang, 'toneOfVoice' => $toneOfVoice, 'error' => 'Empty result from API' ); } wp_send_json($error_response); } } catch (Exception $e) { $error_msg = 'Error: ' . $e->getMessage(); if (defined('WP_DEBUG') && WP_DEBUG) { error_log('Exception in aiautotool_bard_rewrite_callback: ' . $e->getMessage()); error_log('Stack trace: ' . $e->getTraceAsString()); } $error_response = array( 'code' => '500', 'msg' => $error_msg, 'result' => '' ); if (defined('WP_DEBUG') && WP_DEBUG) { $error_response['debug'] = array( 'exception' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ); } wp_send_json($error_response); } wp_die(); } } new AI_Auto_Tool(); function aiautotool_load_func() { $inc_directory = plugin_dir_path(__FILE__) . 'func'; $inc_files = glob($inc_directory . '/*.php'); // print_r($inc_files); if ($inc_files) { foreach ($inc_files as $file) { if (is_file($file)) { include $file; } } } } aiautotool_load_func(); } add_filter('auto_update_plugin_ai-auto-tool', '__return_true');