'; public $limit = AIAUTOTOOL_FREE; private $plan_limit_aiautotool ; public $name_plan ; public $config = array(); public $notice ; // Track last AI call time to ensure minimum 10 seconds between calls private static $last_ai_call_time = 0; private function aiautotool_is_post_editor_context() { if (!is_admin() || wp_doing_ajax()) { return false; } $screen = function_exists('get_current_screen') ? get_current_screen() : null; if ($screen && in_array($screen->base, array('post', 'page', 'post-new', 'page-new'), true)) { return true; } global $pagenow; return in_array($pagenow, array('post.php', 'post-new.php'), true); } private function aiautotool_get_lightweight_provider_models() { $providers_option = get_option('aikct_ai_providers', array()); $active_provider = get_option('aiautotool_active_ai_provider', ''); $active_model = get_option('aiautotool_active_ai_model', ''); $providers = array(); $provider_names = array( 'openai' => 'OpenAI', 'gemini' => 'Google Gemini', 'pollinations' => 'Pollinations.ai', 'llm7' => 'LLM7.io', 'huggingface' => 'HuggingFace', 'cloudflare' => 'Cloudflare', 'anthropic' => 'Anthropic Claude', 'azure_openai' => 'Azure OpenAI', 'openrouter' => 'OpenRouter', '9router' => '9Router', 'groq' => 'Groq', 'deepseek' => 'DeepSeek', 'mistral' => 'Mistral AI', 'together' => 'Together AI', 'fireworks' => 'Fireworks AI', 'perplexity' => 'Perplexity', 'xai' => 'xAI', 'ollama' => 'Ollama Local', ); if (is_array($providers_option)) { foreach ($providers_option as $provider_id => $provider_config) { if (!is_array($provider_config)) { continue; } $enabled = !empty($provider_config['enabled']); $has_key = !empty($provider_config['api_key']) || !empty($provider_config['api_keys']) || $provider_id === 'pollinations' || $provider_id === '9router' || $provider_id === 'ollama'; $model = !empty($provider_config['model']) ? (string) $provider_config['model'] : ''; if (!$enabled && $provider_id !== $active_provider) { continue; } if (!$has_key && $provider_id !== $active_provider) { continue; } if ($model === '' && $provider_id === $active_provider) { $model = $active_model; } if ($model === '') { continue; } $providers[$provider_id] = array( 'id' => $provider_id, 'name' => isset($provider_names[$provider_id]) ? $provider_names[$provider_id] : ucwords(str_replace(array('_', '-'), ' ', $provider_id)), 'configured' => true, 'models' => array($model => $model), 'default_model' => $model, 'capabilities' => array('text_generation'), ); } } if ($active_provider !== '' && $active_model !== '' && empty($providers[$active_provider])) { $providers[$active_provider] = array( 'id' => $active_provider, 'name' => isset($provider_names[$active_provider]) ? $provider_names[$active_provider] : ucwords(str_replace(array('_', '-'), ' ', $active_provider)), 'configured' => true, 'models' => array($active_model => $active_model), 'default_model' => $active_model, 'capabilities' => array('text_generation'), ); } return $providers; } /** * Update AI_post_usage counter after successful article generation * This increments the usage counter for the "AI Posts" feature */ private function aiautotool_update_ai_post_usage() { // Get current usage value $current_value = get_option('AI_post_usage', 0); // Increment by 1 $new_value = $current_value + 1; // Update the option (autoload = 'no' for better performance) update_option('AI_post_usage', $new_value, 'no'); if (defined('WP_DEBUG') && WP_DEBUG) { } return $new_value; } private function aiautotool_get_ai_provider_model_options($include_auto = true) { $options = array(); if ($include_auto) { $options[] = array( 'value' => '', 'label' => __('Auto - use AI Provider settings', 'ai-auto-tool'), 'selected' => true, ); } if ($this->aiautotool_is_post_editor_context()) { $providers_info = $this->aiautotool_get_lightweight_provider_models(); $active_provider_id = get_option('aiautotool_active_ai_provider', ''); $active_model = get_option('aiautotool_active_ai_model', ''); foreach ($providers_info as $provider_id => $provider_info) { foreach ($provider_info['models'] as $model_id => $model_name) { $options[] = array( 'value' => $provider_id . '::' . $model_id, 'label' => sprintf('%s - %s', $provider_info['name'], $model_name ? $model_name : $model_id), 'selected' => !$include_auto && $provider_id === $active_provider_id && $model_id === $active_model, ); } } return $options; } if (!class_exists('AIAutotool_AI_Provider_Manager')) { $manager_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_provider_manager.php'; if (file_exists($manager_file)) { require_once $manager_file; } } if (!class_exists('AIAutotool_AI_Provider_Manager')) { return $options; } $manager = AIAutotool_AI_Provider_Manager::get_instance(); $providers_info = $manager->get_providers_info(); $active_provider = $manager->get_active_provider(); $active_provider_id = $active_provider ? $active_provider->get_id() : ''; $active_model = $manager->get_active_model(); foreach ($providers_info as $provider_id => $provider_info) { if (empty($provider_info['configured']) || empty($provider_info['models']) || !is_array($provider_info['models'])) { continue; } $provider_name = !empty($provider_info['name']) ? $provider_info['name'] : $provider_id; foreach ($provider_info['models'] as $model_id => $model_name) { $model_id = (string) $model_id; if ($model_id === '') { continue; } $is_active = !$include_auto && $provider_id === $active_provider_id && $model_id === $active_model; $options[] = array( 'value' => $provider_id . '::' . $model_id, 'label' => sprintf('%s - %s', $provider_name, $model_name ? $model_name : $model_id), 'selected' => $is_active, ); } } if (count($options) === ($include_auto ? 1 : 0)) { $options[] = array( 'value' => '', 'label' => __('No configured AI Provider. Add API key first.', 'ai-auto-tool'), 'selected' => !$include_auto, ); } return $options; } private function aiautotool_render_ai_provider_model_options($include_auto = true) { foreach ($this->aiautotool_get_ai_provider_model_options($include_auto) as $option) { printf( '', esc_attr($option['value']), !empty($option['selected']) ? ' selected' : '', esc_html($option['label']) ); } } public function aiautotool_get_ai_provider_js_settings() { $settings = array( 'ai_providers' => array(), 'ai_image_providers' => array(), 'active_ai_provider' => '', 'active_ai_model' => '', 'ai_provider_routing_mode' => 'single', 'ai_execution_mode' => 'agent', 'ai_voice' => array(), ); if ($this->aiautotool_is_post_editor_context()) { $settings['ai_providers'] = $this->aiautotool_get_lightweight_provider_models(); $settings['active_ai_provider'] = get_option('aiautotool_active_ai_provider', ''); $settings['active_ai_model'] = get_option('aiautotool_active_ai_model', ''); $routing_mode = get_option('aiautotool_ai_provider_routing_mode', 'single'); $settings['ai_provider_routing_mode'] = in_array($routing_mode, array('single', 'rotate'), true) ? $routing_mode : 'single'; $execution_mode = get_option('aiautotool_ai_execution_mode', 'agent'); $settings['ai_execution_mode'] = in_array($execution_mode, array('agent', 'direct_api'), true) ? $execution_mode : 'agent'; return $settings; } if (!class_exists('AIAutotool_AI_Provider_Manager')) { $manager_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_provider_manager.php'; if (file_exists($manager_file)) { require_once $manager_file; } } if (!class_exists('AIAutotool_AI_Provider_Manager')) { return $settings; } $manager = AIAutotool_AI_Provider_Manager::get_instance(); $active_provider = $manager->get_active_provider(); $settings['ai_providers'] = $manager->get_providers_info(); $settings['ai_image_providers'] = method_exists($manager, 'get_image_providers_info') ? $manager->get_image_providers_info() : array(); $settings['active_ai_provider'] = $active_provider ? $active_provider->get_id() : ''; $settings['active_ai_model'] = $manager->get_active_model(); $settings['ai_provider_routing_mode'] = method_exists($manager, 'get_provider_routing_mode') ? $manager->get_provider_routing_mode() : 'single'; $execution_mode = get_option('aiautotool_ai_execution_mode', 'agent'); $settings['ai_execution_mode'] = in_array($execution_mode, array('agent', 'direct_api'), true) ? $execution_mode : 'agent'; if (class_exists('AIAutotool_AI_Voice_Manager')) { $settings['ai_voice'] = AIAutotool_AI_Voice_Manager::get_instance()->get_config(); } else { $voice_manager_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_voice_manager.php'; if (file_exists($voice_manager_file)) { require_once $voice_manager_file; if (class_exists('AIAutotool_AI_Voice_Manager')) { $settings['ai_voice'] = AIAutotool_AI_Voice_Manager::get_instance()->get_config(); } } } return $settings; } private function aiautotool_resolve_provider_model_selection($model_value, $provider_id = '') { $model_value = sanitize_text_field((string) $model_value); $provider_id = sanitize_text_field((string) $provider_id); if (strpos($model_value, '::') !== false) { list($provider_id, $model_value) = array_pad(explode('::', $model_value, 2), 2, ''); $provider_id = sanitize_text_field($provider_id); $model_value = sanitize_text_field($model_value); } if ($model_value === 'auto' || $model_value === 'provider-default' || $model_value === 'gemini' || $model_value === 'chatgpt') { $model_value = ''; } return array( 'provider_id' => $provider_id, 'model' => $model_value, ); } private static $min_ai_call_interval = 10; // Minimum seconds between AI calls public function __construct() { $this->name_plan = __('Ai Post','ai-auto-tool'); $this->plan_limit_aiautotool = 'plan_limit_aiautotool_'.$this->active_option_name; $this->notice = new aiautotool_Warning_Notice(); // Auto-activate: ensure option is set to 'true' if not exists $active_option = get_option($this->active_option_name); if ($active_option === false) { // Option doesn't exist, set it to 'true' to auto-activate update_option($this->active_option_name, 'true'); $this->active = 'true'; } else { $this->active = $active_option; } // Check if active (handle both string 'true' and boolean true) if ($this->active === 'true' || $this->active === true) { $this->init(); } add_action('wp_ajax_update_active_option_canonical_'.$this->active_option_name, array($this, 'update_active_option_callback')); add_action( 'wp_ajax_aiautotool_write_article_with_google_search', array( $this, 'aiautotool_write_article_with_google_search_callback' )); add_action( 'wp_ajax_aiautotool_write_article_with_analysis', array( $this, 'aiautotool_write_article_with_analysis_callback' )); add_action( 'wp_ajax_aiautotool_write_article_with_auto_writer', array( $this, 'aiautotool_write_article_with_auto_writer_callback' )); // Register settings add_action('admin_init', array($this, 'register_singleai_settings')); // Register assets using Asset Manager (tối ưu hóa) $this->register_assets(); // Enqueue aiautotool.css and js on edit post pages add_action('admin_enqueue_scripts', array($this, 'enqueue_aiautotool_assets'), 5); } /** * Enqueue aiautotool.css and aiautotool.js on edit post pages */ public function enqueue_aiautotool_assets($hook) { // Check if we're on edit post/page screens $screen = get_current_screen(); if (!$screen) { return; } // Get enabled post types from settings $settings = $this->get_singleai_settings(); $enabled_post_types = $settings['post_types']; // Check if current screen is an edit post screen for enabled post types $is_edit_screen = in_array($screen->base, array('post', 'page', 'post-new', 'page-new')); $is_enabled_post_type = isset($screen->post_type) && in_array($screen->post_type, $enabled_post_types); // Also check for ai_single_post page $is_ai_post_page = strpos($screen->id, 'ai_single_post') !== false; if (($is_edit_screen && $is_enabled_post_type) || $is_ai_post_page) { $plugin_url = defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI : plugin_dir_url(dirname(dirname(__FILE__))); // Enqueue Font Awesome if not already enqueued if (!wp_style_is('font-awesome', 'enqueued')) { wp_enqueue_style( 'font-awesome', $plugin_url . 'js/fontawesome/css/all.min.css', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '7.1.0' ); } // Enqueue SweetAlert2 CSS if not already enqueued if (!wp_style_is('sweetalert2', 'enqueued')) { wp_enqueue_style( 'sweetalert2', $plugin_url . 'js/sweetalert2/dist/sweetalert2.min.css', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '11.26.3' ); } // Enqueue SweetAlert2 JS if not already enqueued if (!wp_script_is('sweetalert2', 'enqueued')) { wp_enqueue_script( 'sweetalert2', $plugin_url . 'js/sweetalert2/dist/sweetalert2.all.min.js', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '11.26.3', false ); } // Enqueue main aiautotool.css if not already enqueued if (!wp_style_is('aiautotool', 'enqueued')) { wp_enqueue_style( 'aiautotool', $plugin_url . 'css/aiautotool.css', array('font-awesome'), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0' ); } // Enqueue aiautotool.js if not already enqueued (contains check_aipost_premium function) if (!wp_script_is('kct_cr_scriptx', 'enqueued')) { // Load rendersetting class if needed for JS settings if (!class_exists('rendersetting')) { $rendersetting_file = plugin_dir_path(dirname(dirname(__FILE__))) . 'lib/setting.php'; if (file_exists($rendersetting_file)) { require_once $rendersetting_file; } } // Get JS settings (same logic as asset manager) $setting = class_exists('rendersetting') ? new rendersetting() : null; $langcodedefault = get_option('aiautotool_default_language', 'vi'); global $post; $settingseditornumberline = ''; $freemius_access = function_exists('aiautotool_get_freemius_access_status') ? aiautotool_get_freemius_access_status() : array( 'can_use_pro_features' => false, 'is_free' => true, 'is_trial' => false, 'trial_days_remaining' => null, 'trial_ends' => null, 'reason' => 'freemius_unavailable', ); $js_setting = array( 'ajax_url' => admin_url('admin-ajax.php'), 'security' => wp_create_nonce('aiautotool_nonce'), 'media_search_base_url' => $this->get_media_search_base_url(), 'languageCodes' => $setting ? $setting->languageCodes : array(), 'langcodedefault' => $langcodedefault, 'fsdata' => $setting ? rendersetting::aiautotool_getdata() : array(), 'freemius_access' => $freemius_access, 'aiautotool_premium' => ! empty($freemius_access['can_use_pro_features']), 'code_mirrror' => $settingseditornumberline, 'gemini_api' => defined('AIAUTOTOOL_API_GEM') ? AIAUTOTOOL_API_GEM : '', 'prompt' => get_option('aiautotool_prompt_options', array()) ); if (class_exists('AIAutotool_AI_Provider_Manager')) { $provider_manager = AIAutotool_AI_Provider_Manager::get_instance(); $js_setting['active_ai_provider'] = ($provider_manager->get_active_provider()) ? $provider_manager->get_active_provider()->get_id() : ''; $js_setting['active_ai_model'] = $provider_manager->get_active_model(); $js_setting['ai_provider_routing_mode'] = method_exists($provider_manager, 'get_provider_routing_mode') ? $provider_manager->get_provider_routing_mode() : 'single'; $execution_mode = get_option('aiautotool_ai_execution_mode', 'agent'); $js_setting['ai_execution_mode'] = in_array($execution_mode, array('agent', 'direct_api'), true) ? $execution_mode : 'agent'; } else { $js_setting['active_ai_provider'] = ''; $js_setting['active_ai_model'] = ''; $js_setting['ai_provider_routing_mode'] = 'single'; $js_setting['ai_execution_mode'] = 'agent'; } if (isset($post->ID)) { $js_setting['postID'] = $post->ID; $js_setting['postTitle'] = $post->post_title; } // Register and enqueue aiautotool.js wp_register_script( 'kct_cr_scriptx', $plugin_url . 'js/aiautotool.js', array('jquery'), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0', true ); // Localize script with settings wp_localize_script('kct_cr_scriptx', 'aiautotool_js_setting', $js_setting); wp_enqueue_script('kct_cr_scriptx'); } wp_enqueue_script( 'aiautotool-searchable-select', $plugin_url . 'js/searchable-select.js', array('jquery'), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0', true ); // Enqueue AI Agent JavaScript if (class_exists('AIAutotool_AI_Agent')) { AIAutotool_AI_Agent::enqueue_assets(); } } } /** * Register settings for Single AI */ public function register_singleai_settings() { register_setting( 'aiautotool_singleai_settings_group', $this->settings_option_name, array( 'type' => 'array', 'sanitize_callback' => array($this, 'sanitize_singleai_settings'), 'default' => array('post_types' => array('post', 'page')) ) ); } /** * Sanitize settings */ public function sanitize_singleai_settings($input) { $sanitized = array(); if (isset($input['post_types']) && is_array($input['post_types'])) { $sanitized['post_types'] = array_map('sanitize_text_field', $input['post_types']); } else { $sanitized['post_types'] = array('post', 'page'); } return $sanitized; } /** * Get settings */ public function get_singleai_settings() { $defaults = array('post_types' => array('post', 'page')); $settings = get_option($this->settings_option_name, $defaults); // Ensure post_types is an array if (!isset($settings['post_types']) || !is_array($settings['post_types'])) { $settings['post_types'] = $defaults['post_types']; } return $settings; } private function get_media_search_base_url() { $base_url = defined('AIAUTOTOOL_MEDIA_SEARCH_SERVER') ? AIAUTOTOOL_MEDIA_SEARCH_SERVER : getenv('AIAUTOTOOL_MEDIA_SEARCH_SERVER'); if (empty($base_url)) { $base_url = 'https://aplugin.aiautotool.com'; } return untrailingslashit(esc_url_raw($base_url)); } /** * Register assets using Asset Manager */ private function register_assets() { // Ensure Asset Manager is loaded if (!function_exists('aiautotool_register_assets')) { return; } // Use closure to lazy load config when assets are actually enqueued $feature = $this; aiautotool_register_assets('single-ai', array( 'scripts' => array( 'kct_aipost' => array( 'src' => plugin_dir_url(__FILE__) . 'assets/js/aipost.js', 'deps' => array('jquery', 'kct_cr_scriptx', 'aiautotool-ai-agent'), // Depend on aiautotool.js for check_aipost_premium function 'version' => (defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.2') . '-agent-mode-v2', 'in_footer' => true, 'localize' => array( 'object_name' => 'aipost', 'data' => function() use ($feature) { $ai_provider_data = $feature->aiautotool_get_ai_provider_js_settings(); // Lazy load config when actually enqueuing return array_merge(array( 'ajax_url' => admin_url('admin-ajax.php'), 'config' => isset($feature->config) ? $feature->config : array(), 'media_search_base_url' => $feature->get_media_search_base_url(), 'security' => wp_create_nonce('aiautotool_aipost_nonce') ), $ai_provider_data); } ) ) ), 'styles' => array( 'aiautotool-singleai-modern' => array( 'src' => plugin_dir_url(__FILE__) . 'assets/css/singleai-modern.css', 'deps' => array('aiautotool'), 'version' => defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0', 'media' => 'all' ) ), 'pages' => array('ai_single_post', 'post', 'page', 'post-new', 'page-new'), // Load on single AI post page and edit post/page screens 'conditions' => array( function($hook) { $screen = get_current_screen(); if (!$screen) { return false; } // Load on ai_single_post page if (strpos($screen->id, 'ai_single_post') !== false) { return true; } // Load on edit post/page screens if (in_array($screen->base, array('post', 'page', 'post-new', 'page-new'))) { return true; } // Load on custom post type edit screens if enabled $settings = get_option('aiautotool_singleai_settings', array('post_types' => array('post', 'page'))); $enabled_post_types = isset($settings['post_types']) ? $settings['post_types'] : array('post', 'page'); if (isset($screen->post_type) && in_array($screen->post_type, $enabled_post_types)) { return true; } return false; } ) )); } public function aiautotool_meta_box() { // Get enabled post types from settings $settings = $this->get_singleai_settings(); $enabled_post_types = $settings['post_types']; // Add meta box only for enabled post types if (!empty($enabled_post_types)) { add_meta_box( 'aiautotool-meta-box', 'Ai Auto Tool', array($this, 'aiautotool_meta_box_callback'), $enabled_post_types, 'side', 'high' ); add_meta_box( 'aiautotool-aireview-meta-box', 'Ai Review', array($this,'aiautotool_aireview_meta_box_callback'), $enabled_post_types, 'side', 'high' ); } } public function aiautotool_aireview_meta_box_callback($post) { // Retrieve any saved meta box data $custom_data = get_post_meta($post->ID, 'custom_data_key', true); ?> SEO Review by AI
ID, 'custom_data_key', true); // Output the HTML markup for your custom meta box ?>

Outline Introduction Conclusion Create FAQ

Suggest Outline By Ai Auto Tool

icon . ' ' . esc_html($this->name_plan)); ?>




