'; 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); ?>
); ?>)
); ?>)
); ?>)
' . $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('/' . 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', '
', $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(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)' : '') . '
' . nl2br(esc_html($error_message)) . '
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:
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\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 = '' . 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 
$html = preg_replace('/!\[([^\]]*)\]\(([^)]+)\)/', '$1', $html); // Convert unordered lists (- item or * item) $html = preg_replace('/^[\-\*]\s+(.+)$/m', '
', $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 = "
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:
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\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 = '