plan_limit_aiautotool) !== false; } private function aiautotool_initialize_plugin_data() { $current_date = date('Y-m-d'); $expiration = strtotime('+1 month', strtotime($current_date)); $expiration = date('Y-m-d', $expiration); update_option($this->plan_limit_aiautotool, array( 'start_date' => $current_date,'expiration'=>$expiration)); } public function aiautotool_check_post_limit() { $stored_data = get_option($this->plan_limit_aiautotool, array()); $current_date = date('Y-m-d'); if ($this->is_new_month($current_date, $stored_data['start_date'])) { // Nếu đã qua một tháng, đặt lại số lượng bài đăng và ngày bắt đầu $expiration = strtotime('+1 month', strtotime($current_date)); $expiration = date('Y-m-d', $expiration); update_option($this->plan_limit_aiautotool, array( 'start_date' => $current_date,'expiration'=>$expiration)); update_option($this->usage_option_name, 0,null, 'no'); } } private function is_new_month($current_date, $start_date) { $current_month = date('m', strtotime($current_date)); $start_month = date('m', strtotime($start_date)); return ($current_month != $start_month); } public function aiautotool_checklimit($config) { // return ($config['number_post'] !== -1 && $config['number_post'] >= $config['usage']) || $config['number_post'] === -1; return $this->check_quota(); } public function aiautotool__update_usage() { $this->aiautotool_check_post_limit(); // Get the current usage value $current_value = get_option($this->usage_option_name, 0); // Increment the value by 1 $new_value = $current_value + 1; // Update the option with the new value and set autoload to 'no' update_option($this->usage_option_name, $new_value, 'no'); // Optionally, return the updated value return $new_value; } /** * Legacy method - kept for backward compatibility * Assets are now handled by Asset Manager via register_assets() * * @deprecated Assets are now managed by Asset Manager */ public function add_aiautotool_aipost_js() { // Assets are now managed by Asset Manager // This method is kept for backward compatibility only // If Asset Manager didn't load assets, fallback to old method if (!wp_script_is('kct_aipost', 'enqueued')) { wp_register_script('kct_aipost', plugin_dir_url( __FILE__ ) .'assets/js/aipost.js', array('jquery'), (defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.2') . '-agent-mode-v2', true); wp_localize_script( 'kct_aipost', 'aipost', array_merge(array( 'ajax_url' => admin_url( 'admin-ajax.php'),'config'=>$this->config,'media_search_base_url' => $this->get_media_search_base_url(),'security' => wp_create_nonce('aiautotool_aipost_nonce') ), $this->aiautotool_get_ai_provider_js_settings()) ); wp_enqueue_script('kct_aipost'); } // Enqueue modern CSS for single post page $current_screen = get_current_screen(); if ($current_screen && (strpos($current_screen->id, 'ai_single_post') !== false)) { if (!wp_style_is('aiautotool-singleai-modern', 'enqueued')) { wp_enqueue_style('aiautotool-singleai-modern', plugin_dir_url( __FILE__ ) .'assets/css/singleai-modern.css', array(), defined('AIAUTOTOOL_VERSION_CACHE') ? AIAUTOTOOL_VERSION_CACHE : '1.0.0'); } } } public function aiautotool_update_usage() { $this->aiautotool_check_post_limit(); // Get the current usage value $current_value = get_option($this->usage_option_name, 0); // Increment the value by 1 $new_value = $current_value + 1; if($this->config['number_post']!=-1){ if($this->config['number_post'] > $new_value){ update_option($this->usage_option_name, $new_value, 'no'); } }else{ update_option($this->usage_option_name, $new_value, 'no'); } return $new_value; } public function render_plan(){ if ($this->active=='true') { $quota = $this->config['number_post'] == -1 ? 'Unlimited' : esc_html($this->config['number_post']); echo wp_kses( '

' . $this->icon . ' ' . esc_html($this->name_plan) . ': Usage: ' . esc_html($this->config['usage']) . '

', [ 'p' => [], 'i' => ['class' => []], 'strong' => [], ] ); } } public function update_active_option_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403)); } if (isset($_POST['active'])) { $active = sanitize_text_field($_POST['active']); update_option($this->active_option_name, $active,null, 'no'); print_r($active); } wp_die(); } function init(){ $configs = get_option($this->plan_limit_aiautotool, array()); if (!$this->aiautotool_has_plugin_data()) { $this->aiautotool_initialize_plugin_data(); $configs = get_option($this->plan_limit_aiautotool, array()); } if(isset($configs['expiration'])){ $this->config = array( 'number_post'=>$this->limit, 'usage'=>get_option($this->usage_option_name, 0, 'no'), 'time_exprice'=>$configs['expiration'] ); }else{ $this->config = array( 'number_post'=>$this->limit, 'usage'=>get_option($this->usage_option_name, 0, 'no'), 'time_exprice'=>'' ); } if (function_exists('aiautotool_can_use_pro_features') && aiautotool_can_use_pro_features()) { $fs = $this->is_premium(); $license = ($fs && is_object($fs) && method_exists($fs, '_get_license')) ? $fs->_get_license() : null; if (is_object($license) && isset($license->expiration)) { $this->config = array( 'number_post' => -1, 'usage' => get_option($this->usage_option_name, 0, 'no'), 'time_exprice' => $license->expiration ); } else { $this->config = array( 'number_post' => -1, 'usage' => get_option($this->usage_option_name, 0, 'no'), 'time_exprice' => '' ); } } add_action('admin_menu', array($this, 'add_menu')); add_action('admin_init', array($this, 'aiautotool_check_post_limit')); add_action('wp_ajax_aiautotool_get_slug', array($this, 'aiautotool_get_slug')); add_action('wp_ajax_bard_content', array($this, 'bard_content_callback')); add_action('wp_ajax_save_post_data', array($this, 'save_post_data')); add_action('wp_ajax_update_usage', array($this, 'aiautotool_update_usage_callback')); add_action('wp_ajax_seoreview_ajax', array($this, 'aiautotool_seoreview_ajax_callback')); add_action('add_meta_boxes', array( $this, 'aiautotool_meta_box' )); add_action('wp_ajax_aiautotool_suggest_tag', array($this, 'aiautotool_suggest_tag_callback')); // AJAX handlers for image generation features add_action('wp_ajax_aiautotool_save_draft', array($this, 'aiautotool_save_draft_callback')); add_action('wp_ajax_aiautotool_set_featured_image', array($this, 'aiautotool_set_featured_image_callback')); add_action('wp_ajax_aiautotool_generate_ai_image', array($this, 'aiautotool_generate_ai_image_callback')); add_action('wp_ajax_aiautotool_generate_tts_audio', array($this, 'aiautotool_generate_tts_audio_callback')); add_action('wp_ajax_aiautotool_save_tts_audio', array($this, 'aiautotool_save_tts_audio_callback')); add_action('wp_ajax_aiautotool_fetch_remote_content', array($this, 'aiautotool_fetch_remote_content_callback')); add_action('wp_ajax_aiautotool_analyze_image_positions', array($this, 'aiautotool_analyze_image_positions_callback')); add_action('wp_ajax_aiautotool_generate_english_prompt', array($this, 'aiautotool_generate_english_prompt_callback')); add_action('transition_post_status', array($this, 'aiautotool_maybe_queue_auto_tts'), 10, 3); add_action('aiautotool_generate_post_tts_event', array($this, 'aiautotool_generate_post_tts_event')); add_action('rest_api_init', array($this, 'aiautotool_register_voice_video_rest_routes')); // AJAX handler for article writing with Google search (SSE streaming) //add_action('wp_ajax_aiautotool_write_article_with_google_search', array($this, 'aiautotool_write_article_with_google_search_callback')); } public function aiautotool_suggest_tag_callback() { // Kiểm tra nonce if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( $_POST['security'], 'aiautotool_nonce' ) ) { wp_send_json_error( 'Invalid nonce' ); } if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : ''; $lang = isset($_POST['lang']) ? sanitize_text_field($_POST['lang']) : $this->setting['lang']; $tag = $this->aiautotool_AIprecreatetagname($title,$lang); if(isset($tag)){ wp_send_json_success( $tag ); }else{ wp_send_json_error( 'no tag' ); } } public function aiautotool_AIprecreatetagname($title, $lang) { $bardGenContent = new BardGenContent(); $question = "The most important: The results must only be in JSON format, the response must be in the SAME LANGUAGE as the original text (text between \"======\"). Create %%NUMMBERCOMMENT%% tag for the article. tag only 2 or 3 word tag must have a ====== %%TITLTE%% ====== intellectual level. The post\'s content is between \"=========\". The results must only be in JSON format, with this exact format, you have to fill empty values,Each item in tag has the form { \"tag\": \"\" } "; $question = str_replace('%%TITLTE%%', $title, $question); $question = str_replace('%%NUMMBERCOMMENT%%', rand(8, 15), $question); $json = $bardGenContent->bardcontentmore($question, $lang); return $this->aiautotool_fixjsonreturn($json); } public function aiautotool_seoreview_ajax_callback() { // Kiểm tra xác thực nonce để đảm bảo an toàn check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } // Lấy dữ liệu gửi từ client $post_title = sanitize_text_field($_POST['title']); $post_content = wp_kses_post($_POST['content']); $lang = $_POST['lang']; $question = ' Tên của bạn bây giờ sẽ là AIAutoTool. Mở đầu kết quả trả về bạn phải tự giới thiệu về mình là : AIAutoTool, sau đây là phần đánh giá bài viết của bạn. Ngôn ngữ trả về phải giống với ngôn ngữ có trong nội dung (Nội dung bài viết nằm giữa =======) hãy thống kê từ khoá chính, từ khoá phụ, dự đoán từ khoá cùng vị trí có thể lên top google trong tương lai đối với nội dung bài viết có trong nội dung bài viết sau. Dựa vào bảng checklist dưới đây, đánh giá bài viết có (nội dung bài viết nằm giữa =======) - title Chứa từ khóa chính (khoảng 5-7 từ) - tiêu đề Dưới 70 ký tự (bao gồm cả khoảng trắng) - Sử dụng giọng văn Thu hút và khơi gợi sự tò mò - Sử dụng chữ hoa và số đếm hợp lý, các con số thống kê nên được đưa ra. - Mô tả ngắn của bài viết nên Chứa từ khóa chính (khoảng 10-15 từ).Dưới 160 ký tự (bao gồm cả khoảng trắng) - Tóm tắt nội dung bài viết một cách súc tích và hấp dẫn - Sử dụng Call to Action (CTA) - Cung cấp thông tin hữu ích và giá trị cho người đọc - Đáp ứng đúng ý định tìm kiếm của người dùng - Sử dụng từ khóa chính một cách tự nhiên và mật độ phù hợp (khoảng 1-2%) - Chia bài viết thành các đoạn ngắn, sử dụng headings và subheadings hợp lý - Bổ sung hình ảnh, video và infographic để minh họa cho nội dung - Sử dụng các liên kết nội bộ và liên kết ngoài chất lượng - Chứa từ khóa chính và biến thể của từ khóa mục tiêu. - Có tổ chức logic, dễ đọc và dễ tiếp cận. - Chứa thông tin giá trị và hữu ích cho người đọc. - Sử dụng các tiêu đề con (H2, H3) để phân đoạn nội dung. - Bài viết cần được kiểm tra lỗi chính tả và ngữ pháp Trên đây là những yêu cầu tối thiểu cho một bài viết blog, bạn hãy đóng vai trò người SEOER đánh giá nội dung sau đây có được bao nhiêu điều thoả mãi checklist seo ở trên. Nội dung có trong bài viết sau:. ======= %%CONTENT%% ======='; $question = str_replace('%%CONTENT%%',$post_content,$question); $bardGenContent = new BardGenContent(); $json = $bardGenContent->bardcontentmore($question,$lang); if ($json) { wp_send_json_success($json); wp_die(); } wp_send_json_error($newcontent); wp_die(); } public function aiautotool_fixjsonreturn($result){ $pattern = '/\{(?:[^{}]|(?R))*\}/'; preg_match_all($pattern, $result, $matches); $arritem = array(); foreach ($matches[0] as $jsonString) { $decodedJson = json_decode($jsonString, true); if ($decodedJson !== null) { if(isset($decodedJson['tags'])) { foreach($decodedJson['tags'] as $item){ $arritem[] = $item; } }else{ $arritem[] = $decodedJson; } } else { return null; } } return $arritem; } function aiautotool_update_usage_callback() { check_ajax_referer('aiautotool_aipost_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $this->aiautotool_update_usage(); wp_send_json_success(array('success'=>true)); wp_die(); } function save_post_data() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $languageCodes = $this->languageCodes; $title = sanitize_text_field($_POST['aiautotool_title']); $slug = sanitize_text_field($_POST['aiautotool_slug']); $categories = array_map('absint', $_POST['post_category']); // Ensure categories are integers $tags = sanitize_text_field($_POST['aiautotool_tags']); $content = wp_kses_post($_POST['aiautotool_content']); //xu ly time $publish_year = sanitize_text_field($_POST['publish_year']); $publish_month = sanitize_text_field($_POST['publish_month']); $publish_day = sanitize_text_field($_POST['publish_day']); $publish_hour = sanitize_text_field($_POST['publish_hour']); $publish_minute = sanitize_text_field($_POST['publish_minute']); $attachThumbnail = sanitize_text_field($_POST['custom-thumbnail-id']); $post_language = sanitize_text_field($_POST['post_language']); $publish_timestamp = strtotime("$publish_year-$publish_month-$publish_day $publish_hour:$publish_minute"); $current_time = current_time('timestamp'); if ($publish_timestamp <= $current_time) { $post_status = 'publish'; $post_date = date('Y-m-d H:i:s', $publish_timestamp); } else { $post_status = 'future'; $post_date = date('Y-m-d H:i:s', $publish_timestamp); } $post_data = array( 'post_title' => $title, 'post_name' => $slug, 'post_content' => $content, 'post_status' => $post_status, 'post_date' => $post_date, 'post_category' => $categories, 'tags_input' => $tags, ); $post_id = wp_insert_post($post_data); $selectedLanguageName = 'Vietnamese'; if(array_key_exists($post_language, $languageCodes)) { $selectedLanguageName = $languageCodes[$post_language]; if(in_array('polylang/polylang.php', apply_filters('active_plugins', get_option('active_plugins')))){ pll_set_post_language($post_id, $post_language); } } update_post_meta($post_id, 'lang', $selectedLanguageName); $html = stripslashes($content); preg_match_all('/]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches); $listimg1 = $matches[1]; $imgUploaded = array(); if (!empty($listimg1)){ foreach ($listimg1 as $post_image_url){ try { $image_url_new = $this->kct_aiautotool_save_image($post_image_url,$postname); if (!empty($image_url_new)){ $imgUploaded[] = $image_url_new; if ($attachThumbnail == 0) { $attachThumbnail = $image_url_new['attach_id']; } } }catch (Exception $e) { } } } foreach ($imgUploaded as $img){ $content = str_replace($img['url'],$img['baseurl'],$content); } if ($attachThumbnail != 0) { set_post_thumbnail($post_id, $attachThumbnail); } $post_data = array( 'ID' => $post_id, 'post_title'=>$title, 'post_content' => $content, 'post_status'=>'publish' ); $post_id = wp_update_post($post_data); if ($post_id) { $post_url = get_permalink($post_id); $edit_url = get_edit_post_link($post_id); // Post successfully created, send success response wp_send_json_success(array( 'post_id' => $post_id, 'post_url' => $post_url, 'edit_url' => $edit_url, 'message' => 'Post successfully saved and published!', )); } else { // Error in creating the post, send error response wp_send_json_error(array( 'message' => 'Error saving and publishing the post.', )); } // Perform your data saving logic here (example: save to database) // Send a response back to the client wp_send_json_success(array('content' => $_POST)); // or wp_send_json_error('Error saving data!'); in case of an error } public function kct_aiautotool_save_image($imgURL,$post_title){ $image_name = basename( $imgURL ); $filetype = wp_check_filetype($image_name); $upload_dir = wp_upload_dir(); $extension = $filetype['ext']?$filetype['ext']:"jpg"; if (empty($extension)) $extension = "jpg"; $unique_file_name = sanitize_title($post_title)."-".uniqid().".".$extension; $filename = $upload_dir['path'] . '/' . $unique_file_name; $baseurl = $upload_dir['baseurl'] .$upload_dir['subdir']. '/' . $unique_file_name; $ch = curl_init($imgURL); $fp = fopen($filename, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_exec($ch); $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); fclose($fp); if ($rescode == 200 && filesize($filename) > 100){ $wp_filetype = wp_check_filetype(basename($filename), null); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($post_title), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment($attachment, $filename); $imagenew = get_post($attach_id); $fullsizepath = get_attached_file($imagenew->ID); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata($attach_id, $fullsizepath); wp_update_attachment_metadata($attach_id, $attach_data); $output['url'] = $imgURL; $output['file_name'] = $unique_file_name; $output['path'] = $filename; $output['baseurl'] = $baseurl; $output['attach_id'] = $attach_id; $output['url_out'] = $baseurl; return $output; }else{ return null; } } public function bard_content_callback(){ // Verify nonce for security if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) { wp_send_json_error(array('message' => 'Security check failed')); return; } if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); return; } $languageCodes = $this->languageCodes; $bardGenContent = new BardGenContent(); // Get parameters with fallbacks $question = isset($_POST['question']) ? sanitize_textarea_field($_POST['question']) : ''; $title = isset($_POST['title']) ? sanitize_text_field($_POST['title']) : $question; $option = isset($_POST['option']) ? sanitize_text_field($_POST['option']) : ''; $ac = isset($_POST['ac']) ? sanitize_text_field($_POST['ac']) : $option; $post_language = isset($_POST['lang']) ? sanitize_text_field($_POST['lang']) : ''; $tone = isset($_POST['tone']) ? sanitize_text_field($_POST['tone']) : ''; $resolved_ai_selection = $this->aiautotool_resolve_provider_model_selection( isset($_POST['model']) ? $_POST['model'] : '', isset($_POST['provider_id']) ? $_POST['provider_id'] : '' ); $model = $resolved_ai_selection['model']; $provider_id = $resolved_ai_selection['provider_id']; // Handle old parameter name for compatibility if (empty($post_language) && isset($_POST['post_language'])) { $post_language = sanitize_text_field($_POST['post_language']); } // Resolve language code $lang = 'English'; if (!empty($post_language)) { if(array_key_exists($post_language, $languageCodes)) { $lang = $languageCodes[$post_language]; } else { $lang = $post_language; } } $newcontent = ''; $prompt = ''; try { // Handle different action types switch($ac){ case 'bardcontent': $newcontent = $bardGenContent->bardcontentmore($title, $lang, $model, $provider_id); break; case 'bard_content': $newcontent = $bardGenContent->bardcontentmore($title, $lang, $model, $provider_id); break; case 'writemore': case 'bardcontentmore': // For Remote Rewrite and content expansion if (!empty($question)) { $newcontent = $bardGenContent->bardcontentmore($question, $lang, $model, $provider_id); } else { $newcontent = $bardGenContent->bardcontentmore($title, $lang, $model, $provider_id); } break; case 'bardrewrite': // For content rewriting if (!empty($question)) { $newcontent = $bardGenContent->bardrewrite($question, $lang, $tone, $model, $provider_id); } elseif (!empty($title)) { $newcontent = $bardGenContent->bardrewrite($title, $lang, $tone, $model, $provider_id); } break; case 'writefull': // For full article writing if (!empty($question)) { $newcontent = $bardGenContent->bardcontentfull($question, $lang, $model, $provider_id); } else { $newcontent = $bardGenContent->bardcontentfull($title, $lang, $model, $provider_id); } break; case 'writebard': // For basic content generation if (!empty($question)) { $newcontent = $bardGenContent->bardcontent($question, $lang, $model, $provider_id); } else { $newcontent = $bardGenContent->bardcontent($title, $lang, $model, $provider_id); } break; case 'suggettitle': $allprompt = get_option('aiautotool_prompt_options', array()); if (!isset($allprompt['aiautotool_prompt_suggest_title']) || empty($allprompt['aiautotool_prompt_suggest_title'])) { $prompt_suggest_title = "Generate 5 SEO-friendly titles for the following topic: {title}. Each title should be between 50-70 characters and include the main keyword. Format the response as a numbered list."; } else { $prompt_suggest_title = $allprompt['aiautotool_prompt_suggest_title']; } $content = ''; $cate = ''; $blogtitle = ''; // Add number of titles to generate $num_titles = 5; $prompt = $this->aiautotool_fix_question($prompt_suggest_title, $title, $lang, $cate, $blogtitle, $content); $prompt = str_replace('{num_titles}', $num_titles, $prompt); $newcontent = $bardGenContent->gentitle($prompt, $lang, $model, $provider_id); // Format the response as a numbered list if not already formatted if (strpos($newcontent, '1.') === false) { $titles = explode("\n", trim($newcontent)); $formatted_titles = array(); foreach ($titles as $index => $t) { if (!empty(trim($t))) { $formatted_titles[] = ($index + 1) . '. ' . trim($t); } } $newcontent = implode("\n", $formatted_titles); } break; default: // Default to content generation if (!empty($question)) { $newcontent = $bardGenContent->bardcontentmore($question, $lang, $model, $provider_id); } else { $newcontent = $bardGenContent->bardcontentmore($title, $lang, $model, $provider_id); } break; } // Check if content was generated if (empty($newcontent)) { wp_send_json_error(array( 'message' => 'AI failed to generate content. Please try again.', 'code' => 'empty_content' )); return; } // Return success with generated content wp_send_json_success(array( 'content' => $newcontent, 'result' => $newcontent, 'lang' => $lang, 'lg' => $post_language, 'prompt' => $prompt, 'option' => $ac )); } catch (Exception $e) { wp_send_json_error(array( 'message' => 'Error generating content: ' . $e->getMessage(), 'code' => 'exception' )); } wp_die(); } public function aiautotool_get_slug() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $title = sanitize_title($_POST['title']); wp_send_json_success(array('slug' => $title)); wp_die(); } public function add_menu() { // add_submenu_page( // MENUSUBPARRENT, // ' AI Single Post', // ' AI Single Post', // 'manage_options', // 'ai_single_post', // array($this, 'render_form') // ); add_submenu_page( 'edit.php', ' AI Post', ' AI Post', 'manage_options', 'ai_post', array($this, 'render_form') ); } public function render_setting() { // Get current config $configs = get_option($this->plan_limit_aiautotool, array()); $usage = get_option($this->usage_option_name, 0); $limit = $this->limit; $expiration = isset($configs['expiration']) ? $configs['expiration'] : ''; // Check if premium or active trial - verify with Freemius access helper $is_premium = false; $plan_name = ''; if (function_exists('aiautotool_can_use_pro_features') && aiautotool_can_use_pro_features()) { $premium_obj = $this->is_premium(); $is_premium = true; $limit = -1; // Unlimited if ($premium_obj && is_object($premium_obj) && method_exists($premium_obj, '_get_license')) { $license = $premium_obj->_get_license(); if ($license && isset($license->expiration)) { $expiration = $license->expiration; } } } // Calculate remaining $remaining = ($limit == -1) ? __('Unlimited', 'ai-auto-tool') : max(0, $limit - $usage); $usage_percentage = ($limit == -1 || $limit == 0) ? 0 : min(100, ($usage / $limit) * 100); ?> active == 'true' || $this->active === true) { echo ''; } } public function render_feature(){ // Load feature descriptions require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php'; $autoToolBox = new AutoToolBox( $this->icon.' '.$this->name_plan, AiAutoTool_Feature_Descriptions::get('single_ai'), "https://doc.aiautotool.com/features/ai-content-editor", $this->active_option_name, $this->active, defined('AIAUTOTOOL_URI') ? AIAUTOTOOL_URI . 'images/logo.svg' : plugins_url('../../images/logo.svg', __FILE__) ); echo $autoToolBox->generateHTML(); } public function render_form() { $current_time = current_time('mysql'); $datetime = new DateTime($current_time); $year = $datetime->format('Y'); // Lấy năm $month = $datetime->format('m'); // Lấy tháng $day = $datetime->format('d'); // Lấy ngày $hour = $datetime->format('H'); // Lấy giờ $minute = $datetime->format('i'); // Lấy phút $language_code = explode('_',get_locale()); $language_code = $language_code[0]; // Mảng mã ngôn ngữ và tên tương ứng $languages = $this->languageCodes; // $post = new SinglePost('','vi'); // print_r($post->getPost()); ?>
AI Autotool

'aiautotool_content')); ?>
:

Write button to generate AI content','ai-auto-tool')); ?>

Outline Tool
Create comprehensive outlines with main topics and subtopics

Outline Active Introduction Click to use Conclusion Click to use Create FAQ Click to use

Suggest Outline By AI Auto Tool

Active Tool

Create a comprehensive outline with main topics and subtopics organized in a hierarchical structure.

__('Permission denied', 'ai-auto-tool'))); } $title = sanitize_text_field($_POST['title']); $content = wp_kses_post($_POST['content']); if (empty($title) || empty($content)) { wp_send_json_error('Title and content are required'); } $post_data = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'draft', 'post_type' => 'post', 'post_author' => get_current_user_id() ); $post_id = wp_insert_post($post_data); if ($post_id && !is_wp_error($post_id)) { wp_send_json_success(array( 'post_id' => $post_id, 'message' => 'Draft saved successfully' )); } else { wp_send_json_error('Failed to save draft'); } } /** * AJAX callback to generate an image through configured AI image providers. */ public function aiautotool_generate_ai_image_callback() { check_ajax_referer('aiautotool_aipost_nonce', 'security'); if (!current_user_can('upload_files')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $prompt = isset($_POST['prompt']) ? sanitize_textarea_field(wp_unslash($_POST['prompt'])) : ''; if ($prompt === '') { wp_send_json_error(array('message' => __('Image prompt is required', 'ai-auto-tool'))); } if (!class_exists('AIAutotool_AI_Helper')) { $helper_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_helper.php'; if (file_exists($helper_file)) { require_once $helper_file; } } if (!class_exists('AIAutotool_AI_Helper')) { wp_send_json_error(array('message' => __('AI Provider module is not available', 'ai-auto-tool'))); } $provider = isset($_POST['provider']) ? sanitize_text_field(wp_unslash($_POST['provider'])) : ''; $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : ''; $width = isset($_POST['width']) ? absint($_POST['width']) : 1024; $height = isset($_POST['height']) ? absint($_POST['height']) : 1024; $seed = isset($_POST['seed']) ? sanitize_text_field(wp_unslash($_POST['seed'])) : ''; $negative_prompt = isset($_POST['negative_prompt']) ? sanitize_text_field(wp_unslash($_POST['negative_prompt'])) : 'worst quality, blurry'; $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0; $result = AIAutotool_AI_Helper::generate_image($prompt, array( 'provider' => $provider, 'model' => $model, 'width' => $width, 'height' => $height, 'seed' => $seed, 'negative_prompt' => $negative_prompt, 'timeout' => 120, )); if (empty($result['success'])) { $message = !empty($result['error']) ? $result['error'] : __('Image generation failed', 'ai-auto-tool'); wp_send_json_error(array('message' => $message, 'result' => $result)); } if (!empty($result['data_url'])) { $saved = $this->aiautotool_save_generated_image_data_url($result['data_url'], $prompt, $post_id); if (empty($saved['success'])) { wp_send_json_error(array('message' => $saved['message'])); } $result['url'] = $saved['url']; $result['attachment_id'] = $saved['attachment_id']; unset($result['data_url']); } if (empty($result['url'])) { wp_send_json_error(array('message' => __('Image provider did not return an image URL', 'ai-auto-tool'))); } wp_send_json_success($result); } private function aiautotool_save_generated_image_data_url($data_url, $prompt, $post_id = 0) { if (!preg_match('/^data:image\/(png|jpe?g|webp);base64,(.+)$/i', $data_url, $matches)) { return array('success' => false, 'message' => __('Invalid generated image data', 'ai-auto-tool')); } $extension = strtolower($matches[1]); if ($extension === 'jpeg') { $extension = 'jpg'; } $image_data = base64_decode($matches[2]); if ($image_data === false || $image_data === '') { return array('success' => false, 'message' => __('Failed to decode generated image', 'ai-auto-tool')); } $filename = sanitize_file_name(substr(sanitize_title($prompt), 0, 80)); if ($filename === '') { $filename = 'ai-generated-image'; } $filename .= '-' . time() . '.' . $extension; $upload = wp_upload_bits($filename, null, $image_data); if (!empty($upload['error'])) { return array('success' => false, 'message' => $upload['error']); } $file_path = $upload['file']; $file_url = $upload['url']; $filetype = wp_check_filetype($filename, null); $attachment = array( 'post_mime_type' => !empty($filetype['type']) ? $filetype['type'] : 'image/' . $extension, 'post_title' => sanitize_text_field(wp_trim_words($prompt, 12, '')), 'post_content' => '', 'post_status' => 'inherit', ); $attach_id = wp_insert_attachment($attachment, $file_path, $post_id); if (is_wp_error($attach_id)) { return array('success' => false, 'message' => $attach_id->get_error_message()); } require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $file_path); wp_update_attachment_metadata($attach_id, $attach_data); return array( 'success' => true, 'url' => $file_url, 'attachment_id' => $attach_id, ); } /** * AJAX callback to set featured image */ public function aiautotool_set_featured_image_callback() { check_ajax_referer('aiautotool_nonce', 'security'); $image_url = esc_url_raw($_POST['image_url']); $post_id = intval($_POST['post_id']); if (empty($image_url) || empty($post_id)) { wp_send_json_error('Image URL and post ID are required'); } // Check if post exists $post = get_post($post_id); if (!$post) { wp_send_json_error('Post not found'); } // Check permission to edit post if (!current_user_can('edit_post', $post_id)) { wp_send_json_error('Permission denied'); } try { // Download and upload image to media library $upload_dir = wp_upload_dir(); $image_data = file_get_contents($image_url); if ($image_data === false) { wp_send_json_error('Failed to download image'); } $filename = 'ai-generated-' . time() . '.jpg'; $file_path = $upload_dir['path'] . '/' . $filename; if (file_put_contents($file_path, $image_data) === false) { wp_send_json_error('Failed to save image to server'); } // Create attachment $wp_filetype = wp_check_filetype($filename, null); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment($attachment, $file_path, $post_id); if (is_wp_error($attach_id)) { wp_send_json_error('Failed to create attachment'); } // Generate attachment metadata require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata($attach_id, $file_path); wp_update_attachment_metadata($attach_id, $attach_data); // Set as featured image $result = set_post_thumbnail($post_id, $attach_id); if ($result) { wp_send_json_success(array( 'success' => true, 'attachment_id' => $attach_id, 'message' => 'Featured image set successfully' )); } else { wp_send_json_error('Failed to set featured image'); } } catch (Exception $e) { wp_send_json_error('Error: ' . $e->getMessage()); } } /** * AJAX callback to fetch remote content for Remote Rewrite feature */ public function aiautotool_fetch_remote_content_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $url = isset($_POST['url']) ? esc_url_raw($_POST['url']) : ''; if (empty($url)) { wp_send_json_error(array( 'message' => 'URL is required', 'code' => 'missing_url' )); } if (!filter_var($url, FILTER_VALIDATE_URL)) { wp_send_json_error(array( 'message' => 'Invalid URL format', 'code' => 'invalid_url' )); } if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { wp_send_json_error(array( 'message' => 'URL must use HTTP or HTTPS protocol', 'code' => 'invalid_protocol' )); } try { $response = wp_remote_get($url, array( 'timeout' => 30, 'redirection' => 5, 'httpversion' => '1.1', 'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'headers' => array( 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language' => 'en-US,en;q=0.5', ) )); if (is_wp_error($response)) { wp_send_json_error(array( 'message' => 'Failed to fetch remote content: ' . $response->get_error_message(), 'code' => 'fetch_error' )); } $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { wp_send_json_error(array( 'message' => 'Remote server returned error code: ' . $response_code, 'code' => 'http_error' )); } $content = wp_remote_retrieve_body($response); if (empty($content)) { wp_send_json_error(array( 'message' => 'Remote content is empty', 'code' => 'empty_content' )); } wp_send_json_success(array( 'html' => $content, 'content' => $content, 'url' => $url, 'message' => 'Content fetched successfully' )); } catch (Exception $e) { wp_send_json_error(array( 'message' => 'Exception: ' . $e->getMessage(), 'code' => 'exception' )); } } public function aiautotool_save_tts_audio_callback() { check_ajax_referer('aiautotool_aipost_nonce', 'security'); $audio_url = isset($_POST['audio_url']) ? esc_url_raw(wp_unslash($_POST['audio_url'])) : ''; $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : __('Article narration', 'ai-auto-tool'); if (empty($audio_url)) { wp_send_json_error(array('message' => __('Audio URL is required', 'ai-auto-tool'))); } if ($post_id > 0 && !current_user_can('edit_post', $post_id)) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } if ($post_id <= 0 && !current_user_can('upload_files')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $tmp_file = download_url($audio_url, 60); if (is_wp_error($tmp_file)) { wp_send_json_error(array('message' => $tmp_file->get_error_message())); } $path = wp_parse_url($audio_url, PHP_URL_PATH); $source_name = $path ? basename($path) : ''; if (empty($source_name) || false === strpos($source_name, '.')) { $source_name = sanitize_title($title) . '-' . time() . '.mp3'; } $file_array = array( 'name' => sanitize_file_name($source_name), 'tmp_name' => $tmp_file, ); $filetype = wp_check_filetype($file_array['name']); if (empty($filetype['type']) || 'audio/mpeg' !== $filetype['type']) { @unlink($tmp_file); wp_send_json_error(array('message' => __('Only MP3 audio can be saved', 'ai-auto-tool'))); } $attachment_id = media_handle_sideload($file_array, $post_id, $title); if (is_wp_error($attachment_id)) { @unlink($tmp_file); wp_send_json_error(array('message' => $attachment_id->get_error_message())); } wp_send_json_success(array( 'attachment_id' => $attachment_id, 'url' => wp_get_attachment_url($attachment_id), 'title' => get_the_title($attachment_id), )); } private function aiautotool_get_voice_manager() { if (!class_exists('AIAutotool_AI_Voice_Manager')) { $voice_manager_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_voice_manager.php'; if (file_exists($voice_manager_file)) { require_once $voice_manager_file; } } return class_exists('AIAutotool_AI_Voice_Manager') ? AIAutotool_AI_Voice_Manager::get_instance() : null; } public function aiautotool_generate_tts_audio_callback() { check_ajax_referer('aiautotool_aipost_nonce', 'security'); $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; if ($post_id > 0 && !current_user_can('edit_post', $post_id)) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } if ($post_id <= 0 && !current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : __('Article narration', 'ai-auto-tool'); $text = isset($_POST['text']) ? wp_unslash($_POST['text']) : ''; $provider = isset($_POST['provider']) ? sanitize_key($_POST['provider']) : ''; $model = isset($_POST['model']) ? sanitize_text_field(wp_unslash($_POST['model'])) : ''; $voice = isset($_POST['voice']) ? sanitize_text_field(wp_unslash($_POST['voice'])) : ''; $voice_manager = $this->aiautotool_get_voice_manager(); if (!$voice_manager) { wp_send_json_error(array('message' => __('AI Voice manager is not available', 'ai-auto-tool'))); } if ($post_id > 0 && empty($text)) { $result = $voice_manager->generate_from_post($post_id, array( 'provider' => $provider, 'model' => $model, 'voice' => $voice, 'skip_urls' => true, )); } else { $result = $voice_manager->generate_audio($text, array( 'post_id' => $post_id, 'title' => $title, 'provider' => $provider, 'model' => $model, 'voice' => $voice, 'skip_urls' => true, )); } if (empty($result['success'])) { wp_send_json_error(array('message' => isset($result['error']) ? $result['error'] : __('Could not generate MP3', 'ai-auto-tool'))); } wp_send_json_success(array( 'attachment_id' => $result['attachment_id'], 'audio_url' => $result['url'], 'local_audio_url' => $result['url'], 'provider' => $result['provider'], 'model' => $result['model'], 'voice' => $result['voice'], 'characters' => $result['characters'], 'bytes' => $result['bytes'], )); } public function aiautotool_maybe_queue_auto_tts($new_status, $old_status, $post) { if ($new_status !== 'publish' || $old_status === 'publish' || empty($post->ID)) { return; } if (get_option('aiautotool_tts_auto_generate_on_publish', '0') !== '1') { return; } if (wp_is_post_revision($post->ID) || get_post_meta($post->ID, '_aiautotool_tts_audio', true)) { return; } if (!wp_next_scheduled('aiautotool_generate_post_tts_event', array((int) $post->ID))) { wp_schedule_single_event(time() + 30, 'aiautotool_generate_post_tts_event', array((int) $post->ID)); } } public function aiautotool_generate_post_tts_event($post_id) { $post_id = (int) $post_id; if ($post_id <= 0 || get_post_status($post_id) !== 'publish') { return; } $voice_manager = $this->aiautotool_get_voice_manager(); if (!$voice_manager) { return; } $result = $voice_manager->generate_from_post($post_id, array( 'skip_urls' => true, )); if (empty($result['success'])) { update_post_meta($post_id, '_aiautotool_tts_last_error', isset($result['error']) ? $result['error'] : 'TTS generation failed'); } else { delete_post_meta($post_id, '_aiautotool_tts_last_error'); } } public function aiautotool_register_voice_video_rest_routes() { register_rest_route('aitool/v1', '/tts', array( 'methods' => 'POST', 'callback' => array($this, 'aiautotool_rest_generate_tts'), 'permission_callback' => function() { return current_user_can('edit_posts'); }, )); register_rest_route('aitool/v1', '/providers', array( 'methods' => 'GET', 'callback' => array($this, 'aiautotool_rest_get_voice_providers'), 'permission_callback' => function() { return current_user_can('edit_posts'); }, )); register_rest_route('aitool/v1', '/voices', array( 'methods' => 'GET', 'callback' => array($this, 'aiautotool_rest_get_voices'), 'permission_callback' => function() { return current_user_can('edit_posts'); }, )); register_rest_route('aitool/v1', '/status', array( 'methods' => 'GET', 'callback' => array($this, 'aiautotool_rest_get_media_status'), 'permission_callback' => function() { return current_user_can('edit_posts'); }, )); foreach (array('video', 'subtitle', 'publish') as $route) { register_rest_route('aitool/v1', '/' . $route, array( 'methods' => 'POST', 'callback' => array($this, 'aiautotool_rest_media_placeholder'), 'permission_callback' => function() { return current_user_can('edit_posts'); }, )); } } public function aiautotool_rest_generate_tts($request) { $post_id = (int) $request->get_param('post_id'); if ($post_id > 0 && !current_user_can('edit_post', $post_id)) { return new WP_Error('aiautotool_permission_denied', __('Permission denied', 'ai-auto-tool'), array('status' => 403)); } $voice_manager = $this->aiautotool_get_voice_manager(); if (!$voice_manager) { return new WP_Error('aiautotool_voice_unavailable', __('AI Voice manager is not available', 'ai-auto-tool'), array('status' => 500)); } $options = array( 'provider' => sanitize_key($request->get_param('provider')), 'model' => sanitize_text_field((string) $request->get_param('model')), 'voice' => sanitize_text_field((string) $request->get_param('voice')), 'skip_urls' => true, ); if ($post_id > 0) { $result = $voice_manager->generate_from_post($post_id, $options); } else { $text = (string) $request->get_param('text'); $options['title'] = sanitize_text_field((string) $request->get_param('title')); $result = $voice_manager->generate_audio($text, $options); } if (empty($result['success'])) { return new WP_Error('aiautotool_tts_failed', isset($result['error']) ? $result['error'] : __('Could not generate MP3', 'ai-auto-tool'), array('status' => 500)); } return rest_ensure_response($result); } public function aiautotool_rest_get_voice_providers() { $voice_manager = $this->aiautotool_get_voice_manager(); if (!$voice_manager) { return rest_ensure_response(array('providers' => array())); } return rest_ensure_response($voice_manager->get_config()); } public function aiautotool_rest_get_voices() { return rest_ensure_response(array( 'voices' => array( array('provider' => 'openai', 'voice_id' => 'alloy', 'language' => 'multi', 'gender' => 'neutral', 'name' => 'Alloy'), array('provider' => 'openai', 'voice_id' => 'nova', 'language' => 'multi', 'gender' => 'female', 'name' => 'Nova'), array('provider' => 'openai', 'voice_id' => 'onyx', 'language' => 'multi', 'gender' => 'male', 'name' => 'Onyx'), array('provider' => 'elevenlabs', 'voice_id' => '21m00Tcm4TlvDq8ikWAM', 'language' => 'multi', 'gender' => 'female', 'name' => 'Rachel'), ), )); } public function aiautotool_rest_get_media_status() { $voice_manager = $this->aiautotool_get_voice_manager(); return rest_ensure_response(array( 'tts' => $voice_manager ? $voice_manager->get_usage_stats() : array(), 'video' => array('status' => 'planned', 'message' => 'Short video queue and renderer are prepared for the next implementation phase.'), 'subtitle' => array('status' => 'planned'), 'publish' => array('status' => 'planned'), )); } public function aiautotool_rest_media_placeholder($request) { return rest_ensure_response(array( 'success' => false, 'status' => 'planned', 'message' => __('This workflow endpoint is registered. Queue/render implementation will be added in the next phase.', 'ai-auto-tool'), )); } /** * AJAX callback to analyze image positions in content */ public function aiautotool_analyze_image_positions_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $content = isset($_POST['content']) ? sanitize_textarea_field(wp_unslash($_POST['content'])) : ''; $prompt = isset($_POST['prompt']) ? sanitize_textarea_field(wp_unslash($_POST['prompt'])) : ''; if (empty($content)) { wp_send_json_error('Content is required'); return; } try { $ai_response = $this->call_ai_api_for_image_analysis($prompt); if ($ai_response) { wp_send_json_success($ai_response); } else { wp_send_json_error('Failed to analyze content with AI'); } } catch (Exception $e) { wp_send_json_error('Error: ' . $e->getMessage()); } } /** * AJAX callback to generate English image prompt */ public function aiautotool_generate_english_prompt_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : ''; $paragraph = isset($_POST['paragraph']) ? sanitize_textarea_field(wp_unslash($_POST['paragraph'])) : ''; $ai_analysis = isset($_POST['ai_analysis']) ? json_decode(stripslashes(wp_unslash($_POST['ai_analysis'])), true) : array(); $prompt = isset($_POST['prompt']) ? sanitize_textarea_field(wp_unslash($_POST['prompt'])) : ''; if (empty($title) || empty($paragraph)) { wp_send_json_error('Title and paragraph are required'); return; } try { $english_prompt = str_replace("\n", " ", strip_tags($this->call_ai_api_for_english_prompt($prompt))); if ($english_prompt) { wp_send_json_success($english_prompt); } else { wp_send_json_error('Failed to generate English prompt with AI'); } } catch (Exception $e) { wp_send_json_error('Error: ' . $e->getMessage()); } } /** * Call AI API for English prompt generation */ private function call_ai_api_for_english_prompt($prompt) { return $this->call_ai_provider_for_suggest_images($prompt, array( 'temperature' => 0.4, 'max_tokens' => 700, 'timeout' => 75, )); } /** * Call AI API for image analysis */ private function call_ai_api_for_image_analysis($prompt) { return $this->call_ai_provider_for_suggest_images($prompt, array( 'temperature' => 0.2, 'max_tokens' => 1400, 'timeout' => 90, )); } /** * Call the configured AI Provider for Suggest Image planning. */ private function call_ai_provider_for_suggest_images($prompt, $options = array()) { if (!class_exists('AIAutotool_AI_Helper')) { $helper_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_helper.php'; if (file_exists($helper_file)) { require_once $helper_file; } } if (!class_exists('AIAutotool_AI_Helper')) { return false; } $result = AIAutotool_AI_Helper::generate($prompt, $options); if (!empty($result['success']) && isset($result['content'])) { return trim((string) $result['content']); } return false; } /** * Helper function to search Google using Custom Search API * * @param string $query Search query * @param string $lang Language code * @return array|false Search results or false on error */ private function search_google_custom_search($query, $lang = 'en') { if (defined('WP_DEBUG') && WP_DEBUG) { } // Get Google Custom Search API settings $api_key = get_option('aiautotool_google_search_api_key', ''); $cx_id = get_option('aiautotool_google_search_cx_id', ''); if (defined('WP_DEBUG') && WP_DEBUG) { } // If no API key or CX ID, try to get from general settings if (empty($api_key) || empty($cx_id)) { // Try to get from WordPress options directly if (empty($api_key)) { $api_key = get_option('google_search_api_key', ''); if (defined('WP_DEBUG') && WP_DEBUG) { } } if (empty($cx_id)) { $cx_id = get_option('google_search_cx_id', ''); if (defined('WP_DEBUG') && WP_DEBUG) { } } } // If still no API key or CX ID, use scraping fallback if (empty($api_key) || empty($cx_id)) { if (defined('WP_DEBUG') && WP_DEBUG) { } $scrape_result = $this->search_google_scrape($query, $lang); if (defined('WP_DEBUG') && WP_DEBUG) { } return $scrape_result; } // Build search URL $search_url = 'https://www.googleapis.com/customsearch/v1'; $search_url .= '?key=' . urlencode(trim($api_key)); $search_url .= '&cx=' . urlencode(trim($cx_id)); $search_url .= '&q=' . urlencode($query); $search_url .= '&num=10'; // Get 10 results // Add language parameter if available if (!empty($lang)) { $lang_map = array( 'vietnamese' => 'lang_vi', 'vi' => 'lang_vi', 'english' => 'lang_en', 'en' => 'lang_en' ); $lang_lower = strtolower($lang); if (isset($lang_map[$lang_lower])) { $search_url .= '&lr=' . $lang_map[$lang_lower]; } } if (defined('WP_DEBUG') && WP_DEBUG) { } // Make request using wp_remote_get $response = wp_remote_get($search_url, array( 'timeout' => 30, 'sslverify' => true )); if (is_wp_error($response)) { if (defined('WP_DEBUG') && WP_DEBUG) { $error_data = $response->get_error_data(); if ($error_data) { } } return false; } $body = wp_remote_retrieve_body($response); $status_code = wp_remote_retrieve_response_code($response); if (defined('WP_DEBUG') && WP_DEBUG) { } if ($status_code !== 200) { if (defined('WP_DEBUG') && WP_DEBUG) { } return false; } $data = json_decode($body, true); if (defined('WP_DEBUG') && WP_DEBUG) { if (json_last_error() !== JSON_ERROR_NONE) { } else { } } if (isset($data['error'])) { if (defined('WP_DEBUG') && WP_DEBUG) { if (isset($data['error']['message'])) { } if (isset($data['error']['code'])) { } } return false; } // Format results $results = array(); if (isset($data['items']) && is_array($data['items'])) { if (defined('WP_DEBUG') && WP_DEBUG) { } foreach ($data['items'] as $index => $item) { $results[] = array( 'title' => isset($item['title']) ? $item['title'] : '', 'link' => isset($item['link']) ? $item['link'] : '', 'snippet' => isset($item['snippet']) ? $item['snippet'] : '', 'displayLink' => isset($item['displayLink']) ? $item['displayLink'] : '' ); } } else { if (defined('WP_DEBUG') && WP_DEBUG) { if (isset($data['items'])) { } } } if (defined('WP_DEBUG') && WP_DEBUG) { } return !empty($results) ? $results : false; } /** * Scrape Google search results (fallback when API is not available) * WARNING: CHỈ DÙNG ĐỂ TEST – Google sẽ chặn IP sau vài lần * * @param string $query Search query * @param string $lang Language code * @return array|false Array of search results or false on error */ private function search_google_scrape($query, $lang = 'en') { // Map language codes to Google language codes $lang_map = array( 'vietnamese' => 'vi', 'vi' => 'vi', 'english' => 'en', 'en' => 'en' ); $lang_lower = strtolower($lang); $hl_param = isset($lang_map[$lang_lower]) ? $lang_map[$lang_lower] : 'en'; // Build search URL $encoded_query = urlencode($query); $url = "https://www.google.com/search?q=" . $encoded_query . "&hl=" . $hl_param . "&num=10"; // Use wp_remote_get instead of curl for WordPress compatibility $response = wp_remote_get($url, array( 'timeout' => 15, 'sslverify' => true, 'headers' => array( 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' ), 'redirection' => 5 )); if (is_wp_error($response)) { if (defined('WP_DEBUG') && WP_DEBUG) { } return false; } $html = wp_remote_retrieve_body($response); $status_code = wp_remote_retrieve_response_code($response); if ($status_code !== 200 || empty($html)) { if (defined('WP_DEBUG') && WP_DEBUG) { } return false; } $results = array(); $links = array(); // Method 1: Try to extract links from /url?q= pattern (matching user's example) preg_match_all('/]*>(.*?)<\/span>/is', $html, $snippet_match)) { $snippet = trim(strip_tags($snippet_match[1])); } elseif (preg_match('/' . $escaped_link . '.*?]*class="[^"]*[sS][^"]*"[^>]*>(.*?)<\/div>/is', $html, $snippet_match)) { $snippet = trim(strip_tags($snippet_match[1])); } if (!empty($link)) { $results[] = array( 'title' => $title ?: ($displayLink ?: $link), 'link' => $link, 'snippet' => $snippet, 'displayLink' => $displayLink ?: '' ); } } } // Method 2: If no results, try alternative pattern (Google's newer structure) if (empty($results)) { // Try to match result blocks if (preg_match_all('/]*class="[^"]*g[^"]*"[^>]*>(.*?)<\/div>/is', $html, $result_blocks)) { foreach ($result_blocks[1] as $block) { $result_item = array(); // Extract link if (preg_match('/]+href="([^"]+)"/', $block, $link_match)) { $link = $link_match[1]; if (strpos($link, '/url?q=') === 0) { $link = urldecode(substr($link, 7)); } // Filter out Google internal links if (strpos($link, 'webcache.googleusercontent') === false && strpos($link, 'google.com') === false) { $result_item['link'] = $link; $result_item['displayLink'] = parse_url($link, PHP_URL_HOST) ?: ''; } } // Extract title if (preg_match('/]*>(.*?)<\/h3>/is', $block, $title_match)) { $result_item['title'] = strip_tags($title_match[1]); } // Extract snippet if (preg_match('/]*class="[^"]*[sS][^"]*"[^>]*>(.*?)<\/span>/is', $block, $snippet_match)) { $result_item['snippet'] = strip_tags($snippet_match[1]); } if (!empty($result_item['link']) && count($results) < 10) { $results[] = array( 'title' => isset($result_item['title']) ? $result_item['title'] : '', 'link' => $result_item['link'], 'snippet' => isset($result_item['snippet']) ? $result_item['snippet'] : '', 'displayLink' => isset($result_item['displayLink']) ? $result_item['displayLink'] : '' ); } } } } // If still no results, return at least the links we found if (empty($results) && !empty($links)) { foreach ($links as $link) { $results[] = array( 'title' => parse_url($link, PHP_URL_HOST) ?: $link, 'link' => $link, 'snippet' => '', 'displayLink' => parse_url($link, PHP_URL_HOST) ?: '' ); } } if (defined('WP_DEBUG') && WP_DEBUG) { } return !empty($results) ? $results : false; } public function aiautotool_write_article_with_google_search_callback() { // Verify nonce for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) { // For SSE, we need to send error via stream require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Security check failed. Please refresh the page and try again.'); $stream->close(); return; } if (!current_user_can('edit_posts')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Permission denied'); $stream->close(); return; } } // Check if user has active Pro license or trial access. if (!function_exists('aiautotool_can_use_pro_features') || !aiautotool_can_use_pro_features()) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('This feature requires a Pro account. Please upgrade to Pro to use this feature.'); $stream->close(); return; } // Load rendersetting class if not already loaded if (!class_exists('rendersetting')) { $rendersetting_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/setting.php'; if (file_exists($rendersetting_file)) { require_once $rendersetting_file; } } // Get data from POST $data = array(); if (isset($_POST['data']) && is_string($_POST['data'])) { $data = json_decode(stripslashes($_POST['data']), true); } else { $raw_data = file_get_contents('php://input'); $data = json_decode($raw_data, true); } if (!$data || !is_array($data)) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Invalid JSON data'); $stream->close(); return; } // Extract parameters $title = isset($data['title']) ? sanitize_text_field($data['title']) : ''; $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'Vietnamese'; $resolved_ai_selection = $this->aiautotool_resolve_provider_model_selection( isset($data['model']) ? $data['model'] : '', isset($data['provider_id']) ? $data['provider_id'] : '' ); $model = $resolved_ai_selection['model']; $provider_id = $resolved_ai_selection['provider_id']; $message_id = isset($data['message_id']) ? sanitize_text_field($data['message_id']) : ''; // Extract article settings $target_audience = isset($data['targetAudience']) ? sanitize_text_field($data['targetAudience']) : ''; $tone = isset($data['tone']) ? sanitize_text_field($data['tone']) : ''; $length_type = isset($data['lengthType']) ? sanitize_text_field($data['lengthType']) : ''; $competitors = isset($data['competitors']) && is_array($data['competitors']) ? array_map('esc_url_raw', array_filter($data['competitors'])) : array(); $brand_voice_rules = isset($data['brandVoiceRules']) ? sanitize_textarea_field($data['brandVoiceRules']) : ''; if (empty($title)) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Title parameter is required'); $stream->close(); return; } // Load SSE Stream class require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php'; // Load Google Search class if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/google-search.php')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/google-search.php'; } // Load AI Helper and AI Agent for new AI Provider system if (file_exists(plugin_dir_path(__FILE__) . 'inc/ai-providers/aiautotool_ai_helper.php')) { require_once plugin_dir_path(__FILE__) . 'inc/ai-providers/aiautotool_ai_helper.php'; } // Initialize BardGenContent for fallback $bardGenContent = new BardGenContent(); // Helper function to convert markdown to HTML (same as original function) $convert_markdown_to_html = function($text) { if (empty($text)) { return ''; } // Check if content is already HTML (has HTML tags) $has_html = preg_match('/<[a-z][\s\S]*>/i', $text); if ($has_html) { if (defined('WP_DEBUG') && WP_DEBUG) { } return $text; // Already HTML, return as is } // Try Parsedown first $parsedown_loaded = false; if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/Parsedown.php')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/Parsedown.php'; $parsedown_loaded = class_exists('Parsedown'); } if ($parsedown_loaded) { $parsedown = new Parsedown(); $html = $parsedown->text($text); if (defined('WP_DEBUG') && WP_DEBUG) { } return $html; } // Try markdown parser function if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/markdown-parser.php')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/markdown-parser.php'; if (function_exists('markdown')) { $html = markdown($text); if (defined('WP_DEBUG') && WP_DEBUG) { } return $html; } } // Fallback to simple inline parser $html = preg_replace('/^######\s+(.+)$/m', '
$1
', $text); $html = preg_replace('/^#####\s+(.+)$/m', '
$1
', $html); $html = preg_replace('/^####\s+(.+)$/m', '

$1

', $html); $html = preg_replace('/^###\s+(.+)$/m', '

$1

', $html); $html = preg_replace('/^##\s+(.+)$/m', '

$1

', $html); $html = preg_replace('/^#\s+(.+)$/m', '

$1

', $html); $html = preg_replace_callback('/```([\s\S]*?)```/m', function($matches) { return '
' . esc_html(trim($matches[1])) . '
'; }, $html); $html = preg_replace('/`([^`]+)`/', '$1', $html); $html = preg_replace('/\*\*(.+?)\*\*/', '$1', $html); $html = preg_replace('/__(.+?)__/', '$1', $html); $html = preg_replace('/(?$1', $html); $html = preg_replace('/(?$1', $html); $html = preg_replace('/\[([^\]]+)\]\(([^)]+)\)/', '
$1', $html); $html = preg_replace('/!\[([^\]]*)\]\(([^)]+)\)/', '$1', $html); $html = preg_replace('/^>\s+(.+)$/m', '
$1
', $html); $html = preg_replace('/^[\-\*]\s+(.+)$/m', '
  • $1
  • ', $html); $html = preg_replace('/(
  • .*<\/li>\n?)+/s', '', $html); $html = preg_replace('/^\d+\.\s+(.+)$/m', '
  • $1
  • ', $html); $html = preg_replace('/\n\n+/', '

    ', $html); $html = '

    ' . $html . '

    '; $html = preg_replace('/

    \s*<\/p>/', '', $html); $html = preg_replace('/

    (<[^>]+>)/', '$1

    ', $html); $html = preg_replace('/(<\/[^>]+>)<\/p>/', '$1', $html); if (defined('WP_DEBUG') && WP_DEBUG) { } return $html; }; // Track last AI call time to ensure minimum 10 seconds between calls $last_ai_call_time_2 = 0; $min_ai_call_interval_2 = 10; // Minimum seconds between AI calls // Helper function to generate content using AI Agent with fallback (same as original) $generate_with_agent = function($prompt, $lang, $model, $provider_id = '', $options = array()) use ($bardGenContent, &$last_ai_call_time_2, $min_ai_call_interval_2) { // Ensure minimum 10 seconds between AI calls $current_time = time(); $time_since_last_call = $current_time - $last_ai_call_time_2; if ($last_ai_call_time_2 > 0 && $time_since_last_call < $min_ai_call_interval_2) { $wait_time = $min_ai_call_interval_2 - $time_since_last_call; if (defined('WP_DEBUG') && WP_DEBUG) { } sleep($wait_time); } // Update last call time before making the call $last_ai_call_time_2 = time(); // Try AI Agent first if available if (class_exists('AIAutotool_AI_Agent')) { $agent = AIAutotool_AI_Agent::get_instance(); // Determine use case based on prompt content $use_case = 'general'; $prompt_lower = strtolower($prompt); if (stripos($prompt_lower, 'checklist') !== false || stripos($prompt_lower, 'danh sách') !== false) { $use_case = 'fast'; } elseif (stripos($prompt_lower, 'phân tích') !== false || stripos($prompt_lower, 'analyze') !== false) { $use_case = 'reasoning'; } elseif (strlen($prompt) > 2000) { $use_case = 'long_context'; } if (isset($options['use_case'])) { $use_case = $options['use_case']; } $agent_options = array_merge(array( 'use_case' => $use_case, 'temperature' => 0.7, 'max_tokens' => isset($options['max_tokens']) ? $options['max_tokens'] : 2000 ), $options); if (!empty($provider_id)) { $agent_options['provider'] = $provider_id; if (!empty($model)) { $agent_options['model'] = $model; } } $result = $agent->generate($prompt, $agent_options); if ($result['success'] && !empty($result['content'])) { if (defined('WP_DEBUG') && WP_DEBUG) { } return array( 'code' => '200', 'result' => $result['content'], 'provider' => $result['provider'], 'model' => $result['model'] ); } else { if (defined('WP_DEBUG') && WP_DEBUG) { } } } if (defined('WP_DEBUG') && WP_DEBUG) { } return $bardGenContent->bardcontentmore($prompt, $lang, $model); }; // Helper function to generate language instruction (same as original) $get_language_instruction = function($lang) { $lang_lower = strtolower(trim($lang)); $lang_instruction = ''; if (strpos($lang_lower, 'vietnamese') !== false || strpos($lang_lower, 'tiếng việt') !== false || $lang_lower === 'vi' || $lang_lower === 'vie') { $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n"; $lang_instruction .= "You MUST respond ONLY in Vietnamese (Tiếng Việt).\n"; $lang_instruction .= "ALL your output MUST be in Vietnamese language only.\n"; $lang_instruction .= "DO NOT use English or any other language.\n"; $lang_instruction .= "Response language: Vietnamese (Tiếng Việt) ONLY.\n\n"; } elseif (strpos($lang_lower, 'english') !== false || $lang_lower === 'en' || $lang_lower === 'eng') { $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n"; $lang_instruction .= "You MUST respond ONLY in English.\n"; $lang_instruction .= "ALL your output MUST be in English language only.\n"; $lang_instruction .= "DO NOT use Vietnamese or any other language.\n"; $lang_instruction .= "Response language: English ONLY.\n\n"; } else { $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n"; $lang_instruction .= "You MUST respond ONLY in {$lang} language.\n"; $lang_instruction .= "ALL your output MUST be in {$lang} language only.\n"; $lang_instruction .= "DO NOT use any other language.\n"; $lang_instruction .= "Response language: {$lang} ONLY.\n\n"; } return $lang_instruction; }; // Helper function to find related posts (same as original) $find_related_posts_for_internal_linking = function($title, $keywords_text, $lang, $article_text = '', $limit = 5) { $related_posts = array(); $keywords_summary = mb_substr(strip_tags($keywords_text), 0, 200, 'UTF-8'); $keywords_summary = preg_replace('/\s+/', ' ', trim($keywords_summary)); $keywords_array = array(); $lines = explode("\n", $keywords_text); foreach ($lines as $line) { $line = trim(strip_tags($line)); if (!empty($line) && strlen($line) > 3) { $line = preg_replace('/^[\d\-\*\.\s]+/', '', $line); if (!empty($line)) { $keywords_array[] = $line; if (count($keywords_array) >= 5) break; } } } if (empty($keywords_array)) { $title_words = explode(' ', $title); $keywords_array = array_slice($title_words, 0, 3); } $search_query = implode(' ', array_slice($keywords_array, 0, 3)); $args_by_keywords = array( 'post_type' => 'post', 'posts_per_page' => $limit * 2, 'post_status' => 'publish', 's' => $search_query, 'orderby' => 'relevance', 'order' => 'DESC', ); if (function_exists('pll_get_post_language')) { $args_by_keywords['lang'] = $lang; } $query_by_keywords = new WP_Query($args_by_keywords); if ($query_by_keywords->have_posts()) { while ($query_by_keywords->have_posts()) { $query_by_keywords->the_post(); $post_id = get_the_ID(); $post_title = get_the_title(); $post_url = get_permalink(); $post_excerpt = get_the_excerpt(); $relevance_score = 0; $title_lower = mb_strtolower($title, 'UTF-8'); $post_title_lower = mb_strtolower($post_title, 'UTF-8'); foreach ($keywords_array as $keyword) { $keyword_lower = mb_strtolower($keyword, 'UTF-8'); if (mb_strpos($post_title_lower, $keyword_lower) !== false) { $relevance_score += 3; } if (mb_strpos($post_excerpt, $keyword_lower) !== false) { $relevance_score += 1; } } similar_text($title_lower, $post_title_lower, $similarity); $relevance_score += $similarity / 10; $related_posts[] = array( 'id' => $post_id, 'title' => $post_title, 'url' => $post_url, 'excerpt' => mb_substr($post_excerpt, 0, 150, 'UTF-8'), 'relevance_score' => $relevance_score ); } wp_reset_postdata(); } if (!empty($keywords_array)) { $tag_names = array_slice($keywords_array, 0, 3); $args_by_tags = array( 'post_type' => 'post', 'posts_per_page' => $limit, 'post_status' => 'publish', 'tag_slug__in' => array_map(function($tag) { return sanitize_title($tag); }, $tag_names), 'orderby' => 'date', 'order' => 'DESC', ); if (function_exists('pll_get_post_language')) { $args_by_tags['lang'] = $lang; } $query_by_tags = new WP_Query($args_by_tags); if ($query_by_tags->have_posts()) { while ($query_by_tags->have_posts()) { $query_by_tags->the_post(); $post_id = get_the_ID(); $post_title = get_the_title(); $post_url = get_permalink(); $post_excerpt = get_the_excerpt(); $exists = false; foreach ($related_posts as $existing) { if ($existing['id'] == $post_id) { $exists = true; break; } } if (!$exists) { $relevance_score = 2; $related_posts[] = array( 'id' => $post_id, 'title' => $post_title, 'url' => $post_url, 'excerpt' => mb_substr($post_excerpt, 0, 150, 'UTF-8'), 'relevance_score' => $relevance_score ); } } wp_reset_postdata(); } } usort($related_posts, function($a, $b) { return $b['relevance_score'] <=> $a['relevance_score']; }); return array_slice($related_posts, 0, $limit); }; // Debug logging if (defined('WP_DEBUG') && WP_DEBUG) { } $stream = new AIAutoTool_SSE_Stream(); $stream->start(); if (!empty($message_id)) { $stream->set_message_id($message_id); } try { // Step 1: Search Google for latest content and fetch URLs content $stream->send_step_start(1, 'search_google', 'Searching Google for latest content...'); $google_search_results = array(); $google_search_text = ''; $urls_content = array(); $search_debug_info = array(); // Debug: Check if new class exists $has_new_class = class_exists('AIAutoTool_Google_Search'); if (defined('WP_DEBUG') && WP_DEBUG) { $search_debug_info[] = 'AIAutoTool_Google_Search class: ' . ($has_new_class ? 'Available' : 'Not available'); } // Try using new Google Search class first if ($has_new_class) { if (defined('WP_DEBUG') && WP_DEBUG) { } // Try method 1: Use get_simple_results() first (simplest method like in test file) $search_options = array( 'timeout' => 30, 'params' => array( 'hl' => ($lang === 'Vietnamese' || strpos(strtolower($lang), 'vi') !== false) ? 'vi' : 'en', 'gl' => ($lang === 'Vietnamese' || strpos(strtolower($lang), 'vi') !== false) ? 'vn' : 'us' ) ); $simple_results = AIAutoTool_Google_Search::get_simple_results($title, $search_options); if (defined('WP_DEBUG') && WP_DEBUG) { if (is_wp_error($simple_results)) { } elseif (is_array($simple_results)) { } } // Check if error is due to missing Jina AI API key if (is_wp_error($simple_results) && $simple_results->get_error_code() === 'no_api_key') { $error_message = $simple_results->get_error_message(); $stream->send_error($error_message); $stream->close(); return; } // Check if blocked by Google if (is_wp_error($simple_results) && $simple_results->get_error_code() === 'blocked') { if (defined('WP_DEBUG') && WP_DEBUG) { $search_debug_info[] = 'Google blocked request - Trying fallbacks'; } // Try Custom Search API first $google_search_results = $this->search_google_custom_search($title, $lang); if ($google_search_results !== false && is_array($google_search_results) && !empty($google_search_results)) { $search_debug_info[] = 'Custom Search API: Success - ' . count($google_search_results) . ' results'; } else { // Try Jina AI Search as fallback if (defined('WP_DEBUG') && WP_DEBUG) { $search_debug_info[] = 'Custom Search API: Failed - Trying Jina AI Search'; } $jina_result = AIAutoTool_Google_Search::search_jina_ai($title, $search_options); // Check if error is due to missing API key if (is_wp_error($jina_result) && $jina_result->get_error_code() === 'no_api_key') { $error_message = $jina_result->get_error_message(); $stream->send_error($error_message); $stream->close(); return; } if (!is_wp_error($jina_result) && isset($jina_result['results']['organic']) && !empty($jina_result['results']['organic'])) { // Format Jina AI results foreach ($jina_result['results']['organic'] as $index => $item) { $result_item = array( 'title' => isset($item['title']) ? $item['title'] : 'No title', 'link' => isset($item['url']) ? $item['url'] : '', 'snippet' => isset($item['snippet']) ? $item['snippet'] : '', 'displayLink' => isset($item['url']) ? parse_url($item['url'], PHP_URL_HOST) : '' ); $google_search_results[] = $result_item; } $search_debug_info[] = 'Jina AI Search: Success - ' . count($google_search_results) . ' results'; } else { $search_debug_info[] = 'All fallbacks failed - ' . (is_wp_error($jina_result) ? $jina_result->get_error_message() : ($simple_results->get_error_message() ?: 'No results')); } } } elseif (!is_wp_error($simple_results) && is_array($simple_results) && !empty($simple_results)) { if (defined('WP_DEBUG') && WP_DEBUG) { } // Format results from simple_results foreach ($simple_results as $index => $item) { $result_item = array( 'title' => isset($item['title']) ? $item['title'] : 'No title', 'link' => isset($item['url']) ? $item['url'] : '', 'snippet' => isset($item['snippet']) ? $item['snippet'] : '', 'displayLink' => isset($item['url']) ? parse_url($item['url'], PHP_URL_HOST) : '' ); $google_search_results[] = $result_item; } $search_debug_info[] = 'get_simple_results: Success - ' . count($google_search_results) . ' results'; } else { // Try method 2: Use search() directly if (defined('WP_DEBUG') && WP_DEBUG) { } $search_result = AIAutoTool_Google_Search::search($title, $search_options); if (defined('WP_DEBUG') && WP_DEBUG) { if (is_wp_error($search_result)) { $search_debug_info[] = 'search() error: ' . $search_result->get_error_message(); // If blocked, try Custom Search API if ($search_result->get_error_code() === 'blocked') { $google_search_results = $this->search_google_custom_search($title, $lang); if ($google_search_results !== false && is_array($google_search_results) && !empty($google_search_results)) { $search_debug_info[] = 'Custom Search API fallback: Success - ' . count($google_search_results) . ' results'; } } } elseif (is_array($search_result)) { if (isset($search_result['results']['organic'])) { } } } if (!is_wp_error($search_result) && isset($search_result['results']['organic']) && is_array($search_result['results']['organic']) && !empty($search_result['results']['organic'])) { if (defined('WP_DEBUG') && WP_DEBUG) { } // Format results from search() organic results foreach ($search_result['results']['organic'] as $index => $item) { $result_item = array( 'title' => isset($item['title']) ? $item['title'] : 'No title', 'link' => isset($item['url']) ? $item['url'] : '', 'snippet' => isset($item['snippet']) ? $item['snippet'] : '', 'displayLink' => isset($item['url']) ? parse_url($item['url'], PHP_URL_HOST) : '' ); $google_search_results[] = $result_item; } $search_debug_info[] = 'search() method: Success - ' . count($google_search_results) . ' results'; } else { // Try method 3: Use search_and_get_content (may fail if no URLs, but try anyway) if (defined('WP_DEBUG') && WP_DEBUG) { } $search_limit = 5; $search_content_options = array_merge($search_options, array( 'format' => 'markdown', 'delay' => 2 )); $search_content_result = AIAutoTool_Google_Search::search_and_get_content($title, $search_limit, $search_content_options); if (defined('WP_DEBUG') && WP_DEBUG) { if (is_wp_error($search_content_result)) { $search_debug_info[] = 'search_and_get_content error: ' . $search_content_result->get_error_message(); } elseif (is_array($search_content_result)) { if (isset($search_content_result['results'])) { } } } if (!is_wp_error($search_content_result) && isset($search_content_result['results']) && is_array($search_content_result['results']) && !empty($search_content_result['results'])) { if (defined('WP_DEBUG') && WP_DEBUG) { } // Format results from search_and_get_content foreach ($search_content_result['results'] as $index => $item) { $result_item = array( 'title' => isset($item['search_title']) ? $item['search_title'] : 'No title', 'link' => isset($item['url']) ? $item['url'] : '', 'snippet' => isset($item['search_snippet']) ? $item['search_snippet'] : '', 'displayLink' => isset($item['url']) ? parse_url($item['url'], PHP_URL_HOST) : '' ); // If we got content from Jina AI, add it if (!empty($item['content']) && isset($item['content']['content'])) { $urls_content[] = array( 'url' => $item['url'], 'title' => $item['search_title'], 'content' => $item['content']['content'], 'length' => isset($item['content']['length']) ? $item['content']['length'] : strlen($item['content']['content']) ); // Add content preview to snippet $content_preview = mb_substr(strip_tags($item['content']['content']), 0, 300, 'UTF-8'); $result_item['snippet'] = $content_preview . '...'; $result_item['has_content'] = true; } else if (!empty($item['error'])) { $result_item['error'] = $item['error']; if (defined('WP_DEBUG') && WP_DEBUG) { } } $google_search_results[] = $result_item; } $search_debug_info[] = 'search_and_get_content: Success - ' . count($google_search_results) . ' results'; } else { // All methods failed, use fallback if (defined('WP_DEBUG') && WP_DEBUG) { $search_debug_info[] = 'All new class methods failed - Using fallback'; } $google_search_results = $this->search_google_custom_search($title, $lang); if (defined('WP_DEBUG') && WP_DEBUG) { if ($google_search_results === false) { $search_debug_info[] = 'Fallback method: Failed'; } elseif (is_array($google_search_results)) { $search_debug_info[] = 'Fallback method: Success - ' . count($google_search_results) . ' results'; } } } } } } else { // Fallback to old method if class not available if (defined('WP_DEBUG') && WP_DEBUG) { $search_debug_info[] = 'New class not available - Using fallback directly'; } $google_search_results = $this->search_google_custom_search($title, $lang); if (defined('WP_DEBUG') && WP_DEBUG) { if ($google_search_results === false) { $search_debug_info[] = 'Direct fallback: Failed'; } elseif (is_array($google_search_results)) { $search_debug_info[] = 'Direct fallback: Success - ' . count($google_search_results) . ' results'; } } } // Step 1.1: Extract full content from all URLs found in search results if ($google_search_results && is_array($google_search_results) && !empty($google_search_results)) { $stream->send_status('Extracting content from the URLs found...'); // Collect all URLs from search results $urls_to_fetch = array(); $urls_already_fetched = array(); // Check which URLs already have content foreach ($urls_content as $existing_content) { $urls_already_fetched[] = $existing_content['url']; } // Collect URLs that need content extraction foreach ($google_search_results as $result) { $url = isset($result['link']) ? $result['link'] : (isset($result['url']) ? $result['url'] : ''); if (!empty($url) && filter_var($url, FILTER_VALIDATE_URL)) { // Skip if already fetched or if marked as has_content if (!in_array($url, $urls_already_fetched) && (!isset($result['has_content']) || !$result['has_content'])) { $urls_to_fetch[] = array( 'url' => $url, 'title' => isset($result['title']) ? $result['title'] : '' ); } } } // Initialize failed URLs tracking array $failed_urls = array(); // Extract content from URLs that don't have it yet if (!empty($urls_to_fetch) && $has_new_class) { $stream->send_status('Extracting content from ' . count($urls_to_fetch) . ' URLs...'); if (defined('WP_DEBUG') && WP_DEBUG) { } $content_extraction_options = array( 'format' => 'markdown', 'delay' => 2, // Delay between requests to avoid rate limiting 'timeout' => 60 ); // Get API key if available if (class_exists('AIAutotool_AI_Provider_API_Keys')) { $jina_api_key = AIAutotool_AI_Provider_API_Keys::get_jina_key(); if (!empty($jina_api_key)) { $content_extraction_options['api_key'] = $jina_api_key; $content_extraction_options['jina_api_key'] = $jina_api_key; } } // Extract content from URLs $urls_only = array_column($urls_to_fetch, 'url'); $stream->send_status('Extracting content from ' . count($urls_only) . ' URLs...'); $content_results = AIAutoTool_Google_Search::get_multiple_urls_content($urls_only, $content_extraction_options); // Process extracted content - track failed URLs to skip them if (is_array($content_results)) { foreach ($content_results as $index => $content_result) { $url = $content_result['url']; $result_data = $content_result['result']; if (!is_wp_error($result_data)) { $extracted_content = isset($result_data['content']) ? $result_data['content'] : ''; $extracted_title = isset($result_data['title']) ? $result_data['title'] : (isset($urls_to_fetch[$index]['title']) ? $urls_to_fetch[$index]['title'] : ''); if (!empty($extracted_content)) { $urls_content[] = array( 'url' => $url, 'title' => $extracted_title, 'content' => $extracted_content, 'length' => strlen($extracted_content), 'source' => 'jina_ai' ); $stream->send_status('Content: ' . count($urls_content) . ' ...'); if (defined('WP_DEBUG') && WP_DEBUG) { } } else { // Content is empty, mark as failed $failed_urls[] = array( 'url' => $url, 'reason' => 'Content is empty' ); $stream->send_status('Content: Content is empty: ' . $url . ' ...'); if (defined('WP_DEBUG') && WP_DEBUG) { } } } else { // Error occurred, mark as failed and skip $error_msg = $result_data->get_error_message(); $failed_urls[] = array( 'url' => $url, 'reason' => $error_msg ); if (defined('WP_DEBUG') && WP_DEBUG) { } } } } // Log skipped URLs info if (!empty($failed_urls) && defined('WP_DEBUG') && WP_DEBUG) { foreach ($failed_urls as $failed) { } } } // Format search results text $google_search_text = "Latest information from Google search:\n\n"; // Track which URLs were successfully extracted $extracted_urls = array(); foreach ($urls_content as $content_item) { $extracted_urls[] = $content_item['url']; } foreach ($google_search_results as $index => $result) { $google_search_text .= ($index + 1) . ". " . (isset($result['title']) ? $result['title'] : 'No title') . "\n"; $google_search_text .= " " . (isset($result['snippet']) ? $result['snippet'] : '') . "\n"; $url = isset($result['link']) ? $result['link'] : (isset($result['url']) ? $result['url'] : ''); if (!empty($url)) { $google_search_text .= " Source: " . $url . "\n"; } // Check if we have full content for this URL $has_full_content = false; if (in_array($url, $extracted_urls) || (isset($result['has_content']) && $result['has_content'])) { $has_full_content = true; $google_search_text .= " ✓ Full content fetched\n"; } else { $google_search_text .= " ✗ Content extraction failed - skipped\n"; } $google_search_text .= "\n"; } // Add info about skipped URLs if any if (!empty($failed_urls)) { $google_search_text .= "\n=== URLs Đã Bỏ Qua (không trích xuất được) ===\n\n"; foreach ($failed_urls as $idx => $failed) { $google_search_text .= ($idx + 1) . ". " . $failed['url'] . "\n"; $google_search_text .= " Lý do: " . $failed['reason'] . "\n\n"; } $google_search_text .= "Tổng cộng: " . count($failed_urls) . " URL đã bỏ qua\n\n"; } // Add full extracted content (this will be used for article writing) if (!empty($urls_content)) { $google_search_text .= "\n=== Full Content from Sources (for article writing) ===\n\n"; $google_search_text .= "Đã trích xuất thành công nội dung từ " . count($urls_content) . " URL:\n\n"; foreach ($urls_content as $idx => $content_item) { $google_search_text .= "--- Source " . ($idx + 1) . ": " . $content_item['url'] . " ---\n"; $google_search_text .= "Title: " . $content_item['title'] . "\n"; $google_search_text .= "Content length: " . $content_item['length'] . " characters\n\n"; $google_search_text .= $content_item['content'] . "\n\n"; $google_search_text .= "=== End of Source " . ($idx + 1) . " ===\n\n\n"; } } // Prepare display message $display_message = "Kết quả tìm kiếm Google và nội dung đã trích xuất:\n\n"; $display_message .= "✓ Đã trích xuất thành công: " . count($urls_content) . " URL\n"; if (!empty($failed_urls)) { $display_message .= "✗ Đã bỏ qua: " . count($failed_urls) . " URL (không trích xuất được)\n"; } $display_message .= "\nNội dung đầy đủ sẽ được sử dụng trong các bước tiếp theo.\n"; $stream->send_step_output(1, '

    ' . esc_html($display_message) . '

    ' . esc_html(mb_substr($google_search_text, 0, 2000, 'UTF-8')) . (strlen($google_search_text) > 2000 ? '... (nội dung đầy đủ sẽ được sử dụng trong các bước tiếp theo)' : '') . '
    '); $stream->send_step_complete(1, 'success'); // CRITICAL VALIDATION: Check if we have at least ONE extracted content - MUST have content to continue if (empty($urls_content) || !is_array($urls_content) || count($urls_content) == 0) { $error_message = "Lỗi: Không thể trích xuất nội dung từ BẤT KỲ URL nào trong số các URL tìm được.\n\n"; $error_message .= "Bài viết CHỈ được viết dựa trên nội dung đã crawl được từ các URL.\n"; $error_message .= "Vui lòng thử lại hoặc kiểm tra cấu hình API (Jina AI API key).\n\n"; if (!empty($google_search_results)) { $error_message .= "Đã tìm thấy " . count($google_search_results) . " kết quả tìm kiếm, nhưng không thể trích xuất nội dung từ bất kỳ URL nào.\n\n"; $error_message .= "Các URL đã thử:\n"; foreach (array_slice($google_search_results, 0, 10) as $idx => $result) { $url = isset($result['link']) ? $result['link'] : (isset($result['url']) ? $result['url'] : ''); $error_message .= ($idx + 1) . ". " . $url . "\n"; } } if (!empty($failed_urls)) { $error_message .= "\nChi tiết lỗi:\n"; foreach ($failed_urls as $idx => $failed) { $error_message .= ($idx + 1) . ". " . $failed['url'] . " - " . $failed['reason'] . "\n"; } } if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_error($error_message); $stream->close(); return; } // Log success with info about skipped URLs if (defined('WP_DEBUG') && WP_DEBUG) { if (!empty($failed_urls)) { } foreach ($urls_content as $idx => $content_item) { } } // Send info about skipped URLs if any (as status, not error) if (!empty($failed_urls)) { $skip_message = "Lưu ý: Đã bỏ qua " . count($failed_urls) . " URL không trích xuất được. Sẽ tiếp tục với " . count($urls_content) . " URL đã trích xuất thành công."; $stream->send_status($skip_message); } } else { // If search fails, STOP - we cannot write article without search results and extracted content $error_message = "Lỗi: Không thể tìm kiếm trên Google hoặc không có kết quả.\n\n"; $error_message .= "QUAN TRỌNG: Bài viết CHỈ được viết dựa trên nội dung đã crawl được từ các URL tìm kiếm.\n"; $error_message .= "Không thể tiếp tục viết bài mà không có nội dung từ kết quả tìm kiếm.\n\n"; if (defined('WP_DEBUG') && WP_DEBUG && !empty($search_debug_info)) { $error_message .= "Thông tin debug:\n"; foreach ($search_debug_info as $info) { $error_message .= "- " . $info . "\n"; } $error_message .= "\n"; } if (defined('WP_DEBUG') && WP_DEBUG) { if (!empty($search_debug_info)) { } // Check API configuration $api_key = get_option('aiautotool_google_search_api_key', ''); $cx_id = get_option('aiautotool_google_search_cx_id', ''); } $stream->send_step_output(1, '

    Lỗi Tìm Kiếm Google:

    ' . nl2br(esc_html($error_message)) . '

    '); $stream->send_error($error_message); $stream->close(); return; } // Step 2: Generate Checklist (same as original but with Google search context) $stream->send_step_start(2, 'generate_checklist', 'Generating checklist...'); // Get website information $site_name = get_bloginfo('name'); $site_url = home_url(); // Get author information $current_user = wp_get_current_user(); $author_name = $current_user->display_name; $author_bio = get_user_meta($current_user->ID, 'description', true); $checklist_prompt = $get_language_instruction($lang); $checklist_prompt .= "You are an SEO Content Author with deep understanding of user intent and search behavior.\n\n"; $checklist_prompt .= "Your task: Analyze the topic based on the provided **title** and the extracted content from Google search results.\n\n"; $checklist_prompt .= "Input:\n\n"; $checklist_prompt .= "- title: \"{$title}\"\n\n"; // Add Google search results if available - emphasize using extracted content if (!empty($google_search_text)) { $checklist_prompt .= "Extracted content from Google search results (this is the ONLY content source - do not suggest creating new content):\n{$google_search_text}\n\n"; // Add emphasis if we have extracted content if (!empty($urls_content)) { $checklist_prompt .= "IMPORTANT: The above content has been fully extracted from the search result URLs. "; $checklist_prompt .= "Your analysis should be based ONLY on this extracted content. Do not suggest creating new content or adding information that is not present in the extracted content.\n\n"; } } $checklist_prompt .= "Output:\n\n"; $checklist_prompt .= "Provide a structured analysis including:\n\n"; $checklist_prompt .= "1. **User Intent Analysis**\n\n"; $checklist_prompt .= " - Người tìm kiếm với tiêu đề này đang muốn điều gì?\n\n"; $checklist_prompt .= " - Họ gặp vấn đề, nỗi đau, thắc mắc gì?\n\n"; $checklist_prompt .= " - Mục đích của họ là: tìm hiểu, so sánh, mua hàng, hay giải pháp?\n\n"; $checklist_prompt .= "2. **Search Intent Classification**\n\n"; $checklist_prompt .= " - Phân loại theo 3 nhóm:\n\n"; $checklist_prompt .= " - Informational (tìm hiểu)\n\n"; $checklist_prompt .= " - Commercial Investigation (cân nhắc)\n\n"; $checklist_prompt .= " - Transactional (muốn mua)\n\n"; $checklist_prompt .= " - Giải thích lý do chọn loại này.\n\n"; $checklist_prompt .= "3. **What Users Expect From This Article**\n\n"; $checklist_prompt .= " - Danh sách 5–10 thông tin, câu trả lời hoặc nội dung mà người dùng mong đợi.\n\n"; $checklist_prompt .= " - Điều gì khiến họ hài lòng sau khi đọc?\n\n"; $checklist_prompt .= "4. **What We Should Provide**\n\n"; $checklist_prompt .= " - Những mục nội dung cần có trong bài viết để thoả mãn user intent.\n\n"; $checklist_prompt .= " - Insight đặc biệt mà đối thủ thường thiếu.\n\n"; $checklist_prompt .= " - Nội dung cần ưu tiên + về lý do.\n\n"; $checklist_prompt .= "5. **SEO Opportunities**\n\n"; $checklist_prompt .= " - Gợi ý LSI keywords, entity liên quan.\n\n"; $checklist_prompt .= " - Gợi ý schema nên dùng.\n\n"; $checklist_prompt .= " - Định hướng cấu trúc bài chuẩn SEO.\n\n"; $checklist_prompt .= "Hãy trình bày phân tích một cách logic, có chiều sâu, theo phong cách tác giả chuyên nghiệp.\n\n"; $checklist_prompt .= "IMPORTANT: Return the analysis in JSON format only. Keep responses concise and structured. Use this JSON structure:\n"; $checklist_prompt .= "{\n"; $checklist_prompt .= " \"user_intent\": {\"what_they_want\": \"\", \"problems\": \"\", \"purpose\": \"\"},\n"; $checklist_prompt .= " \"search_intent\": {\"type\": \"\", \"reason\": \"\"},\n"; $checklist_prompt .= " \"user_expectations\": [],\n"; $checklist_prompt .= " \"content_to_provide\": {\"required_sections\": [], \"unique_insights\": \"\", \"priorities\": \"\"},\n"; $checklist_prompt .= " \"seo_opportunities\": {\"lsi_keywords\": [], \"schema\": \"\", \"structure\": \"\"}\n"; $checklist_prompt .= "}\n\n"; if (!empty($author_bio)) { $checklist_prompt .= "Author description: {$author_bio}\n\n"; } // Generate Checklist $checklist_text = ''; // Lấy provider_id từ settings nếu không có trong request if (empty($provider_id) && class_exists('AIAutotool_AI_Provider_Manager')) { $manager = AIAutotool_AI_Provider_Manager::get_instance(); $active_provider = $manager->get_active_provider(); if ($active_provider) { $provider_id = $active_provider->get_id(); } } if (defined('WP_DEBUG') && WP_DEBUG) { } $checklist_result = $generate_with_agent($checklist_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 2000, 'temperature' => 0.7, 'use_case' => 'reasoning' )); if (is_array($checklist_result) && isset($checklist_result['code']) && $checklist_result['code'] != '200') { $stream->send_error($checklist_result['msg'] ?: 'Failed to generate checklist'); $stream->close(); return; } $checklist_text = is_array($checklist_result) ? ($checklist_result['result'] ?? '') : $checklist_result; if (defined('WP_DEBUG') && WP_DEBUG && isset($checklist_result['provider'])) { } // Convert markdown to HTML $checklist_text = $convert_markdown_to_html($checklist_text); $stream->send_step_output(2, $checklist_text); $stream->send_step_complete(2, 'success'); // Step 3: Generate Author Credibility Info (same as original) $stream->send_step_start(3, 'generate_author_credibility', 'Generating author credibility information...'); $author_credibility_prompt = $get_language_instruction($lang); $author_credibility_prompt .= "Based on the checklist from step 2, create author credibility information to establish credibility for the article.\n"; $author_credibility_prompt .= "ONLY RETURN THE NECESSARY INFORMATION, DO NOT WRITE ANYTHING ELSE.\n\n"; $author_credibility_prompt .= "Checklist from step 2:\n{$checklist_text}\n\n"; $author_credibility_prompt .= "Author name: {$author_name}\n"; if (!empty($author_bio)) { $author_credibility_prompt .= "Current author description: {$author_bio}\n"; } $author_credibility_prompt .= "\nONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n"; if (defined('WP_DEBUG') && WP_DEBUG) { } $author_credibility_result = $generate_with_agent($author_credibility_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 500, 'temperature' => 0.7 )); if (is_array($author_credibility_result) && isset($author_credibility_result['code']) && $author_credibility_result['code'] != '200') { $stream->send_error($author_credibility_result['msg'] ?: 'Failed to generate author credibility info'); $stream->close(); return; } $author_credibility_text = is_array($author_credibility_result) ? ($author_credibility_result['result'] ?? '') : $author_credibility_result; // Convert markdown to HTML $author_credibility_text = $convert_markdown_to_html($author_credibility_text); $stream->send_step_output(3, $author_credibility_text); $stream->send_step_complete(3, 'success'); // Step 4: Analyze Keywords (same as original but with Google search context) $stream->send_step_start(4, 'analyze_keywords', 'Analyzing required keywords...'); $checklist_summary = mb_substr(strip_tags($checklist_text), 0, 150, 'UTF-8'); $author_credibility_summary = mb_substr(strip_tags($author_credibility_text), 0, 150, 'UTF-8'); $checklist_summary = preg_replace('/\s+/', ' ', trim($checklist_summary)); $author_credibility_summary = preg_replace('/\s+/', ' ', trim($author_credibility_summary)); $keywords_prompt = $get_language_instruction($lang); $keywords_prompt .= "Based on the following information, create a list of necessary keywords for the article.\n"; $keywords_prompt .= "ONLY RETURN KEYWORDS, DO NOT ADD ANY DESCRIPTION.\n\n"; $keywords_prompt .= "Title: {$title}\n\n"; // Add Google search results if available if (!empty($google_search_text)) { $google_search_summary = mb_substr($google_search_text, 0, 500, 'UTF-8'); $keywords_prompt .= "Latest information from Google: {$google_search_summary}\n\n"; } $keywords_prompt .= "Checklist: {$checklist_summary}\n"; $keywords_prompt .= "Author credibility information: {$author_credibility_summary}\n\n"; $keywords_prompt .= "Requirements:\n"; $keywords_prompt .= "1. 10-15 main keywords\n"; $keywords_prompt .= "2. Secondary keywords and LSI\n\n"; $keywords_prompt .= "ONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n"; if (defined('WP_DEBUG') && WP_DEBUG) { } $keywords_analysis = $generate_with_agent($keywords_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 800, 'temperature' => 0.7 )); if (is_array($keywords_analysis) && isset($keywords_analysis['code']) && $keywords_analysis['code'] != '200') { $error_msg = $keywords_analysis['msg'] ?: 'Failed to analyze keywords'; $stream->send_error($error_msg); $stream->close(); return; } $keywords_analysis_text = is_array($keywords_analysis) ? ($keywords_analysis['result'] ?? '') : $keywords_analysis; // Convert markdown to HTML $keywords_analysis_text = $convert_markdown_to_html($keywords_analysis_text); $stream->send_step_output(4, $keywords_analysis_text); $stream->send_step_complete(4, 'success'); // Step 5: Analyze Writing Direction (same as original but with Google search context) $stream->send_step_start(5, 'analyze_direction', 'Analyzing writing direction...'); $direction_prompt = $get_language_instruction($lang); $direction_prompt .= "Based on the following information, analyze and determine the writing direction for the article.\n"; $direction_prompt .= "ONLY RETURN THE ANALYSIS, DO NOT ADD ANY DESCRIPTION.\n\n"; $direction_prompt .= "Title: {$title}\n\n"; // Add Google search results if available if (!empty($google_search_text)) { $google_search_summary = mb_substr($google_search_text, 0, 800, 'UTF-8'); $direction_prompt .= "Latest information from Google: {$google_search_summary}\n\n"; } $direction_prompt .= "Checklist: {$checklist_summary}\n"; $direction_prompt .= "Keywords: " . mb_substr(strip_tags($keywords_analysis_text), 0, 200, 'UTF-8') . "\n\n"; $direction_prompt .= "ONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n"; if (defined('WP_DEBUG') && WP_DEBUG) { } $direction_analysis = $generate_with_agent($direction_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 1000, 'temperature' => 0.7 )); if (is_array($direction_analysis) && isset($direction_analysis['code']) && $direction_analysis['code'] != '200') { $error_msg = $direction_analysis['msg'] ?: 'Failed to analyze direction'; $stream->send_error($error_msg); $stream->close(); return; } $direction_analysis_text = is_array($direction_analysis) ? ($direction_analysis['result'] ?? '') : $direction_analysis; // Convert markdown to HTML $direction_analysis_text = $convert_markdown_to_html($direction_analysis_text); $stream->send_step_output(5, $direction_analysis_text); $stream->send_step_complete(5, 'success'); // Step 5.5: Find Related Posts & Internal Linking Strategy (moved before writing article) // Check if auto internal links is enabled $auto_internal_links = isset($data['autoInternalLinks']) ? filter_var($data['autoInternalLinks'], FILTER_VALIDATE_BOOLEAN) : true; // Default to true if not set $related_posts = array(); if ($auto_internal_links) { $stream->send_step_start(5.5, 'find_related_posts', 'Finding related posts for internal linking...'); // Find related posts (before writing article, so we can include them in the prompt) $related_posts = $find_related_posts_for_internal_linking($title, $keywords_analysis_text, $lang, '', 5); } $related_posts_info_for_prompt = ''; $related_posts_display = ''; if ($auto_internal_links && !empty($related_posts)) { // Prepare related posts information for prompt $related_posts_info_for_prompt = "\n\nRelated Posts for Internal Linking:\n"; foreach ($related_posts as $index => $post) { $related_posts_info_for_prompt .= ($index + 1) . ". Title: {$post['title']}\n"; $related_posts_info_for_prompt .= " URL: {$post['url']}\n"; $related_posts_info_for_prompt .= " Excerpt: {$post['excerpt']}\n"; $related_posts_info_for_prompt .= " Relevance: " . round($post['relevance_score'], 2) . "\n\n"; } $related_posts_info_for_prompt .= "IMPORTANT: Naturally insert internal links to these related posts in your article where relevant. Use markdown format: [anchor text](url). Make sure links are contextually relevant and add value to readers.\n"; // Prepare for display $related_posts_display = "

    Related Posts Found for Internal Linking:

    \n\n

    These related posts will be included in the writing prompt so AI can naturally insert internal links while writing the article.

    "; } elseif ($auto_internal_links && empty($related_posts)) { $related_posts_display = "

    No related posts found for internal linking. This might be because:

    "; } else { $related_posts_display = "

    Auto Internal Links is disabled. Internal links will not be automatically inserted.

    "; } if ($auto_internal_links) { $stream->send_step_output(5.5, $related_posts_display); $stream->send_step_complete(5.5, 'success'); } else { // Skip step 5.5 if auto internal links is disabled $stream->send_step_start(5.5, 'find_related_posts', 'Auto Internal Links is disabled...'); $stream->send_step_output(5.5, $related_posts_display); $stream->send_step_complete(5.5, 'success'); } // Step 6: Generate Multiple Prompts (one for each section from step 2) $stream->send_step_start(6, 'generate_prompt', 'Generating optimized prompts for AI...'); // Define article end marker (used in both step 6 and step 7) $article_end_marker = ""; // Get the original prompt template if available $original_prompt = ''; if (isset($data['original_prompt']) && !empty($data['original_prompt'])) { $original_prompt = mb_substr(strip_tags($data['original_prompt']), 0, 500, 'UTF-8'); } // Parse checklist to extract required sections $article_sections = array(); $checklist_json = null; // Try to extract JSON from checklist_text $checklist_plain = strip_tags($checklist_text); // Try to find JSON in the text if (preg_match('/\{[^{}]*"required_sections"[^{}]*\}/s', $checklist_plain, $json_matches)) { // Try to find full JSON structure $json_start = strpos($checklist_plain, '{'); $json_end = strrpos($checklist_plain, '}'); if ($json_start !== false && $json_end !== false && $json_end > $json_start) { $json_str = substr($checklist_plain, $json_start, $json_end - $json_start + 1); $checklist_json = json_decode($json_str, true); } } // If JSON parsing failed, try to extract sections from text if (!$checklist_json || !isset($checklist_json['content_to_provide']['required_sections'])) { // Fallback: try to extract sections from text format if (preg_match('/required_sections["\']?\s*:\s*\[(.*?)\]/s', $checklist_plain, $sections_match)) { $sections_text = $sections_match[1]; // Try to extract quoted strings preg_match_all('/["\']([^"\']+)["\']/', $sections_text, $section_matches); if (!empty($section_matches[1])) { $article_sections = $section_matches[1]; } } // If still no sections, create default sections based on direction analysis if (empty($article_sections)) { // Create default sections: Introduction, Main Content, Conclusion $article_sections = array('Introduction', 'Main Content', 'Conclusion'); } } else { // Extract sections from JSON $article_sections = $checklist_json['content_to_provide']['required_sections']; if (empty($article_sections) || !is_array($article_sections)) { $article_sections = array('Introduction', 'Main Content', 'Conclusion'); } } // Ensure we have at least one section if (empty($article_sections)) { $article_sections = array('Introduction', 'Main Content', 'Conclusion'); } // Tối ưu hóa final prompt: giới hạn độ dài các phân tích $checklist_final = mb_substr(strip_tags($checklist_text), 0, 300, 'UTF-8'); $author_credibility_final = mb_substr(strip_tags($author_credibility_text), 0, 300, 'UTF-8'); $keywords_final = mb_substr(strip_tags($keywords_analysis_text), 0, 400, 'UTF-8'); $direction_final = mb_substr(strip_tags($direction_analysis_text), 0, 500, 'UTF-8'); // Làm sạch text $checklist_final = preg_replace('/\s+/', ' ', trim($checklist_final)); $author_credibility_final = preg_replace('/\s+/', ' ', trim($author_credibility_final)); $keywords_final = preg_replace('/\s+/', ' ', trim($keywords_final)); $direction_final = preg_replace('/\s+/', ' ', trim($direction_final)); // Add language instruction to final prompt FIRST $lang_instruction_final = $get_language_instruction($lang); // Build common requirements that will be used in all section prompts $common_requirements = "Requirements:\n"; $common_requirements .= "- output with Language: {$lang}\n"; $common_requirements .= "- Format: Markdown (## for headings, ** for bold, * for italic, - for lists, [text](url) for links)\n"; $common_requirements .= "- SEO: Optimize keywords\n"; $common_requirements .= "- Quality: High, useful, professional\n"; $common_requirements .= "- Style: According to analysis\n"; $common_requirements .= "- Write for readers. The writing should be poetic.\n"; // Add extracted content from Google search - CRITICAL: AI must ONLY use this content if (!empty($urls_content) && is_array($urls_content)) { $common_requirements .= "\n=== CRITICAL WRITING INSTRUCTION ===\n\n"; $common_requirements .= "You have been provided with FULL EXTRACTED CONTENT from Google search results below.\n"; $common_requirements .= "YOUR TASK: Write the article by REWRITING, REORGANIZING, and SYNTHESIZING this extracted content ONLY.\n"; $common_requirements .= "DO NOT create new content, DO NOT add information that is not in the extracted content below.\n"; $common_requirements .= "DO NOT invent facts, statistics, or information.\n"; $common_requirements .= "You can:\n"; $common_requirements .= "- Rewrite the content in your own words\n"; $common_requirements .= "- Reorganize and restructure the information\n"; $common_requirements .= "- Combine and synthesize information from multiple sources\n"; $common_requirements .= "- Improve the flow, clarity, and readability\n"; $common_requirements .= "- Optimize for SEO while keeping the original information\n"; $common_requirements .= "You CANNOT:\n"; $common_requirements .= "- Add new facts or information not present in the extracted content\n"; $common_requirements .= "- Create new examples or case studies not mentioned in the sources\n"; $common_requirements .= "- Invent statistics, numbers, or data not found in the sources\n\n"; $common_requirements .= "=== EXTRACTED CONTENT FROM SOURCES ===\n\n"; // Add full extracted content (limit each to reasonable size but include key information) foreach ($urls_content as $idx => $content_item) { $content_preview = $content_item['content']; // Limit each source to 3000 chars to avoid token limits, but include as much as possible if (strlen($content_preview) > 3000) { $content_preview = mb_substr($content_preview, 0, 3000, 'UTF-8') . "\n... (content truncated, use the available portion)"; } $common_requirements .= "--- SOURCE " . ($idx + 1) . " ---\n"; $common_requirements .= "URL: " . $content_item['url'] . "\n"; $common_requirements .= "Title: " . $content_item['title'] . "\n"; $common_requirements .= "Content:\n" . $content_preview . "\n\n"; $common_requirements .= "=== END OF SOURCE " . ($idx + 1) . " ===\n\n\n"; } $common_requirements .= "Remember: Use ONLY the information from the sources above. Rewrite and reorganize it, but do not add new information.\n\n"; } else { // This should never happen due to validation, but add safety check $common_requirements .= "\nERROR: No extracted content available. Article cannot be written without crawled content.\n"; $common_requirements .= "The article writing process requires extracted content from Google search URLs.\n\n"; } // Add article settings if provided if (!empty($target_audience)) { $common_requirements .= "\nTarget Audience: {$target_audience}\n"; $common_requirements .= "IMPORTANT: Write this article specifically for {$target_audience}. Tailor the content, examples, and language to resonate with this audience.\n"; } if (!empty($tone)) { $tone_descriptions = array( 'professional' => 'professional, authoritative, and business-like', 'friendly' => 'friendly, warm, and approachable', 'humorous' => 'humorous, light-hearted, and entertaining', 'formal' => 'formal, respectful, and traditional', 'casual' => 'casual, relaxed, and conversational', 'authoritative' => 'authoritative, expert, and confident', 'conversational' => 'conversational, engaging, and personable' ); $tone_desc = isset($tone_descriptions[$tone]) ? $tone_descriptions[$tone] : $tone; $common_requirements .= "\nTone: Write in a {$tone_desc} tone throughout the article.\n"; } if (!empty($length_type)) { $length_instructions = array( 'short-form' => 'Keep the article concise and to the point (500-800 words). Focus on key information without extensive detail.', 'long-form' => 'Write a comprehensive, detailed article (2000+ words). Include in-depth explanations, examples, and thorough coverage of the topic.', 'comparison' => 'Structure the article as a comparison. Compare different options, approaches, or solutions with clear pros and cons.' ); if (isset($length_instructions[$length_type])) { $common_requirements .= "\nLength Type: {$length_instructions[$length_type]}\n"; } } if (!empty($competitors)) { $common_requirements .= "\nCompetitor Analysis:\n"; $common_requirements .= "The following are top competitor articles on similar topics:\n"; foreach ($competitors as $index => $competitor_url) { $common_requirements .= ($index + 1) . ". {$competitor_url}\n"; } $common_requirements .= "IMPORTANT: Analyze these competitor articles and create content that is:\n"; $common_requirements .= "- More comprehensive and valuable\n"; $common_requirements .= "- Better structured and easier to read\n"; $common_requirements .= "- More up-to-date and accurate\n"; $common_requirements .= "- Unique in perspective and approach\n"; } if (!empty($brand_voice_rules)) { $common_requirements .= "\nBrand Voice Rules:\n"; $common_requirements .= "Follow these brand voice guidelines when writing:\n"; $common_requirements .= $brand_voice_rules . "\n"; $common_requirements .= "IMPORTANT: Strictly adhere to these brand voice rules throughout the entire article.\n"; } // Add internal linking requirements if related posts found if ($auto_internal_links && !empty($related_posts)) { $common_requirements .= $related_posts_info_for_prompt; $common_requirements .= "- Insert 3-5 internal links directly and naturally within the paragraphs of the article, using appropriate keywords in context. Do NOT place links on separate lines; links must be inside the main text, not as standalone items.\n"; $common_requirements .= "- Each related post/link should appear only ONCE in the entire article. Do NOT insert the same link multiple times.\n"; $common_requirements .= "- Use natural anchor text (not exact post titles) that fits the context and the keywords.\n"; $common_requirements .= "- Don't over-link: maximum 1 link per 200 words.\n"; $common_requirements .= "- Links should be contextually relevant to the surrounding paragraph and enhance the reader's experience.\n\n"; } // Generate prompts for each section $section_prompts = array(); $total_sections = count($article_sections); for ($i = 0; $i < $total_sections; $i++) { $section_name = $article_sections[$i]; $is_first_section = ($i === 0); $is_last_section = ($i === $total_sections - 1); $section_prompt = $lang_instruction_final; if ($is_first_section) { $section_prompt .= "Write the first section of the article:\n\n"; } else { $section_prompt .= "Continue writing the next section of the article:\n\n"; } $section_prompt .= "Title: {$title}\n\n"; $section_prompt .= "Analysis:\n"; $section_prompt .= "1. Checklist: {$checklist_final}\n"; $section_prompt .= "2. Keywords: {$keywords_final}\n"; $section_prompt .= "3. Content direction: {$direction_final}\n\n"; $section_prompt .= "Current Section to Write: {$section_name}\n"; $section_prompt .= "Section Number: " . ($i + 1) . " of {$total_sections}\n\n"; $section_prompt .= $common_requirements; if ($is_first_section) { $section_prompt .= "\n- IMPORTANT: Write the article directly, DO NOT introduce your AI role, DO NOT say \"Excellent!\", \"As a...\", \"I believe I can...\" or any introductory phrases. Start writing the article immediately.\n"; $section_prompt .= "- Write the introduction section of the article. This should be engaging and hook the reader.\n"; } else { $section_prompt .= "\n- IMPORTANT: Continue writing seamlessly from the previous section.\n"; $section_prompt .= "- You will receive the last part of the previous section to continue from.\n"; $section_prompt .= "- Write the section: {$section_name}\n"; $section_prompt .= "- Make sure the transition is smooth and natural.\n"; } if ($is_last_section) { $section_prompt .= "\n- CRITICAL: When you finish writing this final section, you MUST add this exact marker at the very end: {$article_end_marker}\n"; $section_prompt .= "- This marker indicates that the article is complete. Do NOT add any content after this marker.\n"; $section_prompt .= "- Make sure to write a proper conclusion that wraps up the article.\n"; } if (!empty($original_prompt) && $is_first_section) { $section_prompt .= "\nAdditional: {$original_prompt}\n"; } if ($is_first_section) { $section_prompt .= "\nWrite the first section of the article now."; } else { $section_prompt .= "\nYou will receive the previous section's ending to continue from. Write the next section."; } $section_prompts[] = array( 'section_name' => $section_name, 'section_index' => $i, 'prompt' => $section_prompt, 'is_first' => $is_first_section, 'is_last' => $is_last_section ); } // Display all prompts $prompts_display = "Generated " . count($section_prompts) . " prompts for article sections:\n\n"; foreach ($section_prompts as $idx => $sp) { $prompts_display .= "Section " . ($idx + 1) . ": {$sp['section_name']}\n"; } $prompts_display .= "\n" . str_repeat("=", 50) . "\n\n"; $prompts_display .= "First section prompt preview:\n\n"; $prompts_display .= mb_substr($section_prompts[0]['prompt'], 0, 1000, 'UTF-8') . "..."; $stream->send_step_output(6, $prompts_display); $stream->send_step_complete(6, 'success'); // Step 7: Write Article $stream->send_step_start(7, 'write_article', 'Writing article...'); $stream->send_status('Generating article content with AI...'); if (defined('WP_DEBUG') && WP_DEBUG) { } // Build system prompt for article writing // Prepare author information for system prompt $author_info_for_system = ''; if (!empty($author_credibility_text)) { $author_credibility_plain = strip_tags($author_credibility_text); $author_credibility_plain = preg_replace('/\s+/', ' ', trim($author_credibility_plain)); // Limit to reasonable length for system prompt $author_info_for_system = mb_substr($author_credibility_plain, 0, 500, 'UTF-8'); } $system_prompt = "You are an expert content writer and SEO specialist with years of experience creating high-quality, engaging articles.\n\n"; // Add author role information to system prompt if (!empty($author_info_for_system)) { $system_prompt .= "Author Role and Credibility:\n"; $system_prompt .= "You are writing as the article author with the following background and credibility:\n"; $system_prompt .= $author_info_for_system . "\n\n"; $system_prompt .= "IMPORTANT: Embody this author persona when writing. Write from this author's perspective, using their expertise, experience, and voice. "; $system_prompt .= "However, DO NOT explicitly mention or introduce this author information in the article content itself. "; $system_prompt .= "Instead, let your writing naturally reflect this author's expertise and perspective through the quality, depth, and style of the content.\n\n"; } $system_prompt .= "Your role:\n"; $system_prompt .= "- Write comprehensive, well-structured articles that provide real value to readers\n"; $system_prompt .= "- Optimize content for SEO while maintaining natural, readable flow\n"; $system_prompt .= "- Use proper markdown formatting (## for headings, ** for bold, * for italic, - for lists, [text](url) for links)\n"; $system_prompt .= "- Create content that is original, informative, and engaging\n\n"; $system_prompt .= "Writing guidelines:\n"; $system_prompt .= "- Write directly as the article author - DO NOT introduce yourself as AI\n"; $system_prompt .= "- DO NOT use phrases like \"Excellent!\", \"As a...\", \"I believe I can...\", or any introductory phrases\n"; $system_prompt .= "- Start writing the article content immediately\n"; $system_prompt .= "- Integrate information naturally and organically, not mechanically\n"; $system_prompt .= "- Write for readers first, ensuring the content is valuable and easy to understand\n"; $system_prompt .= "- Use a poetic, engaging writing style when appropriate\n"; $system_prompt .= "- Maintain consistency in tone and style throughout the article\n\n"; $system_prompt .= "Quality standards:\n"; $system_prompt .= "- High-quality, professional content\n"; $system_prompt .= "- Accurate, up-to-date information\n"; $system_prompt .= "- Well-structured with clear headings and subheadings\n"; $system_prompt .= "- Natural keyword integration (1-2% keyword density)\n"; $system_prompt .= "- Engaging introduction and strong conclusion with CTA when appropriate\n\n"; $system_prompt .= "Article completion marker:\n"; $system_prompt .= "- When you finish writing the complete article, you MUST add this exact marker at the very end: \n"; $system_prompt .= "- This marker indicates that the article is complete. Do NOT add any content after this marker.\n"; $system_prompt .= "- Only add this marker when the article is truly finished with a proper conclusion.\n"; // Add language requirement to system prompt $lang_instruction = $get_language_instruction($lang); if (!empty($lang_instruction)) { $system_prompt .= "\n" . $lang_instruction; } // Helper function to extract article content up to the end marker $extract_article_content = function($text) use (&$article_end_marker) { if (empty($text)) { return $text; } // Check if marker exists in the text $marker_pos = strpos($text, $article_end_marker); if ($marker_pos !== false) { // Extract content before the marker $extracted = substr($text, 0, $marker_pos); // Remove any trailing whitespace $extracted = rtrim($extracted); if (defined('WP_DEBUG') && WP_DEBUG) { } return $extracted; } // Marker not found, return original text return $text; }; // Write article section by section $article_text = ''; $previous_section_ending = ''; // Check if section_prompts exists (from step 6) if (!isset($section_prompts) || empty($section_prompts)) { // Fallback: if section_prompts not available, use old method if (defined('WP_DEBUG') && WP_DEBUG) { } // Create a basic prompt if section_prompts not available $fallback_prompt = $lang_instruction_final . "Write a complete article about: {$title}\n\n"; $fallback_prompt .= "Requirements:\n"; $fallback_prompt .= "- Language: {$lang}\n"; $fallback_prompt .= "- Format: Markdown\n"; $fallback_prompt .= "- Write directly, DO NOT introduce yourself.\n"; // Add Google search results if available if (!empty($google_search_text)) { $fallback_prompt .= "\nIMPORTANT: Use the following latest information from Google search:\n\n"; $fallback_prompt .= $google_search_text . "\n\n"; } $article_content = $generate_with_agent($fallback_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 4000, 'temperature' => 0.8, 'use_case' => 'long_context', 'system' => $system_prompt )); if (is_array($article_content) && isset($article_content['code']) && $article_content['code'] != '200') { $stream->send_error($article_content['msg'] ?: 'Failed to generate article'); $stream->close(); return; } $article_text = is_array($article_content) ? ($article_content['result'] ?? '') : $article_content; $article_text = $extract_article_content($article_text); } else { // Write section by section using section_prompts $total_sections = count($section_prompts); for ($section_idx = 0; $section_idx < $total_sections; $section_idx++) { $section_data = $section_prompts[$section_idx]; $section_name = $section_data['section_name']; $section_prompt = $section_data['prompt']; $is_first = $section_data['is_first']; $is_last = $section_data['is_last']; if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_status('Writing section ' . ($section_idx + 1) . ' of ' . $total_sections . ': ' . $section_name . '...'); // If not first section, add previous section ending to prompt if (!$is_first && !empty($previous_section_ending)) { // Get last 1500 characters of previous section for context $context_ending = mb_substr($previous_section_ending, -1500); // Modify prompt to include previous section ending $section_prompt .= "\n\n---\n"; $section_prompt .= "Here is the ending of the previous section to continue from:\n\n"; $section_prompt .= $context_ending . "\n\n"; $section_prompt .= "---\n\n"; $section_prompt .= "IMPORTANT: Continue writing seamlessly from the last sentence above. "; $section_prompt .= "Do NOT repeat what was already written. Maintain the same writing style and tone.\n"; } // Generate section content $section_content = $generate_with_agent($section_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 4000, 'temperature' => 0.8, 'use_case' => 'long_context', 'system' => $system_prompt )); if (is_array($section_content) && isset($section_content['code']) && $section_content['code'] != '200') { $error_msg = $section_content['msg'] ?: 'Failed to generate section: ' . $section_name; if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_error($error_msg); // Continue with next section or break if ($is_last) { break; } continue; } $section_text = is_array($section_content) ? ($section_content['result'] ?? '') : $section_content; if (defined('WP_DEBUG') && WP_DEBUG && isset($section_content['provider'])) { } // Extract content up to the end marker (if marker exists in last section) if ($is_last) { $section_text = $extract_article_content($section_text); } // Check if this section has a main heading (h2/h3) in markdown and search for image BEFORE adding to article_text if (!empty($section_text)) { $section_has_main_heading = false; $main_heading_title = ''; $main_heading_markdown_pos = -1; // Check for h2 heading in markdown (## heading) if (preg_match('/^##\s+(.+)$/m', $section_text, $h2_match, PREG_OFFSET_CAPTURE)) { $section_has_main_heading = true; $main_heading_title = trim($h2_match[1][0]); $main_heading_markdown_pos = $h2_match[0][1] + strlen($h2_match[0][0]); } elseif (preg_match('/^###\s+(.+)$/m', $section_text, $h3_match, PREG_OFFSET_CAPTURE)) { // Fallback to h3 if no h2 $section_has_main_heading = true; $main_heading_title = trim($h3_match[1][0]); $main_heading_markdown_pos = $h3_match[0][1] + strlen($h3_match[0][0]); } // If section has main heading, search and insert image into markdown if ($section_has_main_heading && !empty($main_heading_title) && strlen($main_heading_title) > 3) { $stream->send_status('Đang tìm hình ảnh cho section: ' . $main_heading_title . '...'); // Get section content for better search query $section_content_plain = strip_tags($section_text); $section_content_plain = mb_substr($section_content_plain, 0, 500, 'UTF-8'); // Generate search query using AI $image_search_query = $main_heading_title; if (!empty($section_content_plain) && strlen($section_content_plain) > 20) { $query_prompt = $get_language_instruction($lang); $query_prompt .= "Tạo một từ khóa tìm kiếm hình ảnh ngắn gọn (3-5 từ) phù hợp với section sau:\n\n"; $query_prompt .= "Tiêu đề section: {$main_heading_title}\n"; $query_prompt .= "Nội dung section: " . mb_substr($section_content_plain, 0, 300, 'UTF-8') . "\n\n"; $query_prompt .= "Yêu cầu:\n"; $query_prompt .= "- Chỉ trả về từ khóa tìm kiếm, không có giải thích\n"; $query_prompt .= "- Từ khóa phải phù hợp để tìm hình ảnh minh họa\n"; $query_prompt .= "- Tối đa 5 từ\n\n"; $query_prompt .= "Chỉ trả về từ khóa tìm kiếm:"; $query_result = $generate_with_agent($query_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 50, 'temperature' => 0.7, 'use_case' => 'fast' )); if (is_array($query_result) && isset($query_result['code']) && $query_result['code'] == '200') { $generated_query = is_array($query_result) ? trim($query_result['result'] ?? '') : trim($query_result); $generated_query = strip_tags($generated_query); $generated_query = preg_replace('/["\']/', '', $generated_query); if (!empty($generated_query) && strlen($generated_query) > 3) { $image_search_query = $generated_query; } } } // Search for image try { $image_results = $bardGenContent->searchimg($image_search_query); // Handle both cases: direct array or object with 'result' key $image_array = null; if (is_array($image_results) && !empty($image_results)) { // Direct array case (sendPostRequest returns $decoded->result) $image_array = $image_results; } elseif (is_object($image_results) && isset($image_results->result) && is_array($image_results->result) && !empty($image_results->result)) { // Object with 'result' key case $image_array = $image_results->result; } elseif (isset($image_results['result']) && is_array($image_results['result']) && !empty($image_results['result'])) { // Array with 'result' key case $image_array = $image_results['result']; } if ($image_array && !empty($image_array)) { $selected_image = $image_array[0]; // Create image markdown format $image_markdown = "\n\n![{$main_heading_title}]({$selected_image})\n\n"; // Insert image after heading in section_text (markdown) $section_text = substr_replace($section_text, $image_markdown, $main_heading_markdown_pos, 0); $stream->send_status('✓ Đã tìm và chèn hình ảnh cho section: ' . $main_heading_title); // Stream section content immediately after inserting image (especially for section 1) if ($is_first || $section_idx === 0) { $section_html = $convert_markdown_to_html($section_text); if (!empty($section_html)) { $section_header = '
    '; $section_header .= '
    Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '
    '; $section_footer = '
    '; $stream->send_step_output(7, $section_header . $section_html . $section_footer); } } if (defined('WP_DEBUG') && WP_DEBUG) { } } else { // Fallback: try with section title only if ($image_search_query !== $main_heading_title) { $image_results = $bardGenContent->searchimg($main_heading_title); if ($image_results && isset($image_results['result']) && is_array($image_results['result']) && !empty($image_results['result'])) { $selected_image = $image_results['result'][0]; $image_markdown = "\n\n![{$main_heading_title}]({$selected_image})\n\n"; $section_text = substr_replace($section_text, $image_markdown, $main_heading_markdown_pos, 0); $stream->send_status('✓ Đã tìm và chèn hình ảnh cho section: ' . $main_heading_title); // Stream section content immediately after inserting image (especially for section 1) if ($is_first || $section_idx === 0) { $section_html = $convert_markdown_to_html($section_text); if (!empty($section_html)) { $section_header = '
    '; $section_header .= '
    Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '
    '; $section_footer = '
    '; $stream->send_step_output(7, $section_header . $section_html . $section_footer); } } } } } } catch (Exception $img_ex) { if (defined('WP_DEBUG') && WP_DEBUG) { } } // Small delay usleep(300000); // 0.3 second delay } // If not first section, add a newline for separation if (!empty($article_text)) { $article_text .= "\n\n"; } // Append section_text (which now includes image if found) to article_text $article_text .= $section_text; // Store the ending of this section for next iteration // Take last 2000 characters for context $previous_section_ending = mb_substr($section_text, -2000); // Convert section to HTML and display the entire section at once $section_html = $convert_markdown_to_html($section_text); if (!empty($section_html)) { // Add section header for clarity $section_header = '
    '; $section_header .= '
    Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '
    '; $section_footer = '
    '; // Send the complete section at once (with image if found) $stream->send_step_output(7, $section_header . $section_html . $section_footer); } } // If this is the last section and we have the end marker, we're done if ($is_last && strpos($section_text, $article_end_marker) !== false) { if (defined('WP_DEBUG') && WP_DEBUG) { } break; } } } // Convert final article to HTML (for final output) $article_text = $convert_markdown_to_html($article_text); $stream->send_step_complete(7, 'success', array('content' => $article_text)); // Update AI_post_usage counter $this->aiautotool_update_ai_post_usage(); // Send completion $stream->send_complete($article_text, array( 'google_search_results' => $google_search_results, 'checklist' => $checklist_text, 'author_credibility' => $author_credibility_text, 'keywords_analysis' => $keywords_analysis_text, 'direction_analysis' => $direction_analysis_text, 'final_prompt' => $final_prompt, 'article' => $article_text, 'related_posts' => $related_posts ), $message_id); } catch (Exception $e) { $error_msg = 'Error: ' . $e->getMessage(); if (defined('WP_DEBUG') && WP_DEBUG) { } if (!$stream) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); } $stream->send_error($error_msg, array( 'exception' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ), $message_id); } catch (Error $e) { $error_msg = 'Fatal Error: ' . $e->getMessage(); if (defined('WP_DEBUG') && WP_DEBUG) { } if (!isset($stream) || !$stream) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); } $stream->send_error($error_msg, array( 'exception' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ), $message_id); } if (isset($stream) && $stream) { $stream->close(); } else { exit; } } public function aiautotool_write_article_with_analysis_callback() { // Verify nonce for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) { // For SSE, we need to send error via stream require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Security check failed. Please refresh the page and try again.'); $stream->close(); return; } if (!current_user_can('edit_posts')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Permission denied'); $stream->close(); return; } } // Check if user has active Pro license or trial access. if (!function_exists('aiautotool_can_use_pro_features') || !aiautotool_can_use_pro_features()) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('This feature requires a Pro account. Please upgrade to Pro to use this feature.'); $stream->close(); return; } // Load rendersetting class if not already loaded if (!class_exists('rendersetting')) { $rendersetting_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/setting.php'; if (file_exists($rendersetting_file)) { require_once $rendersetting_file; } } // Get data from POST $data = array(); if (isset($_POST['data']) && is_string($_POST['data'])) { $data = json_decode(stripslashes($_POST['data']), true); } else { $raw_data = file_get_contents('php://input'); $data = json_decode($raw_data, true); } if (!$data || !is_array($data)) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Invalid JSON data'); $stream->close(); return; } // Extract parameters $title = isset($data['title']) ? sanitize_text_field($data['title']) : ''; $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'Vietnamese'; $resolved_ai_selection = $this->aiautotool_resolve_provider_model_selection( isset($data['model']) ? $data['model'] : '', isset($data['provider_id']) ? $data['provider_id'] : '' ); $model = $resolved_ai_selection['model']; $provider_id = $resolved_ai_selection['provider_id']; $message_id = isset($data['message_id']) ? sanitize_text_field($data['message_id']) : ''; // Extract article settings $target_audience = isset($data['targetAudience']) ? sanitize_text_field($data['targetAudience']) : ''; $tone = isset($data['tone']) ? sanitize_text_field($data['tone']) : ''; $length_type = isset($data['lengthType']) ? sanitize_text_field($data['lengthType']) : ''; $competitors = isset($data['competitors']) && is_array($data['competitors']) ? array_map('esc_url_raw', array_filter($data['competitors'])) : array(); $brand_voice_rules = isset($data['brandVoiceRules']) ? sanitize_textarea_field($data['brandVoiceRules']) : ''; if (empty($title)) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Title parameter is required'); $stream->close(); return; } // Load SSE Stream class require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php'; // Load AI Helper and AI Agent for new AI Provider system if (file_exists(plugin_dir_path(__FILE__) . 'inc/ai-providers/aiautotool_ai_helper.php')) { require_once plugin_dir_path(__FILE__) . 'inc/ai-providers/aiautotool_ai_helper.php'; } // Initialize BardGenContent for fallback $bardGenContent = new BardGenContent(); // Helper function to convert markdown to HTML $convert_markdown_to_html = function($text) { if (empty($text)) { return ''; } // Check if content is already HTML (has HTML tags) $has_html = preg_match('/<[a-z][\s\S]*>/i', $text); if ($has_html) { if (defined('WP_DEBUG') && WP_DEBUG) { } return $text; // Already HTML, return as is } // Try Parsedown first $parsedown_loaded = false; if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/Parsedown.php')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/Parsedown.php'; $parsedown_loaded = class_exists('Parsedown'); } if ($parsedown_loaded) { $parsedown = new Parsedown(); $html = $parsedown->text($text); if (defined('WP_DEBUG') && WP_DEBUG) { } return $html; } // Try markdown parser function if (file_exists(plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/markdown-parser.php')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/markdown-parser.php'; if (function_exists('markdown')) { $html = markdown($text); if (defined('WP_DEBUG') && WP_DEBUG) { } return $html; } } // Fallback to simple inline parser (inline implementation) // Convert headers (h1-h6) $html = preg_replace('/^######\s+(.+)$/m', '
    $1
    ', $text); $html = preg_replace('/^#####\s+(.+)$/m', '
    $1
    ', $html); $html = preg_replace('/^####\s+(.+)$/m', '

    $1

    ', $html); $html = preg_replace('/^###\s+(.+)$/m', '

    $1

    ', $html); $html = preg_replace('/^##\s+(.+)$/m', '

    $1

    ', $html); $html = preg_replace('/^#\s+(.+)$/m', '

    $1

    ', $html); // Convert code blocks (```code```) $html = preg_replace_callback('/```([\s\S]*?)```/m', function($matches) { return '
    ' . esc_html(trim($matches[1])) . '
    '; }, $html); // Convert inline code (`code`) $html = preg_replace('/`([^`]+)`/', '$1', $html); // Convert bold (**text** or __text__) $html = preg_replace('/\*\*(.+?)\*\*/', '$1', $html); $html = preg_replace('/__(.+?)__/', '$1', $html); // Convert italic (*text* or _text_) $html = preg_replace('/(?$1', $html); $html = preg_replace('/(?$1', $html); // Convert links [text](url) $html = preg_replace('/\[([^\]]+)\]\(([^)]+)\)/', '$1', $html); // Convert images ![alt](url) $html = preg_replace('/!\[([^\]]*)\]\(([^)]+)\)/', '$1', $html); // Convert blockquotes (> text) $html = preg_replace('/^>\s+(.+)$/m', '
    $1
    ', $html); // Convert unordered lists (- item or * item) $html = preg_replace('/^[\-\*]\s+(.+)$/m', '
  • $1
  • ', $html); $html = preg_replace('/(
  • .*<\/li>\n?)+/s', '', $html); // Convert ordered lists (1. item) $html = preg_replace('/^\d+\.\s+(.+)$/m', '
  • $1
  • ', $html); // Convert line breaks (double newline = paragraph break) $html = preg_replace('/\n\n+/', '

    ', $html); $html = '

    ' . $html . '

    '; // Clean up empty paragraphs $html = preg_replace('/

    \s*<\/p>/', '', $html); $html = preg_replace('/

    (<[^>]+>)/', '$1

    ', $html); $html = preg_replace('/(<\/[^>]+>)<\/p>/', '$1', $html); if (defined('WP_DEBUG') && WP_DEBUG) { } return $html; }; // Track last AI call time to ensure minimum 10 seconds between calls $last_ai_call_time = 0; $min_ai_call_interval = 10; // Minimum seconds between AI calls // Helper function to generate content using AI Agent with fallback $generate_with_agent = function($prompt, $lang, $model, $provider_id = '', $options = array()) use ($bardGenContent, &$last_ai_call_time, $min_ai_call_interval) { // Ensure minimum 10 seconds between AI calls $current_time = time(); $time_since_last_call = $current_time - $last_ai_call_time; if ($last_ai_call_time > 0 && $time_since_last_call < $min_ai_call_interval) { $wait_time = $min_ai_call_interval - $time_since_last_call; if (defined('WP_DEBUG') && WP_DEBUG) { } sleep($wait_time); } // Update last call time before making the call $last_ai_call_time = time(); // Try AI Agent first if available if (class_exists('AIAutotool_AI_Agent')) { $agent = AIAutotool_AI_Agent::get_instance(); // Determine use case based on prompt content $use_case = 'general'; $prompt_lower = strtolower($prompt); if (stripos($prompt_lower, 'checklist') !== false || stripos($prompt_lower, 'danh sách') !== false) { $use_case = 'fast'; // Checklist is a simple task } elseif (stripos($prompt_lower, 'phân tích') !== false || stripos($prompt_lower, 'analyze') !== false) { $use_case = 'reasoning'; // Analysis requires reasoning } elseif (strlen($prompt) > 2000) { $use_case = 'long_context'; // Long prompts need long context models } // Merge options - allow use_case override from options if (isset($options['use_case'])) { $use_case = $options['use_case']; } $agent_options = array_merge(array( 'use_case' => $use_case, 'temperature' => 0.7, 'max_tokens' => isset($options['max_tokens']) ? $options['max_tokens'] : 2000 ), $options); // If provider_id is specified, try that first if (!empty($provider_id)) { $agent_options['provider'] = $provider_id; if (!empty($model)) { $agent_options['model'] = $model; } } $result = $agent->generate($prompt, $agent_options); if ($result['success'] && !empty($result['content'])) { if (defined('WP_DEBUG') && WP_DEBUG) { } return array( 'code' => '200', 'result' => $result['content'], 'provider' => $result['provider'], 'model' => $result['model'] ); } else { if (defined('WP_DEBUG') && WP_DEBUG) { } } } // Fallback to old method (bardcontentmore) if (defined('WP_DEBUG') && WP_DEBUG) { } return $bardGenContent->bardcontentmore($prompt, $lang, $model); }; // Helper function to generate language instruction $get_language_instruction = function($lang) { $lang_lower = strtolower(trim($lang)); $lang_instruction = ''; // Check for Vietnamese (more specific patterns first) if (strpos($lang_lower, 'vietnamese') !== false || strpos($lang_lower, 'tiếng việt') !== false || $lang_lower === 'vi' || $lang_lower === 'vie') { $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n"; $lang_instruction .= "You MUST respond ONLY in Vietnamese (Tiếng Việt).\n"; $lang_instruction .= "ALL your output MUST be in Vietnamese language only.\n"; $lang_instruction .= "DO NOT use English or any other language.\n"; $lang_instruction .= "Response language: Vietnamese (Tiếng Việt) ONLY.\n\n"; } // Check for English elseif (strpos($lang_lower, 'english') !== false || $lang_lower === 'en' || $lang_lower === 'eng') { $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n"; $lang_instruction .= "You MUST respond ONLY in English.\n"; $lang_instruction .= "ALL your output MUST be in English language only.\n"; $lang_instruction .= "DO NOT use Vietnamese or any other language.\n"; $lang_instruction .= "Response language: English ONLY.\n\n"; } // For other languages else { $lang_instruction = "🚨 CRITICAL LANGUAGE REQUIREMENT 🚨\n"; $lang_instruction .= "You MUST respond ONLY in {$lang} language.\n"; $lang_instruction .= "ALL your output MUST be in {$lang} language only.\n"; $lang_instruction .= "DO NOT use any other language.\n"; $lang_instruction .= "Response language: {$lang} ONLY.\n\n"; } return $lang_instruction; }; // Helper function to find related posts for internal linking $find_related_posts_for_internal_linking = function($title, $keywords_text, $lang, $article_text = '', $limit = 5) { $related_posts = array(); // Extract main keywords from keywords analysis $keywords_summary = mb_substr(strip_tags($keywords_text), 0, 200, 'UTF-8'); $keywords_summary = preg_replace('/\s+/', ' ', trim($keywords_summary)); // Extract keywords array (first 3-5 keywords) $keywords_array = array(); $lines = explode("\n", $keywords_text); foreach ($lines as $line) { $line = trim(strip_tags($line)); if (!empty($line) && strlen($line) > 3) { // Remove numbering and bullets $line = preg_replace('/^[\d\-\*\.\s]+/', '', $line); if (!empty($line)) { $keywords_array[] = $line; if (count($keywords_array) >= 5) break; } } } // If no keywords extracted, use title words if (empty($keywords_array)) { $title_words = explode(' ', $title); $keywords_array = array_slice($title_words, 0, 3); } // Build search query from keywords $search_query = implode(' ', array_slice($keywords_array, 0, 3)); // Find posts by keywords (search) $args_by_keywords = array( 'post_type' => 'post', 'posts_per_page' => $limit * 2, // Get more to filter later 'post_status' => 'publish', 's' => $search_query, 'orderby' => 'relevance', 'order' => 'DESC', ); // Add language filter if Polylang is active if (function_exists('pll_get_post_language')) { $args_by_keywords['lang'] = $lang; } $query_by_keywords = new WP_Query($args_by_keywords); if ($query_by_keywords->have_posts()) { while ($query_by_keywords->have_posts()) { $query_by_keywords->the_post(); $post_id = get_the_ID(); $post_title = get_the_title(); $post_url = get_permalink(); $post_excerpt = get_the_excerpt(); // Calculate relevance score (simple: based on keyword matches) $relevance_score = 0; $title_lower = mb_strtolower($title, 'UTF-8'); $post_title_lower = mb_strtolower($post_title, 'UTF-8'); foreach ($keywords_array as $keyword) { $keyword_lower = mb_strtolower($keyword, 'UTF-8'); if (mb_strpos($post_title_lower, $keyword_lower) !== false) { $relevance_score += 3; } if (mb_strpos($post_excerpt, $keyword_lower) !== false) { $relevance_score += 1; } } // Check title similarity similar_text($title_lower, $post_title_lower, $similarity); $relevance_score += $similarity / 10; $related_posts[] = array( 'id' => $post_id, 'title' => $post_title, 'url' => $post_url, 'excerpt' => mb_substr($post_excerpt, 0, 150, 'UTF-8'), 'relevance_score' => $relevance_score ); } wp_reset_postdata(); } // Also find by tags if available (tags are more flexible than categories) // Try to find posts with similar tags based on keywords if (!empty($keywords_array)) { $tag_names = array_slice($keywords_array, 0, 3); // Use first 3 keywords as potential tags $args_by_tags = array( 'post_type' => 'post', 'posts_per_page' => $limit, 'post_status' => 'publish', 'tag_slug__in' => array_map(function($tag) { return sanitize_title($tag); }, $tag_names), 'orderby' => 'date', 'order' => 'DESC', ); if (function_exists('pll_get_post_language')) { $args_by_tags['lang'] = $lang; } $query_by_tags = new WP_Query($args_by_tags); if ($query_by_tags->have_posts()) { while ($query_by_tags->have_posts()) { $query_by_tags->the_post(); $post_id = get_the_ID(); $post_title = get_the_title(); $post_url = get_permalink(); $post_excerpt = get_the_excerpt(); // Check if already in related_posts $exists = false; foreach ($related_posts as $existing) { if ($existing['id'] == $post_id) { $exists = true; break; } } if (!$exists) { $relevance_score = 2; // Lower score for tag matches $related_posts[] = array( 'id' => $post_id, 'title' => $post_title, 'url' => $post_url, 'excerpt' => mb_substr($post_excerpt, 0, 150, 'UTF-8'), 'relevance_score' => $relevance_score ); } } wp_reset_postdata(); } } // Sort by relevance score and limit usort($related_posts, function($a, $b) { return $b['relevance_score'] <=> $a['relevance_score']; }); return array_slice($related_posts, 0, $limit); }; // Debug logging if (defined('WP_DEBUG') && WP_DEBUG) { } $stream = new AIAutoTool_SSE_Stream(); $stream->start(); if (!empty($message_id)) { $stream->set_message_id($message_id); } try { // Step 1: Generate Checklist $stream->send_step_start(1, 'generate_checklist', 'Generating checklist...'); // Get website information $site_name = get_bloginfo('name'); $site_url = home_url(); // Get author information $current_user = wp_get_current_user(); $author_name = $current_user->display_name; $author_bio = get_user_meta($current_user->ID, 'description', true); $checklist_prompt = $get_language_instruction($lang); $checklist_prompt .= "You are an SEO Content Author with deep understanding of user intent and search behavior.\n\n"; $checklist_prompt .= "Your task: Analyze the topic based on the provided **title**.\n\n"; $checklist_prompt .= "Input:\n\n"; $checklist_prompt .= "- title: \"{$title}\"\n\n"; $checklist_prompt .= "Output:\n\n"; $checklist_prompt .= "Provide a structured analysis including:\n\n"; $checklist_prompt .= "1. **User Intent Analysis**\n\n"; $checklist_prompt .= " - Người tìm kiếm với tiêu đề này đang muốn điều gì?\n\n"; $checklist_prompt .= " - Họ gặp vấn đề, nỗi đau, thắc mắc gì?\n\n"; $checklist_prompt .= " - Mục đích của họ là: tìm hiểu, so sánh, mua hàng, hay giải pháp?\n\n"; $checklist_prompt .= "2. **Search Intent Classification**\n\n"; $checklist_prompt .= " - Phân loại theo 3 nhóm:\n\n"; $checklist_prompt .= " - Informational (tìm hiểu)\n\n"; $checklist_prompt .= " - Commercial Investigation (cân nhắc)\n\n"; $checklist_prompt .= " - Transactional (muốn mua)\n\n"; $checklist_prompt .= " - Giải thích lý do chọn loại này.\n\n"; $checklist_prompt .= "3. **What Users Expect From This Article**\n\n"; $checklist_prompt .= " - Danh sách 5–10 thông tin, câu trả lời hoặc nội dung mà người dùng mong đợi.\n\n"; $checklist_prompt .= " - Điều gì khiến họ hài lòng sau khi đọc?\n\n"; $checklist_prompt .= "4. **What We Should Provide**\n\n"; $checklist_prompt .= " - Những mục nội dung cần có trong bài viết để thoả mãn user intent.\n\n"; $checklist_prompt .= " - Insight đặc biệt mà đối thủ thường thiếu.\n\n"; $checklist_prompt .= " - Nội dung cần ưu tiên + về lý do.\n\n"; $checklist_prompt .= "5. **SEO Opportunities**\n\n"; $checklist_prompt .= " - Gợi ý LSI keywords, entity liên quan.\n\n"; $checklist_prompt .= " - Gợi ý schema nên dùng.\n\n"; $checklist_prompt .= " - Định hướng cấu trúc bài chuẩn SEO.\n\n"; $checklist_prompt .= "Hãy trình bày phân tích một cách logic, có chiều sâu, theo phong cách tác giả chuyên nghiệp.\n\n"; $checklist_prompt .= "IMPORTANT: Return the analysis in JSON format only. Keep responses concise and structured. Use this JSON structure:\n"; $checklist_prompt .= "{\n"; $checklist_prompt .= " \"user_intent\": {\"what_they_want\": \"\", \"problems\": \"\", \"purpose\": \"\"},\n"; $checklist_prompt .= " \"search_intent\": {\"type\": \"\", \"reason\": \"\"},\n"; $checklist_prompt .= " \"user_expectations\": [],\n"; $checklist_prompt .= " \"content_to_provide\": {\"required_sections\": [], \"unique_insights\": \"\", \"priorities\": \"\"},\n"; $checklist_prompt .= " \"seo_opportunities\": {\"lsi_keywords\": [], \"schema\": \"\", \"structure\": \"\"}\n"; $checklist_prompt .= "}\n\n"; if (!empty($author_bio)) { $checklist_prompt .= "Author description: {$author_bio}\n\n"; } // Step 1: Generate Checklist - Sử dụng AI Agent với tự động fallback $checklist_text = ''; // Lấy provider_id từ settings nếu không có trong request if (empty($provider_id) && class_exists('AIAutotool_AI_Provider_Manager')) { $manager = AIAutotool_AI_Provider_Manager::get_instance(); $active_provider = $manager->get_active_provider(); if ($active_provider) { $provider_id = $active_provider->get_id(); } } if (defined('WP_DEBUG') && WP_DEBUG) { } $checklist_result = $generate_with_agent($checklist_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 2000, 'temperature' => 0.7, 'use_case' => 'reasoning' )); if (is_array($checklist_result) && isset($checklist_result['code']) && $checklist_result['code'] != '200') { $stream->send_error($checklist_result['msg'] ?: 'Failed to generate checklist'); $stream->close(); return; } $checklist_text = is_array($checklist_result) ? ($checklist_result['result'] ?? '') : $checklist_result; if (defined('WP_DEBUG') && WP_DEBUG && isset($checklist_result['provider'])) { } // Convert markdown to HTML $checklist_text = $convert_markdown_to_html($checklist_text); $stream->send_step_output(1, $checklist_text); $stream->send_step_complete(1, 'success'); // Step 2: Generate Author Credibility Info - Sử dụng AI Agent $stream->send_step_start(2, 'generate_author_credibility', 'Generating author credibility information...'); $author_credibility_prompt = $get_language_instruction($lang); $author_credibility_prompt .= "Based on the checklist from step 1, create author credibility information to establish credibility for the article.\n"; $author_credibility_prompt .= "ONLY RETURN THE NECESSARY INFORMATION, DO NOT WRITE ANYTHING ELSE.\n\n"; $author_credibility_prompt .= "Checklist from step 1:\n{$checklist_text}\n\n"; $author_credibility_prompt .= "Author name: {$author_name}\n"; if (!empty($author_bio)) { $author_credibility_prompt .= "Current author description: {$author_bio}\n"; } $author_credibility_prompt .= "\nONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n"; if (defined('WP_DEBUG') && WP_DEBUG) { } $author_credibility_result = $generate_with_agent($author_credibility_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 500, 'temperature' => 0.7 )); if (is_array($author_credibility_result) && isset($author_credibility_result['code']) && $author_credibility_result['code'] != '200') { $stream->send_error($author_credibility_result['msg'] ?: 'Failed to generate author credibility info'); $stream->close(); return; } $author_credibility_text = is_array($author_credibility_result) ? ($author_credibility_result['result'] ?? '') : $author_credibility_result; // Convert markdown to HTML $author_credibility_text = $convert_markdown_to_html($author_credibility_text); $stream->send_step_output(2, $author_credibility_text); $stream->send_step_complete(2, 'success'); // Step 3: Analyze Keywords $stream->send_step_start(3, 'analyze_keywords', 'Analyzing required keywords...'); // Tối ưu hóa prompt: giới hạn độ dài và làm sạch text $checklist_summary = mb_substr(strip_tags($checklist_text), 0, 150, 'UTF-8'); $author_credibility_summary = mb_substr(strip_tags($author_credibility_text), 0, 150, 'UTF-8'); // Làm sạch và rút gọn text $checklist_summary = preg_replace('/\s+/', ' ', trim($checklist_summary)); $author_credibility_summary = preg_replace('/\s+/', ' ', trim($author_credibility_summary)); $keywords_prompt = $get_language_instruction($lang); $keywords_prompt .= "Based on the following information, create a list of necessary keywords for the article.\n"; $keywords_prompt .= "ONLY RETURN KEYWORDS, DO NOT ADD ANY DESCRIPTION.\n\n"; $keywords_prompt .= "Title: {$title}\n\n"; $keywords_prompt .= "Checklist: {$checklist_summary}\n"; $keywords_prompt .= "Author credibility information: {$author_credibility_summary}\n\n"; $keywords_prompt .= "Requirements:\n"; $keywords_prompt .= "1. 10-15 main keywords\n"; $keywords_prompt .= "2. Secondary keywords and LSI\n\n"; $keywords_prompt .= "ONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n"; // Log prompt length for debugging if (defined('WP_DEBUG') && WP_DEBUG) { } if (defined('WP_DEBUG') && WP_DEBUG) { } $keywords_analysis = $generate_with_agent($keywords_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 800, 'temperature' => 0.7 )); if (is_array($keywords_analysis) && isset($keywords_analysis['code']) && $keywords_analysis['code'] != '200') { $error_msg = $keywords_analysis['msg'] ?: 'Failed to analyze keywords'; if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_error('Step 3 - Keywords analysis failed: ' . $error_msg . ' (Error code: ' . (isset($keywords_analysis['code']) ? $keywords_analysis['code'] : 'N/A') . ')'); $stream->close(); return; } $keywords_analysis_text = is_array($keywords_analysis) ? ($keywords_analysis['result'] ?? '') : $keywords_analysis; // Convert markdown to HTML $keywords_analysis_text = $convert_markdown_to_html($keywords_analysis_text); $stream->send_step_output(3, $keywords_analysis_text); $stream->send_step_complete(3, 'success'); // Step 4: Determine Content Direction $stream->send_step_start(4, 'determine_direction', 'Determining article content direction...'); // Tối ưu hóa prompt: giới hạn độ dài các phân tích $checklist_summary = mb_substr(strip_tags($checklist_text), 0, 200, 'UTF-8'); $author_credibility_summary = mb_substr(strip_tags($author_credibility_text), 0, 200, 'UTF-8'); $keywords_summary = mb_substr(strip_tags($keywords_analysis_text), 0, 300, 'UTF-8'); // Làm sạch text $checklist_summary = preg_replace('/\s+/', ' ', trim($checklist_summary)); $author_credibility_summary = preg_replace('/\s+/', ' ', trim($author_credibility_summary)); $keywords_summary = preg_replace('/\s+/', ' ', trim($keywords_summary)); $direction_prompt = $get_language_instruction($lang); $direction_prompt .= "Title: {$title}\n\n"; $direction_prompt .= "Analysis summary:\n"; $direction_prompt .= "- Checklist: {$checklist_summary}\n"; $direction_prompt .= "- Author credibility information: {$author_credibility_summary}\n"; $direction_prompt .= "- Keywords: {$keywords_summary}\n\n"; $direction_prompt .= "Requirements:\n"; $direction_prompt .= "1. Article structure (number of sections, headings)\n"; $direction_prompt .= "2. Content and main points\n"; $direction_prompt .= "3. Style and tone\n"; $direction_prompt .= "4. Length and format\n\n"; $direction_prompt .= "ONLY RETURN the requested content in text format, DO NOT ADD ANY DESCRIPTION.\n\n"; // Log prompt length for debugging if (defined('WP_DEBUG') && WP_DEBUG) { } if (defined('WP_DEBUG') && WP_DEBUG) { } $direction_analysis = $generate_with_agent($direction_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 1000, 'temperature' => 0.7 )); if (is_array($direction_analysis) && isset($direction_analysis['code']) && $direction_analysis['code'] != '200') { $stream->send_error($direction_analysis['msg'] ?: 'Failed to determine content direction'); $stream->close(); return; } $direction_analysis_text = is_array($direction_analysis) ? ($direction_analysis['result'] ?? '') : $direction_analysis; // Convert markdown to HTML $direction_analysis_text = $convert_markdown_to_html($direction_analysis_text); $stream->send_step_output(4, $direction_analysis_text); $stream->send_step_complete(4, 'success'); // Step 5: Find Related Posts & Internal Linking Strategy (moved before writing article) // Check if auto internal links is enabled $auto_internal_links = isset($data['autoInternalLinks']) ? filter_var($data['autoInternalLinks'], FILTER_VALIDATE_BOOLEAN) : true; // Default to true if not set $related_posts = array(); if ($auto_internal_links) { $stream->send_step_start(5, 'find_related_posts', 'Finding related posts for internal linking...'); // Find related posts (before writing article, so we can include them in the prompt) $related_posts = $find_related_posts_for_internal_linking($title, $keywords_analysis_text, $lang, '', 5); } $related_posts_info_for_prompt = ''; $related_posts_display = ''; if ($auto_internal_links && !empty($related_posts)) { // Prepare related posts information for prompt $related_posts_info_for_prompt = "\n\nRelated Posts for Internal Linking:\n"; foreach ($related_posts as $index => $post) { $related_posts_info_for_prompt .= ($index + 1) . ". Title: {$post['title']}\n"; $related_posts_info_for_prompt .= " URL: {$post['url']}\n"; $related_posts_info_for_prompt .= " Excerpt: {$post['excerpt']}\n"; $related_posts_info_for_prompt .= " Relevance: " . round($post['relevance_score'], 2) . "\n\n"; } $related_posts_info_for_prompt .= "IMPORTANT: Naturally insert internal links to these related posts in your article where relevant. Use markdown format: [anchor text](url). Make sure links are contextual and add value to readers.\n"; // Prepare for display $related_posts_display = "

    Related Posts Found for Internal Linking:

    \n\n

    These related posts will be included in the writing prompt so AI can naturally insert internal links while writing the article.

    "; } elseif ($auto_internal_links && empty($related_posts)) { $related_posts_display = "

    No related posts found for internal linking. This might be because:

    "; } else { $related_posts_display = "

    Auto Internal Links is disabled. Internal links will not be automatically inserted.

    "; } if ($auto_internal_links) { $stream->send_step_output(5, $related_posts_display); $stream->send_step_complete(5, 'success'); } else { // Skip step 5 if auto internal links is disabled $stream->send_step_start(5, 'find_related_posts', 'Auto Internal Links is disabled...'); $stream->send_step_output(5, $related_posts_display); $stream->send_step_complete(5, 'success'); } // Step 6: Generate Multiple Prompts (one for each section from step 1) $stream->send_step_start(6, 'generate_prompt', 'Generating optimized prompts for AI...'); // Define article end marker (used in both step 6 and step 7) $article_end_marker = ""; // Get the original prompt template if available $original_prompt = ''; if (isset($data['original_prompt']) && !empty($data['original_prompt'])) { $original_prompt = mb_substr(strip_tags($data['original_prompt']), 0, 500, 'UTF-8'); } // Parse checklist to extract required sections $article_sections = array(); $checklist_json = null; // Try to extract JSON from checklist_text $checklist_plain = strip_tags($checklist_text); // Try to find JSON in the text if (preg_match('/\{[^{}]*"required_sections"[^{}]*\}/s', $checklist_plain, $json_matches)) { // Try to find full JSON structure $json_start = strpos($checklist_plain, '{'); $json_end = strrpos($checklist_plain, '}'); if ($json_start !== false && $json_end !== false && $json_end > $json_start) { $json_str = substr($checklist_plain, $json_start, $json_end - $json_start + 1); $checklist_json = json_decode($json_str, true); } } // If JSON parsing failed, try to extract sections from text if (!$checklist_json || !isset($checklist_json['content_to_provide']['required_sections'])) { // Fallback: try to extract sections from text format if (preg_match('/required_sections["\']?\s*:\s*\[(.*?)\]/s', $checklist_plain, $sections_match)) { $sections_text = $sections_match[1]; // Try to extract quoted strings preg_match_all('/["\']([^"\']+)["\']/', $sections_text, $section_matches); if (!empty($section_matches[1])) { $article_sections = $section_matches[1]; } } // If still no sections, create default sections based on direction analysis if (empty($article_sections)) { // Create default sections: Introduction, Main Content, Conclusion $article_sections = array('Introduction', 'Main Content', 'Conclusion'); } } else { // Extract sections from JSON $article_sections = $checklist_json['content_to_provide']['required_sections']; if (empty($article_sections) || !is_array($article_sections)) { $article_sections = array('Introduction', 'Main Content', 'Conclusion'); } } // Ensure we have at least one section if (empty($article_sections)) { $article_sections = array('Introduction', 'Main Content', 'Conclusion'); } // Tối ưu hóa final prompt: giới hạn độ dài các phân tích $checklist_final = mb_substr(strip_tags($checklist_text), 0, 300, 'UTF-8'); $author_credibility_final = mb_substr(strip_tags($author_credibility_text), 0, 300, 'UTF-8'); $keywords_final = mb_substr(strip_tags($keywords_analysis_text), 0, 400, 'UTF-8'); $direction_final = mb_substr(strip_tags($direction_analysis_text), 0, 500, 'UTF-8'); // Làm sạch text $checklist_final = preg_replace('/\s+/', ' ', trim($checklist_final)); $author_credibility_final = preg_replace('/\s+/', ' ', trim($author_credibility_final)); $keywords_final = preg_replace('/\s+/', ' ', trim($keywords_final)); $direction_final = preg_replace('/\s+/', ' ', trim($direction_final)); // Add language instruction to final prompt FIRST $lang_instruction_final = $get_language_instruction($lang); // Build common requirements that will be used in all section prompts $common_requirements = "Requirements:\n"; $common_requirements .= "- output with Language: {$lang}\n"; $common_requirements .= "- Format: Markdown (## for headings, ** for bold, * for italic, - for lists, [text](url) for links)\n"; $common_requirements .= "- SEO: Optimize keywords\n"; $common_requirements .= "- Quality: High, useful, professional\n"; $common_requirements .= "- Style: According to analysis\n"; $common_requirements .= "- Write for readers. The writing should be poetic.\n"; // Add article settings if provided if (!empty($target_audience)) { $common_requirements .= "\nTarget Audience: {$target_audience}\n"; $common_requirements .= "IMPORTANT: Write this article specifically for {$target_audience}. Tailor the content, examples, and language to resonate with this audience.\n"; } if (!empty($tone)) { $tone_descriptions = array( 'professional' => 'professional, authoritative, and business-like', 'friendly' => 'friendly, warm, and approachable', 'humorous' => 'humorous, light-hearted, and entertaining', 'formal' => 'formal, respectful, and traditional', 'casual' => 'casual, relaxed, and conversational', 'authoritative' => 'authoritative, expert, and confident', 'conversational' => 'conversational, engaging, and personable' ); $tone_desc = isset($tone_descriptions[$tone]) ? $tone_descriptions[$tone] : $tone; $common_requirements .= "\nTone: Write in a {$tone_desc} tone throughout the article.\n"; } if (!empty($length_type)) { $length_instructions = array( 'short-form' => 'Keep the article concise and to the point (500-800 words). Focus on key information without extensive detail.', 'long-form' => 'Write a comprehensive, detailed article (2000+ words). Include in-depth explanations, examples, and thorough coverage of the topic.', 'comparison' => 'Structure the article as a comparison. Compare different options, approaches, or solutions with clear pros and cons.' ); if (isset($length_instructions[$length_type])) { $common_requirements .= "\nLength Type: {$length_instructions[$length_type]}\n"; } } if (!empty($competitors)) { $common_requirements .= "\nCompetitor Analysis:\n"; $common_requirements .= "The following are top competitor articles on similar topics:\n"; foreach ($competitors as $index => $competitor_url) { $common_requirements .= ($index + 1) . ". {$competitor_url}\n"; } $common_requirements .= "IMPORTANT: Analyze these competitor articles and create content that is:\n"; $common_requirements .= "- More comprehensive and valuable\n"; $common_requirements .= "- Better structured and easier to read\n"; $common_requirements .= "- More up-to-date and accurate\n"; $common_requirements .= "- Unique in perspective and approach\n"; } if (!empty($brand_voice_rules)) { $common_requirements .= "\nBrand Voice Rules:\n"; $common_requirements .= "Follow these brand voice guidelines when writing:\n"; $common_requirements .= $brand_voice_rules . "\n"; $common_requirements .= "IMPORTANT: Strictly adhere to these brand voice rules throughout the entire article.\n"; } // Add internal linking requirements if related posts found if ($auto_internal_links && !empty($related_posts)) { $common_requirements .= $related_posts_info_for_prompt; $common_requirements .= "- Insert 3-5 internal links directly and naturally within the paragraphs of the article, using appropriate keywords in context. Do NOT place links on separate lines; links must be inside the main text, not as standalone items.\n"; $common_requirements .= "- Each related post/link should appear only ONCE in the entire article. Do NOT insert the same link multiple times.\n"; $common_requirements .= "- Use natural anchor text (not exact post titles) that fits the context and the keywords.\n"; $common_requirements .= "- Don't over-link: maximum 1 link per 200 words.\n"; $common_requirements .= "- Links should be contextually relevant to the surrounding paragraph and enhance the reader's experience.\n\n"; } // Generate prompts for each section $section_prompts = array(); $total_sections = count($article_sections); for ($i = 0; $i < $total_sections; $i++) { $section_name = $article_sections[$i]; $is_first_section = ($i === 0); $is_last_section = ($i === $total_sections - 1); $section_prompt = $lang_instruction_final; if ($is_first_section) { $section_prompt .= "Write the first section of the article:\n\n"; } else { $section_prompt .= "Continue writing the next section of the article:\n\n"; } $section_prompt .= "Title: {$title}\n\n"; $section_prompt .= "Analysis:\n"; $section_prompt .= "1. Checklist: {$checklist_final}\n"; $section_prompt .= "2. Keywords: {$keywords_final}\n"; $section_prompt .= "3. Content direction: {$direction_final}\n\n"; $section_prompt .= "Current Section to Write: {$section_name}\n"; $section_prompt .= "Section Number: " . ($i + 1) . " of {$total_sections}\n\n"; $section_prompt .= $common_requirements; if ($is_first_section) { $section_prompt .= "\n- IMPORTANT: Write the article directly, DO NOT introduce your AI role, DO NOT say \"Excellent!\", \"As a...\", \"I believe I can...\" or any introductory phrases. Start writing the article immediately.\n"; $section_prompt .= "- Write the introduction section of the article. This should be engaging and hook the reader.\n"; } else { $section_prompt .= "\n- IMPORTANT: Continue writing seamlessly from the previous section.\n"; $section_prompt .= "- You will receive the last part of the previous section to continue from.\n"; $section_prompt .= "- Write the section: {$section_name}\n"; $section_prompt .= "- Make sure the transition is smooth and natural.\n"; } if ($is_last_section) { $section_prompt .= "\n- CRITICAL: When you finish writing this final section, you MUST add this exact marker at the very end: {$article_end_marker}\n"; $section_prompt .= "- This marker indicates that the article is complete. Do NOT add any content after this marker.\n"; $section_prompt .= "- Make sure to write a proper conclusion that wraps up the article.\n"; } if (!empty($original_prompt) && $is_first_section) { $section_prompt .= "\nAdditional: {$original_prompt}\n"; } if ($is_first_section) { $section_prompt .= "\nWrite the first section of the article now."; } else { $section_prompt .= "\nYou will receive the previous section's ending to continue from. Write the next section."; } $section_prompts[] = array( 'section_name' => $section_name, 'section_index' => $i, 'prompt' => $section_prompt, 'is_first' => $is_first_section, 'is_last' => $is_last_section ); } // Display all prompts $prompts_display = "Generated " . count($section_prompts) . " prompts for article sections:\n\n"; foreach ($section_prompts as $idx => $sp) { $prompts_display .= "Section " . ($idx + 1) . ": {$sp['section_name']}\n"; } $prompts_display .= "\n" . str_repeat("=", 50) . "\n\n"; $prompts_display .= "First section prompt preview:\n\n"; $prompts_display .= mb_substr($section_prompts[0]['prompt'], 0, 1000, 'UTF-8') . "..."; $stream->send_step_output(6, $prompts_display); $stream->send_step_complete(6, 'success'); // Step 7: Write Article $stream->send_step_start(7, 'write_article', 'Writing article...'); $stream->send_status('Generating article content with AI...'); // Log final prompt length before writing article if (defined('WP_DEBUG') && WP_DEBUG) { } if (defined('WP_DEBUG') && WP_DEBUG) { } // Build system prompt for article writing // Prepare author information for system prompt $author_info_for_system = ''; if (!empty($author_credibility_text)) { $author_credibility_plain = strip_tags($author_credibility_text); $author_credibility_plain = preg_replace('/\s+/', ' ', trim($author_credibility_plain)); // Limit to reasonable length for system prompt $author_info_for_system = mb_substr($author_credibility_plain, 0, 500, 'UTF-8'); } $system_prompt = "You are an expert content writer and SEO specialist with years of experience creating high-quality, engaging articles.\n\n"; // Add author role information to system prompt if (!empty($author_info_for_system)) { $system_prompt .= "Author Role and Credibility:\n"; $system_prompt .= "You are writing as the article author with the following background and credibility:\n"; $system_prompt .= $author_info_for_system . "\n\n"; $system_prompt .= "IMPORTANT: Embody this author persona when writing. Write from this author's perspective, using their expertise, experience, and voice. "; $system_prompt .= "However, DO NOT explicitly mention or introduce this author information in the article content itself. "; $system_prompt .= "Instead, let your writing naturally reflect this author's expertise and perspective through the quality, depth, and style of the content.\n\n"; } $system_prompt .= "Your role:\n"; $system_prompt .= "- Write comprehensive, well-structured articles that provide real value to readers\n"; $system_prompt .= "- Optimize content for SEO while maintaining natural, readable flow\n"; $system_prompt .= "- Use proper markdown formatting (## for headings, ** for bold, * for italic, - for lists, [text](url) for links)\n"; $system_prompt .= "- Create content that is original, informative, and engaging\n\n"; $system_prompt .= "Writing guidelines:\n"; $system_prompt .= "- Write directly as the article author - DO NOT introduce yourself as AI\n"; $system_prompt .= "- DO NOT use phrases like \"Excellent!\", \"As a...\", \"I believe I can...\", or any introductory phrases\n"; $system_prompt .= "- Start writing the article content immediately\n"; $system_prompt .= "- Integrate information naturally and organically, not mechanically\n"; $system_prompt .= "- Write for readers first, ensuring the content is valuable and easy to understand\n"; $system_prompt .= "- Use a poetic, engaging writing style when appropriate\n"; $system_prompt .= "- Maintain consistency in tone and style throughout the article\n\n"; $system_prompt .= "Quality standards:\n"; $system_prompt .= "- High-quality, professional content\n"; $system_prompt .= "- Accurate, up-to-date information\n"; $system_prompt .= "- Well-structured with clear headings and subheadings\n"; $system_prompt .= "- Natural keyword integration (1-2% keyword density)\n"; $system_prompt .= "- Engaging introduction and strong conclusion with CTA when appropriate\n\n"; $system_prompt .= "Article completion marker:\n"; $system_prompt .= "- When you finish writing the complete article, you MUST add this exact marker at the very end: \n"; $system_prompt .= "- This marker indicates that the article is complete. Do NOT add any content after this marker.\n"; $system_prompt .= "- Only add this marker when the article is truly finished with a proper conclusion.\n"; // Add language requirement to system prompt $lang_instruction = $get_language_instruction($lang); if (!empty($lang_instruction)) { $system_prompt .= "\n" . $lang_instruction; } // Helper function to extract article content up to the end marker $extract_article_content = function($text) use (&$article_end_marker) { if (empty($text)) { return $text; } // Check if marker exists in the text $marker_pos = strpos($text, $article_end_marker); if ($marker_pos !== false) { // Extract content before the marker $extracted = substr($text, 0, $marker_pos); // Remove any trailing whitespace $extracted = rtrim($extracted); if (defined('WP_DEBUG') && WP_DEBUG) { } return $extracted; } // Marker not found, return original text return $text; }; // Helper function to check if article is incomplete $is_article_incomplete = function($text, $length_type) use (&$article_end_marker) { if (empty($text)) { return true; } // First check: if marker exists, article is complete if (strpos($text, $article_end_marker) !== false) { return false; // Article is complete (has marker) } // Remove HTML tags for accurate length checking $plain_text = strip_tags($text); $plain_text = preg_replace('/\s+/', ' ', $plain_text); // Normalize whitespace $char_count = mb_strlen($plain_text); // For long-form articles, check character/word count - MUST be at least 2000 words if ($length_type === 'long-form') { // Estimate word count: approximately 5 characters per word (works for most languages) $estimated_words = $char_count / 5; // Long-form articles MUST be at least 2000 words (approximately 10000 characters) // If less than 2000 words, article is definitely incomplete if ($char_count < 10000 || $estimated_words < 2000) { if (defined('WP_DEBUG') && WP_DEBUG) { } return true; // Must continue writing } } // Check if article ends abruptly (no conclusion, ends mid-sentence) $text_trimmed = trim($plain_text); if (empty($text_trimmed)) { return true; } $last_chars = mb_substr($text_trimmed, -10); // Last 10 characters $last_sentence = mb_substr($text_trimmed, -200); // Last 200 characters for context // Check for proper ending punctuation $proper_endings = array('.', '!', '?', '。', '!', '?', '…'); $ends_properly = false; foreach ($proper_endings as $ending) { if (mb_substr($text_trimmed, -1) === $ending) { $ends_properly = true; break; } } // Check for conclusion keywords $conclusion_keywords = array( 'kết luận', 'conclusion', 'tóm lại', 'tổng kết', 'summary', 'tổng hợp', 'tổng kết lại', 'kết luận lại', 'tóm tắt', 'tổng hợp lại' ); $has_conclusion = false; $last_sentence_lower = mb_strtolower($last_sentence); foreach ($conclusion_keywords as $keyword) { if (mb_stripos($last_sentence_lower, $keyword) !== false) { $has_conclusion = true; break; } } // For long-form articles: if doesn't end properly and no conclusion, likely incomplete if ($length_type === 'long-form') { // Even if ends properly, if no conclusion section, might be incomplete if (!$has_conclusion && $char_count < 12000) { // If less than 12000 chars and no conclusion, likely incomplete if (defined('WP_DEBUG') && WP_DEBUG) { } return true; } // If doesn't end properly, definitely incomplete if (!$ends_properly && !$has_conclusion) { return true; } } return false; }; // Write article section by section $article_text = ''; $previous_section_ending = ''; // Check if section_prompts exists (from step 6) if (!isset($section_prompts) || empty($section_prompts)) { // Fallback: if section_prompts not available, use old method if (defined('WP_DEBUG') && WP_DEBUG) { } // Use final_prompt if available, otherwise create a basic one if (!isset($final_prompt) || empty($final_prompt)) { $final_prompt = $lang_instruction_final . "Write a complete article about: {$title}\n\n"; $final_prompt .= "Requirements:\n"; $final_prompt .= "- Language: {$lang}\n"; $final_prompt .= "- Format: Markdown\n"; $final_prompt .= "- Write directly, DO NOT introduce yourself.\n"; } $article_content = $generate_with_agent($final_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 4000, 'temperature' => 0.8, 'use_case' => 'long_context', 'system' => $system_prompt )); if (is_array($article_content) && isset($article_content['code']) && $article_content['code'] != '200') { $stream->send_error($article_content['msg'] ?: 'Failed to generate article'); $stream->close(); return; } $article_text = is_array($article_content) ? ($article_content['result'] ?? '') : $article_content; $article_text = $extract_article_content($article_text); } else { // Write section by section using section_prompts $total_sections = count($section_prompts); for ($section_idx = 0; $section_idx < $total_sections; $section_idx++) { $section_data = $section_prompts[$section_idx]; $section_name = $section_data['section_name']; $section_prompt = $section_data['prompt']; $is_first = $section_data['is_first']; $is_last = $section_data['is_last']; if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_status('Writing section ' . ($section_idx + 1) . ' of ' . $total_sections . ': ' . $section_name . '...'); // If not first section, add previous section ending to prompt if (!$is_first && !empty($previous_section_ending)) { // Get last 1500 characters of previous section for context $context_ending = mb_substr($previous_section_ending, -1500); // Modify prompt to include previous section ending $section_prompt .= "\n\n---\n"; $section_prompt .= "Here is the ending of the previous section to continue from:\n\n"; $section_prompt .= $context_ending . "\n\n"; $section_prompt .= "---\n\n"; $section_prompt .= "IMPORTANT: Continue writing seamlessly from the last sentence above. "; $section_prompt .= "Do NOT repeat what was already written. Maintain the same writing style and tone.\n"; } // Generate section content $section_content = $generate_with_agent($section_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 4000, 'temperature' => 0.8, 'use_case' => 'long_context', 'system' => $system_prompt )); if (is_array($section_content) && isset($section_content['code']) && $section_content['code'] != '200') { $error_msg = $section_content['msg'] ?: 'Failed to generate section: ' . $section_name; if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_error($error_msg); // Continue with next section or break if ($is_last) { break; } continue; } $section_text = is_array($section_content) ? ($section_content['result'] ?? '') : $section_content; if (defined('WP_DEBUG') && WP_DEBUG && isset($section_content['provider'])) { } // Extract content up to the end marker (if marker exists in last section) if ($is_last) { $section_text = $extract_article_content($section_text); } // Check if this section has a main heading (h2/h3) in markdown and search for image BEFORE adding to article_text if (!empty($section_text)) { $section_has_main_heading = false; $main_heading_title = ''; $main_heading_markdown_pos = -1; // Check for h2 heading in markdown (## heading) if (preg_match('/^##\s+(.+)$/m', $section_text, $h2_match, PREG_OFFSET_CAPTURE)) { $section_has_main_heading = true; $main_heading_title = trim($h2_match[1][0]); $main_heading_markdown_pos = $h2_match[0][1] + strlen($h2_match[0][0]); } elseif (preg_match('/^###\s+(.+)$/m', $section_text, $h3_match, PREG_OFFSET_CAPTURE)) { // Fallback to h3 if no h2 $section_has_main_heading = true; $main_heading_title = trim($h3_match[1][0]); $main_heading_markdown_pos = $h3_match[0][1] + strlen($h3_match[0][0]); } // If section has main heading, search and insert image into markdown if ($section_has_main_heading && !empty($main_heading_title) && strlen($main_heading_title) > 3) { $stream->send_status('Đang tìm hình ảnh cho section: ' . $main_heading_title . '...'); // Get section content for better search query $section_content_plain = strip_tags($section_text); $section_content_plain = mb_substr($section_content_plain, 0, 500, 'UTF-8'); // Generate search query using AI $image_search_query = $main_heading_title; if (!empty($section_content_plain) && strlen($section_content_plain) > 20) { $query_prompt = $get_language_instruction($lang); $query_prompt .= "Tạo một từ khóa tìm kiếm hình ảnh ngắn gọn (3-5 từ) phù hợp với section sau:\n\n"; $query_prompt .= "Tiêu đề section: {$main_heading_title}\n"; $query_prompt .= "Nội dung section: " . mb_substr($section_content_plain, 0, 300, 'UTF-8') . "\n\n"; $query_prompt .= "Yêu cầu:\n"; $query_prompt .= "- Chỉ trả về từ khóa tìm kiếm, không có giải thích\n"; $query_prompt .= "- Từ khóa phải phù hợp để tìm hình ảnh minh họa\n"; $query_prompt .= "- Tối đa 5 từ\n\n"; $query_prompt .= "Chỉ trả về từ khóa tìm kiếm:"; $query_result = $generate_with_agent($query_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 50, 'temperature' => 0.7, 'use_case' => 'fast' )); if (is_array($query_result) && isset($query_result['code']) && $query_result['code'] == '200') { $generated_query = is_array($query_result) ? trim($query_result['result'] ?? '') : trim($query_result); $generated_query = strip_tags($generated_query); $generated_query = preg_replace('/["\']/', '', $generated_query); if (!empty($generated_query) && strlen($generated_query) > 3) { $image_search_query = $generated_query; } } } // Search for image try { $image_results = $bardGenContent->searchimg($image_search_query); // Handle both cases: direct array or object with 'result' key $image_array = null; if (is_array($image_results) && !empty($image_results)) { // Direct array case (sendPostRequest returns $decoded->result) $image_array = $image_results; } elseif (is_object($image_results) && isset($image_results->result) && is_array($image_results->result) && !empty($image_results->result)) { // Object with 'result' key case $image_array = $image_results->result; } elseif (isset($image_results['result']) && is_array($image_results['result']) && !empty($image_results['result'])) { // Array with 'result' key case $image_array = $image_results['result']; } if ($image_array && !empty($image_array)) { $selected_image = $image_array[0]; // Create image markdown format $image_markdown = "\n\n![{$main_heading_title}]({$selected_image})\n\n"; // Insert image after heading in section_text (markdown) $section_text = substr_replace($section_text, $image_markdown, $main_heading_markdown_pos, 0); $stream->send_status('✓ Đã tìm và chèn hình ảnh cho section: ' . $main_heading_title); // Stream section content immediately after inserting image (especially for section 1) if ($is_first || $section_idx === 0) { $section_html = $convert_markdown_to_html($section_text); if (!empty($section_html)) { $section_header = '
    '; $section_header .= '
    Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '
    '; $section_footer = '
    '; $stream->send_step_output(7, $section_header . $section_html . $section_footer); } } if (defined('WP_DEBUG') && WP_DEBUG) { } } else { // Fallback: try with section title only if ($image_search_query !== $main_heading_title) { $image_results = $bardGenContent->searchimg($main_heading_title); if ($image_results && isset($image_results['result']) && is_array($image_results['result']) && !empty($image_results['result'])) { $selected_image = $image_results['result'][0]; $image_markdown = "\n\n![{$main_heading_title}]({$selected_image})\n\n"; $section_text = substr_replace($section_text, $image_markdown, $main_heading_markdown_pos, 0); $stream->send_status('✓ Đã tìm và chèn hình ảnh cho section: ' . $main_heading_title); // Stream section content immediately after inserting image (especially for section 1) if ($is_first || $section_idx === 0) { $section_html = $convert_markdown_to_html($section_text); if (!empty($section_html)) { $section_header = '
    '; $section_header .= '
    Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '
    '; $section_footer = '
    '; $stream->send_step_output(7, $section_header . $section_html . $section_footer); } } } } } } catch (Exception $img_ex) { if (defined('WP_DEBUG') && WP_DEBUG) { } } // Small delay usleep(300000); // 0.3 second delay } // If not first section, add a newline for separation if (!empty($article_text)) { $article_text .= "\n\n"; } // Append section_text (which now includes image if found) to article_text $article_text .= $section_text; // Store the ending of this section for next iteration // Take last 2000 characters for context $previous_section_ending = mb_substr($section_text, -2000); // Convert section to HTML and display the entire section at once $section_html = $convert_markdown_to_html($section_text); if (!empty($section_html)) { // Add section header for clarity $section_header = '
    '; $section_header .= '
    Section ' . ($section_idx + 1) . ': ' . esc_html($section_name) . '
    '; $section_footer = '
    '; // Send the complete section at once (with image if found) $stream->send_step_output(7, $section_header . $section_html . $section_footer); } } // If this is the last section and we have the end marker, we're done if ($is_last && strpos($section_text, $article_end_marker) !== false) { if (defined('WP_DEBUG') && WP_DEBUG) { } break; } } } // Check if article is incomplete and continue writing if needed (fallback for edge cases) // For long-form articles, allow more continuation attempts to ensure minimum length $max_continuations = ($length_type === 'long-form') ? 3 : 1; $continuation_count = 0; while ($is_article_incomplete($article_text, $length_type) && $continuation_count < $max_continuations) { $continuation_count++; if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_status('Continuing article writing... (part ' . ($continuation_count + 1) . ')'); // Get the last part of the article to continue from // Take last 2000 characters to maintain context $context_text = mb_substr($article_text, -2000); // Create continuation prompt $continue_prompt = "Continue writing the article from where it left off. Here is the incomplete part:\n\n"; $continue_prompt .= $context_text . "\n\n"; $continue_prompt .= "IMPORTANT:\n"; $continue_prompt .= "- Continue seamlessly from the last sentence\n"; $continue_prompt .= "- Do NOT repeat what was already written\n"; $continue_prompt .= "- Maintain the same writing style and tone\n"; $continue_prompt .= "- Complete the article with a proper conclusion if this is the final part\n"; $continue_prompt .= "- Write directly, DO NOT introduce yourself or add any meta-commentary\n"; $continue_prompt .= "\nCRITICAL: When you finish writing the complete article, you MUST add this exact marker at the very end: {$article_end_marker}\n"; $continue_prompt .= "This marker indicates that the article is complete. Do NOT add any content after this marker.\n"; // Add original requirements for consistency if (!empty($length_type) && $length_type === 'long-form') { // Calculate current word count to inform AI $plain_text = strip_tags($article_text); $plain_text = preg_replace('/\s+/', ' ', $plain_text); $current_chars = mb_strlen($plain_text); $current_words = round($current_chars / 5); $continue_prompt .= "\nLENGTH REQUIREMENT (CRITICAL):\n"; $continue_prompt .= "- Current article length: approximately {$current_words} words\n"; $continue_prompt .= "- REQUIRED: You MUST write at least 2000+ words total (currently at {$current_words} words)\n"; $continue_prompt .= "- Continue writing substantial content to reach the minimum requirement\n"; $continue_prompt .= "- Add the end marker ONLY when you have written at least 2000 words total\n"; $continue_prompt .= "- If you haven't reached 2000 words yet, continue writing more content\n"; } // Generate continuation $continue_content = $generate_with_agent($continue_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 4000, 'temperature' => 0.8, 'use_case' => 'long_context', 'system' => $system_prompt )); if (is_array($continue_content) && isset($continue_content['code']) && $continue_content['code'] != '200') { // If continuation fails, break and use what we have if (defined('WP_DEBUG') && WP_DEBUG) { } break; } $continue_text = is_array($continue_content) ? ($continue_content['result'] ?? '') : $continue_content; // Extract content up to the end marker (if marker exists) $continue_text = $extract_article_content($continue_text); if (!empty($continue_text)) { // Remove any potential overlap by finding where the continuation starts // Check if continuation begins with content that's already in article_text $continue_trimmed = trim($continue_text); $overlap_found = false; // Check for overlap in first 200 characters if (strlen($continue_trimmed) > 200) { $continue_start = substr($continue_trimmed, 0, 200); if (strpos($article_text, $continue_start) !== false) { $overlap_found = true; // Find where this content appears in article_text and start from after it $pos = strpos($article_text, $continue_start); if ($pos !== false) { $continue_text = substr($continue_trimmed, strlen($continue_start)); } } } // Append continuation if (!empty(trim($continue_text))) { $article_text .= "\n\n" . $continue_text; // Convert continuation to HTML and stream it $continue_html = $convert_markdown_to_html($continue_text); if (!empty($continue_html)) { $chunk_size = 100; $continue_length = strlen($continue_html); for ($i = 0; $i < $continue_length; $i += $chunk_size) { $chunk = substr($continue_html, $i, $chunk_size); $stream->send_step_output(7, $chunk); usleep(50000); // Small delay for streaming effect } } // For long-form: check if continuation added enough content if ($length_type === 'long-form' && $continuation_count < $max_continuations) { $plain_text_check = strip_tags($article_text); $plain_text_check = preg_replace('/\s+/', ' ', $plain_text_check); $current_chars = mb_strlen($plain_text_check); $current_words = round($current_chars / 5); // If still too short and we have more attempts, log it if ($current_chars < 10000 && $continuation_count < $max_continuations - 1) { if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_status('Article length: ~' . $current_words . ' words. Continuing to reach 2000+ words...'); } } } else { // Continuation text is empty, but for long-form we should try again if ($length_type === 'long-form' && $continuation_count < $max_continuations - 1) { if (defined('WP_DEBUG') && WP_DEBUG) { } // Don't break, continue to next iteration } else { // No continuation content, break break; } } } else { // No continuation content, but for long-form we should try again if ($length_type === 'long-form' && $continuation_count < $max_continuations - 1) { if (defined('WP_DEBUG') && WP_DEBUG) { } // Don't break, continue to next iteration } else { // No continuation content, break break; } } // Small delay before checking again usleep(100000); // 100ms } // Final check for long-form articles if ($length_type === 'long-form') { $plain_text_final = strip_tags($article_text); $plain_text_final = preg_replace('/\s+/', ' ', $plain_text_final); $final_chars = mb_strlen($plain_text_final); $final_words = round($final_chars / 5); if ($final_chars < 10000) { if (defined('WP_DEBUG') && WP_DEBUG) { } $stream->send_status('Warning: Article length is ~' . $final_words . ' words. Target was 2000+ words.'); } else { if (defined('WP_DEBUG') && WP_DEBUG) { } } } if ($continuation_count > 0 && defined('WP_DEBUG') && WP_DEBUG) { } // Step 8: Generate introduction and conclusion summary (mobai and ketbai) $stream->send_status('writing introduction and conclusion...'); if (defined('WP_DEBUG') && WP_DEBUG) { } // Prepare article text for summary // Since $article_text is still in markdown format, we'll convert it to plain text for summary // Remove markdown formatting for cleaner summary context $article_plain_text = $article_text; $article_plain_text = preg_replace('/#{1,6}\s+/', '', $article_plain_text); // Remove headers $article_plain_text = preg_replace('/\*\*(.*?)\*\*/', '$1', $article_plain_text); // Remove bold $article_plain_text = preg_replace('/\*(.*?)\*/', '$1', $article_plain_text); // Remove italic $article_plain_text = preg_replace('/\[([^\]]+)\]\([^\)]+\)/', '$1', $article_plain_text); // Remove links $article_plain_text = preg_replace('/\s+/', ' ', $article_plain_text); // Normalize whitespace $article_plain_text = trim($article_plain_text); // Get full article for better context (but limit to avoid token limits) $article_for_context = $article_plain_text; if (mb_strlen($article_for_context) > 4000) { // Take first 2000 and last 2000 characters for better context $article_for_context = mb_substr($article_for_context, 0, 2000) . ' ... ' . mb_substr($article_for_context, -2000); } // Create prompt to generate both mobai (introduction) and ketbai (conclusion) in JSON format if (stripos($lang, 'vietnamese') !== false || stripos($lang, 'việt') !== false || $lang === 'vi' || $lang === 'Vietnamese') { $summary_prompt = "Dựa trên nội dung bài viết sau đây, hãy tạo 2 phần:\n\n"; $summary_prompt .= "1. MỞ BÀI (mobai): Viết một đoạn mở bài giới thiệu ngắn gọn (3-5 câu) dựa trên các ý chính quan trọng của bài viết. Phần này sẽ được dùng để giới thiệu bài viết.\n"; $summary_prompt .= "2. KẾT BÀI (ketbai): Viết một đoạn tóm tắt kết luận ngắn gọn (3-5 câu) các ý chính quan trọng nhất đã được trình bày trong bài viết.\n\n"; $summary_prompt .= "Yêu cầu:\n"; $summary_prompt .= "- Mỗi phần viết 3-5 câu, ngắn gọn, súc tích, dễ hiểu\n"; $summary_prompt .= "- Tập trung vào những thông tin quan trọng nhất\n"; $summary_prompt .= "- Viết tự nhiên, không cần tiêu đề 'Mở bài', 'Kết luận' hay 'Tóm tắt'\n"; $summary_prompt .= "- TRẢ VỀ ĐỊNH DẠNG JSON CHÍNH XÁC với 2 key: 'mobai' và 'ketbai'\n"; $summary_prompt .= "- Format JSON: {\"mobai\": \"nội dung mở bài\", \"ketbai\": \"nội dung kết bài\"}\n"; $summary_prompt .= "- CHỈ trả về JSON, không có text thêm, không có markdown code block\n\n"; } else { $summary_prompt = "Based on the following article content, create 2 parts:\n\n"; $summary_prompt .= "1. INTRODUCTION (mobai): Write a brief introduction paragraph (3-5 sentences) based on the main important points of the article. This will be used to introduce the article.\n"; $summary_prompt .= "2. CONCLUSION (ketbai): Write a brief conclusion summary (3-5 sentences) of the main important points presented in the article.\n\n"; $summary_prompt .= "Requirements:\n"; $summary_prompt .= "- Each part should be 3-5 sentences, concise, clear, and easy to understand\n"; $summary_prompt .= "- Focus on the most important information\n"; $summary_prompt .= "- Write naturally, no need for 'Introduction', 'Conclusion' or 'Summary' headings\n"; $summary_prompt .= "- RETURN EXACT JSON FORMAT with 2 keys: 'mobai' and 'ketbai'\n"; $summary_prompt .= "- JSON format: {\"mobai\": \"introduction content\", \"ketbai\": \"conclusion content\"}\n"; $summary_prompt .= "- RETURN ONLY JSON, no additional text, no markdown code block\n\n"; } $summary_prompt .= "Article content:\n" . $article_for_context; // Generate summary using AI $summary_result = $generate_with_agent($summary_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 800, 'temperature' => 0.7, 'use_case' => 'fast' )); if (is_array($summary_result) && isset($summary_result['code']) && $summary_result['code'] == '200') { $summary_response = is_array($summary_result) ? ($summary_result['result'] ?? '') : $summary_result; $summary_response = trim($summary_response); // Try to extract JSON from response (in case it's wrapped in markdown code block or has extra text) $json_match = null; if (preg_match('/\{[\s\S]*"mobai"[\s\S]*"ketbai"[\s\S]*\}/', $summary_response, $json_match)) { $summary_response = $json_match[0]; } // Remove markdown code blocks if present $summary_response = preg_replace('/```json\s*/', '', $summary_response); $summary_response = preg_replace('/```\s*/', '', $summary_response); $summary_response = trim($summary_response); // Parse JSON $summary_data = json_decode($summary_response, true); if ($summary_data && isset($summary_data['mobai']) && isset($summary_data['ketbai'])) { $mobai = trim($summary_data['mobai']); $ketbai = trim($summary_data['ketbai']); // Remove quotes if present $mobai = trim($mobai, ' "\''); $ketbai = trim($ketbai, ' "\''); if (!empty($mobai) && !empty($ketbai)) { // Add mobai at the beginning of article (after title if exists, or at the start) // Check if article starts with a heading (markdown ## or #) if (preg_match('/^(#{1,6}\s+.+?\n\n)/', $article_text, $matches)) { // Article starts with heading, add mobai after first heading $article_text = preg_replace('/^(#{1,6}\s+.+?\n\n)/', '$1' . $mobai . "\n\n", $article_text, 1); } else { // No heading at start, add mobai at the beginning $article_text = $mobai . "\n\n" . $article_text; } // Add ketbai at the end of article $article_text .= "\n\n" . $ketbai; if (defined('WP_DEBUG') && WP_DEBUG) { } // Stream the mobai and ketbai $mobai_html = $convert_markdown_to_html($mobai); $ketbai_html = $convert_markdown_to_html($ketbai); if (!empty($mobai_html)) { $stream->send_step_output(7, "\n\n" . $mobai_html); } if (!empty($ketbai_html)) { $stream->send_step_output(7, "\n\n" . $ketbai_html); } } else { if (defined('WP_DEBUG') && WP_DEBUG) { } } } else { if (defined('WP_DEBUG') && WP_DEBUG) { if (json_last_error() !== JSON_ERROR_NONE) { } } } } else { if (defined('WP_DEBUG') && WP_DEBUG) { $error_msg = isset($summary_result['msg']) ? $summary_result['msg'] : 'Unknown error'; } // Continue without summary if generation fails } // Convert final article to HTML (for final output) $article_text = $convert_markdown_to_html($article_text); $stream->send_step_complete(7, 'success', array('content' => $article_text)); // Update AI_post_usage counter after successful article generation $this->aiautotool_update_ai_post_usage(); // Send completion $stream->send_complete($article_text, array( 'checklist' => $checklist_text, 'author_credibility' => $author_credibility_text, 'keywords_analysis' => $keywords_analysis_text, 'direction_analysis' => $direction_analysis_text, 'final_prompt' => $final_prompt, 'article' => $article_text, 'related_posts' => $related_posts ), $message_id); } catch (Exception $e) { $error_msg = 'Error: ' . $e->getMessage(); if (defined('WP_DEBUG') && WP_DEBUG) { } // Make sure stream is started before sending error if (!$stream) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); } $stream->send_error($error_msg, array( 'exception' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ), $message_id); } catch (Error $e) { $error_msg = 'Fatal Error: ' . $e->getMessage(); if (defined('WP_DEBUG') && WP_DEBUG) { } // Make sure stream is started before sending error if (!isset($stream) || !$stream) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); } $stream->send_error($error_msg, array( 'exception' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ), $message_id); } if (isset($stream) && $stream) { $stream->close(); } else { // If stream was never created, exit cleanly exit; } } /** * AJAX callback for writing article with AI Auto Writer (SSE streaming) */ private function aiautotool_is_provider_retryable_error($error) { if (empty($error)) { return false; } $error = (string) $error; $retryable_patterns = array( '401', '403', '404', '408', '409', '422', '429', '500', '502', '503', '504', 'permission_denied', 'unauthorized', 'forbidden', 'invalid api key', 'invalid_api_key', 'invalid key', 'api key', 'quota', 'rate limit', 'too many requests', 'resource has been exhausted', 'billing', 'credits', 'credit', 'license', 'licenses', 'doesn\'t have any credits', 'does not have any credits', 'purchase', 'insufficient', 'balance', 'no balance', 'no credits', 'no active subscription', 'subscription', 'plan', 'team doesn\'t have', 'team does not have', 'invalid response structure', 'missing message content', 'failed to create outline', 'failed to parse outline', 'failed to write introduction', 'failed to write section', 'failed to write conclusion', 'incomplete article', 'empty response', 'timeout', 'timed out', 'connection error', 'network response was not ok', ); foreach ($retryable_patterns as $pattern) { if (stripos($error, $pattern) !== false) { return true; } } return false; } public function aiautotool_write_article_with_auto_writer_callback() { if (function_exists('ignore_user_abort')) { ignore_user_abort(true); } if (function_exists('set_time_limit')) { @set_time_limit(300); } @ini_set('max_execution_time', '300'); @ini_set('hard_timeout', '30'); @ini_set('default_socket_timeout', '300'); // Verify nonce for AJAX requests if (defined('DOING_AJAX') && DOING_AJAX) { if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aiautotool_nonce')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Security check failed. Please refresh the page and try again.'); $stream->close(); return; } if (!current_user_can('edit_posts')) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Permission denied'); $stream->close(); return; } } // Get data from POST $data = array(); if (isset($_POST['data']) && is_string($_POST['data'])) { $data = json_decode(stripslashes($_POST['data']), true); } else { $raw_data = file_get_contents('php://input'); $data = json_decode($raw_data, true); } if (!$data || !is_array($data)) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Invalid JSON data'); $stream->close(); return; } // Extract parameters $title = isset($data['title']) ? sanitize_text_field($data['title']) : ''; $lang = isset($data['lang']) ? sanitize_text_field($data['lang']) : 'vi'; $message_id = isset($data['message_id']) ? sanitize_text_field($data['message_id']) : ''; $resolved_ai_selection = $this->aiautotool_resolve_provider_model_selection( isset($data['model']) ? $data['model'] : '', isset($data['provider_id']) ? $data['provider_id'] : '' ); $requested_provider_id = $resolved_ai_selection['provider_id']; $requested_model = $resolved_ai_selection['model']; $article_settings = (isset($data['article_settings']) && is_array($data['article_settings'])) ? $data['article_settings'] : array(); $execution_mode = isset($data['execution_mode']) ? sanitize_key($data['execution_mode']) : get_option('aiautotool_ai_execution_mode', 'agent'); $execution_mode = in_array($execution_mode, array('agent', 'direct_api'), true) ? $execution_mode : 'agent'; if (empty($title)) { require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('Title parameter is required'); $stream->close(); return; } // Load SSE Stream class $sse_stream_path = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/aiautotool-sse-stream.php'; if (!file_exists($sse_stream_path)) { // Try alternative path $sse_stream_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/lib/aiautotool-sse-stream.php'; } if (!file_exists($sse_stream_path)) { wp_die('SSE Stream class not found'); } require_once $sse_stream_path; // Load AI Auto Writer $auto_writer_path = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_auto_writer.php'; if (!file_exists($auto_writer_path)) { // Try alternative path $auto_writer_path = dirname(dirname(dirname(dirname(__FILE__)))) . '/inc/ai-providers/aiautotool_ai_auto_writer.php'; } if (!file_exists($auto_writer_path)) { $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('AI Auto Writer class not found at: ' . $auto_writer_path); $stream->close(); return; } require_once $auto_writer_path; // Check if class exists if (!class_exists('AIAutotool_AI_Auto_Writer')) { $stream = new AIAutoTool_SSE_Stream(); $stream->start(); $stream->send_error('AI Auto Writer class not loaded'); $stream->close(); return; } // Initialize stream $stream = new AIAutoTool_SSE_Stream(); $stream->start(); if (!empty($message_id)) { $stream->set_message_id($message_id); } // Get auto writer instance try { $auto_writer = AIAutotool_AI_Auto_Writer::get_instance(); } catch (Exception $e) { $stream->send_error('Failed to get AI Auto Writer instance: ' . $e->getMessage()); $stream->close(); return; } // Load AI Provider Manager to check available providers require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_provider_manager.php'; require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_provider_api_keys.php'; $provider_manager = AIAutotool_AI_Provider_Manager::get_instance(); $provider_manager->refresh_providers(); $routing_mode = method_exists($provider_manager, 'get_provider_routing_mode') ? $provider_manager->get_provider_routing_mode() : 'single'; $route = false; if (!empty($requested_provider_id)) { $requested_provider = $provider_manager->get_provider($requested_provider_id); if (!$requested_provider || !$requested_provider->is_configured()) { $stream->send_error('Selected AI provider is not configured. Please choose another provider or update AI Provider settings.'); $stream->close(); return; } $available_models = $requested_provider->get_available_models(); if (empty($requested_model) || !isset($available_models[$requested_model])) { $requested_model = $requested_provider->get_default_model(); } $route = array( 'provider' => $requested_provider, 'provider_id' => $requested_provider_id, 'model' => $requested_model, 'routing_mode' => 'editor_override', ); } else { $route = method_exists($provider_manager, 'get_provider_for_request') ? $provider_manager->get_provider_for_request() : false; } $active_provider = $provider_manager->get_active_provider(); $active_provider_id = $active_provider ? $active_provider->get_id() : ''; $active_model = $provider_manager->get_active_model(); if ($active_provider && empty($active_model)) { $active_model = $active_provider->get_default_model(); } // Active or routed provider from AI Provider settings must be tried first. $providers_to_try = array(); if ($route && !empty($route['provider_id'])) { $providers_to_try[] = array( 'provider' => $route['provider_id'], 'model' => !empty($route['model']) ? $route['model'] : $route['provider']->get_default_model(), 'source' => !empty($requested_provider_id) ? 'editor' : ($routing_mode === 'rotate' ? 'rotate' : 'active'), ); } elseif ($active_provider) { $providers_to_try[] = array( 'provider' => $active_provider_id, 'model' => $active_model ? $active_model : $active_provider->get_default_model(), 'source' => 'active', ); } // Fallback providers are only used in rotate mode. In single/editor mode, // respect the user's explicit provider choice and fail fast if it cannot complete. if ($routing_mode === 'rotate' && empty($requested_provider_id)) { $fallback_priority = method_exists($provider_manager, 'get_provider_priority') ? $provider_manager->get_provider_priority() : array( 'pollinations', 'llm7', 'gemini', 'groq', 'openrouter', 'huggingface', 'deepseek', 'mistral', 'together', 'fireworks', 'perplexity', 'xai', 'anthropic', 'openai', 'azure_openai', 'ollama', ); foreach ($fallback_priority as $provider_id) { if (!empty($providers_to_try[0]['provider']) && $provider_id === $providers_to_try[0]['provider']) { continue; } $provider = $provider_manager->get_provider($provider_id); if (!$provider || !$provider->is_configured()) { continue; } $providers_to_try[] = array( 'provider' => $provider_id, 'model' => $provider->get_default_model(), 'source' => 'fallback', ); } } if (empty($providers_to_try)) { $stream->send_error('No AI provider is configured. Please add an API key and select an active provider in AI Provider settings.'); $stream->close(); return; } // Prepare base options $base_options = array( 'language' => $lang === 'vi' || $lang === 'Vietnamese' ? 'vi' : 'en', 'industry' => 'auto', 'min_sections' => 5, 'max_sections' => 10, 'words_per_section' => 300, 'include_intro' => true, 'include_conclusion' => true, 'detailed_level' => 'high', 'max_retries' => 1, 'retry_delay' => 0, 'suppress_internal_errors' => true, 'debug' => false, ); if (!empty($article_settings['tone'])) { $base_options['tone'] = sanitize_text_field($article_settings['tone']); } if (!empty($article_settings['targetAudience'])) { $base_options['target_audience'] = sanitize_text_field($article_settings['targetAudience']); } if (!empty($article_settings['lengthType'])) { $length_type = sanitize_text_field($article_settings['lengthType']); if ($length_type === 'short') { $base_options['min_sections'] = 3; $base_options['max_sections'] = 5; $base_options['words_per_section'] = 220; $base_options['detailed_level'] = 'medium'; } elseif ($length_type === 'standard') { $base_options['min_sections'] = 4; $base_options['max_sections'] = 7; $base_options['words_per_section'] = 300; $base_options['detailed_level'] = 'high'; } elseif ($length_type === 'long') { $base_options['min_sections'] = 6; $base_options['max_sections'] = 10; $base_options['words_per_section'] = 450; $base_options['detailed_level'] = 'high'; } } if ($execution_mode === 'agent') { $agent_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'inc/ai-providers/aiautotool_ai_agent.php'; if (!class_exists('AIAutotool_AI_Agent') && file_exists($agent_file)) { require_once $agent_file; } if (!class_exists('AIAutotool_AI_Agent')) { $stream->send_error('AI Agent class not loaded. Please refresh the page and try again.'); $stream->close(); return; } $agent_provider_config = $providers_to_try[0]; $agent_options = array_merge($base_options, array( 'provider' => $agent_provider_config['provider'], 'model' => $agent_provider_config['model'], 'execution_mode' => 'agent', 'skip_clarification' => true, )); $stream->send_status("AI Agent workflow đang xử lý với provider: {$agent_provider_config['provider']} - {$agent_provider_config['model']}..."); try { $agent = AIAutotool_AI_Agent::get_instance(); $agent->execute_with_stream($title, $stream, $agent_options, $title); } catch (Exception $e) { $stream->send_error('AI Agent Error: ' . $e->getMessage()); } $stream->close(); return; } // Try each provider until one succeeds $result = null; $last_error = ''; $attempted_providers = array(); $provider_errors = array(); foreach ($providers_to_try as $provider_config) { $attempted_providers[] = $provider_config['provider'] . '/' . $provider_config['model']; if ($provider_config['source'] === 'rotate') { $try_label = 'provider xoay vòng'; } elseif ($provider_config['source'] === 'editor') { $try_label = 'provider chọn trong bài viết'; } else { $try_label = $provider_config['source'] === 'active' ? 'provider đã chọn' : 'provider dự phòng'; } $stream->send_status("Đang thử với {$try_label}: {$provider_config['provider']} - {$provider_config['model']}..."); // Merge provider/model into options $options = array_merge($base_options, array( 'provider' => $provider_config['provider'], 'model' => $provider_config['model'] )); // Call auto writer with streaming try { $result = $auto_writer->write_article_from_title_with_stream($title, $stream, $options); if ($result && isset($result['success']) && $result['success']) { // Success! Send complete event $stream->send_complete($result['full_content'], array( 'title' => isset($result['title']) ? $result['title'] : $title, 'word_count' => isset($result['word_count']) ? $result['word_count'] : 0, 'execution_time' => isset($result['execution_time']) ? $result['execution_time'] : 0, 'provider' => $provider_config['provider'], 'model' => $provider_config['model'] )); $stream->close(); return; // Exit successfully } else { $error = isset($result['error']) ? $result['error'] : 'Failed to write article'; $last_error = $error; $provider_errors[] = $provider_config['provider'] . ': ' . $error; if ($this->aiautotool_is_provider_retryable_error($error)) { $stream->send_status("Provider {$provider_config['provider']} failed: " . substr($error, 0, 100) . "... Đang thử provider khác..."); continue; // Try next provider } else { // Other error, might be fatal break; } } } catch (Exception $e) { error_log('AI Auto Writer Error with ' . $provider_config['provider'] . ': ' . $e->getMessage()); $last_error = $e->getMessage(); $provider_errors[] = $provider_config['provider'] . ': ' . $e->getMessage(); if ($this->aiautotool_is_provider_retryable_error($e->getMessage())) { $stream->send_status("Provider {$provider_config['provider']} error: " . substr($e->getMessage(), 0, 100) . "... Đang thử provider khác..."); continue; // Try next provider } else { // Other error, might be fatal break; } } catch (Error $e) { error_log('AI Auto Writer Fatal Error with ' . $provider_config['provider'] . ': ' . $e->getMessage()); $last_error = $e->getMessage(); break; // Fatal error, stop trying } } // All providers failed if (empty($last_error)) { $last_error = 'Tất cả providers đều thất bại. Vui lòng kiểm tra API keys trong Settings.'; } elseif (!empty($provider_errors)) { if ($routing_mode === 'rotate' && empty($requested_provider_id)) { $last_error = 'Tất cả AI providers đã thử đều chưa tạo được bài hoàn chỉnh. Đã thử: ' . implode(', ', $attempted_providers) . '. Lỗi cuối: ' . $last_error; } else { $last_error = 'Provider đã chọn chưa tạo được bài hoàn chỉnh. Đã thử: ' . implode(', ', $attempted_providers) . '. Lỗi: ' . $last_error; } } $stream->send_error($last_error); // Close stream $stream->close(); } } // End of AIAutoToolsinglepost class } // End of class_exists check