'; protected $postfields = array(); protected $shortcodes = array(); protected $htmltags = array(); public $limit = AIAUTOTOOL_FREE; private $plan_limit_aiautotool ; public $name_plan ; public $config = array(); public $notice ; public function __construct() { // Prevent multiple initialization of hooks and actions // Check if this instance's class has already been initialized $class_name = get_class($this); // If already initialized, skip hook registration if (self::$initialized) { // Still set basic properties for this instance $this->name_plan = esc_html__('Autoblogging AI','ai-auto-tool'); $this->active_option_name = 'AI_AutoTool_Autoblogging_active'; if (class_exists('AIAutoTool_FeatureOptions')) { $this->active = AIAutoTool_FeatureOptions::get_option($this->active_option_name, 'false'); } else { $normalized_name = (strpos($this->active_option_name, 'aiautotool_') !== 0) ? 'aiautotool_' . $this->active_option_name : $this->active_option_name; $this->active = get_option($normalized_name, 'false'); } return; } // Mark as initialized self::$initialized = true; // Store instance in global variable for standalone functions global $aiautotool_scan_instance; $aiautotool_scan_instance = $this; $this->name_plan = esc_html__('Autoblogging AI','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 'false' if not exists (default inactive) // Use FeatureOptions to get the option (normalizes the option name) if (class_exists('AIAutoTool_FeatureOptions')) { $active_option = AIAutoTool_FeatureOptions::get_option($this->active_option_name, 'false'); if ($active_option === 'false' || $active_option === false) { // Option doesn't exist or is false, ensure it's set to 'false' (default inactive) AIAutoTool_FeatureOptions::set_option($this->active_option_name, 'false'); $this->active = 'false'; } else { $this->active = $active_option; } } else { // Fallback: check both normalized and non-normalized option names for backward compatibility $normalized_name = (strpos($this->active_option_name, 'aiautotool_') !== 0) ? 'aiautotool_' . $this->active_option_name : $this->active_option_name; $active_option = get_option($normalized_name, false); if ($active_option === false) { // Also check the old non-normalized name $active_option = get_option($this->active_option_name, false); } if ($active_option === false) { // Option doesn't exist, set it to 'false' to default inactive (use normalized name) update_option($normalized_name, 'false'); $this->active = 'false'; } else { $this->active = $active_option; // Migrate to normalized name if using old name if (get_option($normalized_name) === false && get_option($this->active_option_name) !== false) { update_option($normalized_name, $active_option); } } } // Only run init logic if active if ($this->active === 'true' || $this->active === true) { $this->init(); } // Register AJAX handler only once add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback')); add_action('wp_ajax_add_post', array($this, 'add_post_callback')); } private function aiautotool_has_plugin_data() { return get_option($this->plan_limit_aiautotool) !== false; } private function aiautotool_initialize_plugin_data() { $current_date = date('Y-m-d'); $expiration = strtotime('+1 month', strtotime($current_date)); $expiration = date('Y-m-d', $expiration); update_option($this->plan_limit_aiautotool, array( 'start_date' => $current_date,'expiration'=>$expiration)); } public function aiautotool_check_post_limit() { $stored_data = get_option($this->plan_limit_aiautotool, array()); $current_date = date('Y-m-d'); if ($this->is_new_month($current_date, $stored_data['start_date'])) { $expiration = strtotime('+1 month', strtotime($current_date)); $expiration = date('Y-m-d', $expiration); update_option($this->plan_limit_aiautotool, array( 'start_date' => $current_date,'expiration'=>$expiration)); update_option($this->usage_option_name, 0,null, 'no'); } } private function is_new_month($current_date, $start_date) { $current_month = date('m', strtotime($current_date)); $start_month = date('m', strtotime($start_date)); return ($current_month != $start_month); } public function aiautotool_checklimit($config) { return self::check_quota(); } public function aiautotool_update_usage() { $this->aiautotool_check_post_limit(); $current_value = get_option($this->usage_option_name, 0); $new_value = $current_value + 1; if($this->config['number_post']!=-1){ if($this->config['number_post'] > $new_value){ update_option($this->usage_option_name, $new_value, 'no'); } }else{ update_option($this->usage_option_name, $new_value, 'no'); } return $new_value; } public function render_plan(){ if ($this->active=='true') { $quota = $this->config['number_post'] == -1 ? 'Unlimited' : esc_html($this->config['number_post']); echo wp_kses( '
' . $this->icon . ' ' . esc_html($this->name_plan) . ': Usage: ' . esc_html($this->config['usage']) . '
', [ 'p' => [], 'i' => ['class' => []], 'strong' => [], ] ); } } public function update_active_option_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403)); } if (isset($_POST['active'])) { $active = sanitize_text_field($_POST['active']); // Use FeatureOptions if available to normalize option name if (class_exists('AIAutoTool_FeatureOptions')) { AIAutoTool_FeatureOptions::set_option($this->active_option_name, $active); } else { // Fallback: ensure option name starts with aiautotool_ if it doesn't $normalized_name = (strpos($this->active_option_name, 'aiautotool_') !== 0) ? 'aiautotool_' . $this->active_option_name : $this->active_option_name; update_option($normalized_name, $active, null, 'no'); } print_r($active); } wp_die(); } public function init(){ // Add admin menu and scripts add_action('admin_menu', array($this, 'add_menu')); add_action('admin_init', array($this, 'aiautotool_check_post_limit')); add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts')); // IMPORTANT: Register cron schedules early, before any cron events are scheduled // This must be done regardless of checklimit to prevent "Event schedule does not exist" errors add_filter('cron_schedules', array($this, 'aiautotool_schedule_cron_intervals')); add_filter('cron_schedules', array($this, 'schedule_create_content')); // Register cron action hooks early add_action('aiautotool_autoblogging_publish_draft_posts', array($this, 'autoblogging_cron_publish_draft_posts')); add_action('aiautotool_autoblogging_generate_content_for_draft', array($this, 'autoblogging_cron_generate_content_for_draft')); // Initialize configs $configs = get_option($this->plan_limit_aiautotool, array()); if (!$this->aiautotool_has_plugin_data()) { $this->aiautotool_initialize_plugin_data(); $configs = (array) $this->aiautotool_has_plugin_data(); } if(!isset($configs['expiration'])) { $current_date = date('Y-m-d'); $expiration = strtotime('+1 month', strtotime($current_date)); $configs['expiration'] = date('Y-m-d', $expiration); } $this->config = array( 'number_post'=>$this->limit, 'usage'=>get_option($this->usage_option_name, 0, 'no'), 'time_exprice'=>$configs['expiration'] ); 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; $expiration = (is_object($license) && isset($license->expiration)) ? $license->expiration : $configs['expiration']; $this->config = array( 'number_post'=>-1, 'usage'=>get_option($this->usage_option_name, 0, 'no'), 'time_exprice'=>$expiration ); } if ($this->aiautotool_checklimit($this->config)) { // Schedule cron events only if limit check passes if (!wp_next_scheduled('aiautotool_autoblogging_publish_draft_posts')) { wp_schedule_event(time(), 'aiautotool_schedule_cron_intervals', 'aiautotool_autoblogging_publish_draft_posts'); } if (!wp_next_scheduled('aiautotool_autoblogging_generate_content_for_draft')) { wp_schedule_event(time(), 'schedule_create_content', 'aiautotool_autoblogging_generate_content_for_draft'); } }else{ $this->notice->add_notice( AIAUTOTOOL_TITLE_UPGRADE, 'notice-error', null, true, 'aiautotool' ); } add_action('wp_ajax_add_post', array($this, 'add_post_callback')); add_action('rest_api_init', array($this, 'register_aiautotool_scan_route')); // Flush rewrite rules if endpoint registration version changed $this->maybe_flush_rewrite_rules(); add_action('wp_ajax_clear_log_action', array($this, 'clear_log_action_callback')); add_action('url_scanner_clear_log_cron', array($this, 'clear_log_action_callback')); if (!wp_next_scheduled('url_scanner_clear_log_cron')) { wp_schedule_event(time(), 'twicedaily', 'url_scanner_clear_log_cron'); } add_action('wp_ajax_aiautotool_idea_title_post', array($this, 'aiautotool_idea_title_post')); add_action('wp_ajax_run_autoblogging_cron', array($this, 'run_autoblogging_cron_callback')); } public function render_setting() { ?> '; } $current_interval = get_option('aiautotool_draft_public_time', 5); $number_post = get_option('aiautotool_draft_public_number_post', 1); $aiautotool_draft_public_turnoff_auto_images = get_option('aiautotool_draft_public_turnoff_auto_images', false); $default_language = get_option('aiautotool_default_language', 'vi'); $autoblogging_model = get_option('aiautotool_autoblogging_model', ''); $languages = $this->languageCodes; ?>/', $content, $matches, PREG_OFFSET_CAPTURE);
$total_paragraphs = count($matches[0]);
$random_position = mt_rand(2, $total_paragraphs - 1);
if (isset($matches[0][$random_position])) {
$paragraph_pos = $matches[0][$random_position][1] + strlen($matches[0][$random_position][0]);
$content = substr($content, 0, $paragraph_pos) . $text . substr($content, $paragraph_pos);
}
return $content;
}
private function process_post_content($post_id, $title, $lang, $auto_generate_title, $log){
}
/**
* Generate tags for a post using AI based on post content
*
* @param int $post_id Post ID
* @param string $title Post title
* @param string $content Post content
* @param string $lang Language
* @return bool True if tags were generated successfully
*/
private function generate_tags_for_post($post_id, $title, $content, $lang = 'Vietnamese') {
// Check if AI Helper is available
if (!class_exists('AIAutotool_AI_Helper')) {
return false;
}
if (!AIAutotool_AI_Helper::is_available()) {
return false;
}
// Prepare content excerpt for prompt (limit to avoid token limits)
$content_excerpt = wp_trim_words(strip_tags($content), 200);
// Build prompt for tag generation
$prompt = "Based on the following blog post, generate 5-8 relevant tags (keywords) that best describe the content. ";
$prompt .= "Tags should be SEO-friendly, specific, and relevant to the post topic.\n\n";
$prompt .= "Post Title: {$title}\n\n";
$prompt .= "Post Content:\n{$content_excerpt}\n\n";
$prompt .= "Generate tags as a comma-separated list. Only return the tags, no explanations. ";
$prompt .= "Write tags in {$lang} language if applicable, or use English for technical terms.";
// Generate tags using AI
$result = AIAutotool_AI_Helper::generate($prompt, array(
'temperature' => 0.7,
'max_tokens' => 200
));
if (!$result['success'] || empty($result['content'])) {
return false;
}
// Extract tags from AI response
$ai_tags = trim($result['content']);
// Clean up the response - remove any extra text, keep only tags
// Remove common prefixes like "Tags:", "Keywords:", etc.
$ai_tags = preg_replace('/^(tags?|keywords?|labels?)[:\s]*/i', '', $ai_tags);
$ai_tags = preg_replace('/\n.*$/s', '', $ai_tags); // Remove everything after first line
$ai_tags = trim($ai_tags, " \n\r\t.,;");
// Split by comma and clean each tag
$tags_array = array_map('trim', explode(',', $ai_tags));
$tags_array = array_filter($tags_array, function($tag) {
return !empty($tag) && strlen($tag) > 1;
});
// Limit to 8 tags max
$tags_array = array_slice($tags_array, 0, 8);
if (empty($tags_array)) {
return false;
}
// Set tags for the post
wp_set_post_tags($post_id, $tags_array, false);
return true;
}
/**
* Cron job: Publish draft posts with content (Legacy method)
* This is the legacy version that uses transient for draft posts list
*/
public function autoblogging_cron_publish_draft_posts_legacy() {
// Ensure textdomain is loaded (important for cron jobs)
// Only load if 'init' action has fired (WordPress 6.7.0+ requirement)
if (!is_textdomain_loaded('ai-auto-tool') || !is_textdomain_loaded('aiautotool-cron-widget')) {
if (did_action('init')) {
if (function_exists('aiautotool_load_textdomain')) {
aiautotool_load_textdomain();
}
}
}
// Load required classes
if (!class_exists('BardGenContent')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
}
if (!class_exists('Imagescontent')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/imageinsert.php';
}
if (!class_exists('AIautoTool_log')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/AIautotool_logall.php';
}
$log = new AIautoTool_log();
set_time_limit(300);
$draft_posts = get_transient('aiautotool_draft_posts_public');
if (false === $draft_posts) {
$number_post = get_option('aiautotool_draft_public_number_post', 500);
$args = array(
'post_type' => 'post',
'post_status' => 'draft',
'posts_per_page' => $number_post,
);
$draft_posts_query = new WP_Query($args);
if ($draft_posts_query->have_posts()) {
$draft_posts = array();
while ($draft_posts_query->have_posts()) {
$draft_posts_query->the_post();
$draft_posts[] = get_the_ID();
}
set_transient('aiautotool_draft_posts_public', $draft_posts, 24 * HOUR_IN_SECONDS);
} else {
return;
}
}
$post_id = array_shift($draft_posts);
if (!$post_id) {
delete_transient('aiautotool_draft_posts_public');
return;
}
$content_post = get_post($post_id);
$current_content = $content_post->post_content;
if (strlen($current_content) < 255) {
if($this->aiautotool_checklimit($this->config)){
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'star run bard api'));
$auto_generate_title = 0;//get_post_meta($post_id, 'auto_generate_title', false);
$aiautotool_prompt = get_post_meta($post_id, 'aiautotool_prompt', true);
$lang = get_post_meta($post_id, 'lang', 'Vietnamese');
// Use default language if post doesn't have language set
if (empty($lang) || $lang === 'Vietnamese') {
$default_language = get_option('aiautotool_default_language', 'vi');
$lang = $this->languageCodes[$default_language] ?? 'Vietnamese';
}
$aiautotool_linkin = get_post_meta($post_id, 'aiautotool_linkin', true);
$bardGenContent = new BardGenContent();
$Imagescontent = new Imagescontent();
$title = self::fix_years(get_the_title($post_id));
// Get prompt_mode for this post
$prompt_mode = get_post_meta($post_id, 'prompt_selection_mode', true);
if (empty($prompt_mode)) {
$prompt_mode = 'single'; // Default to single if not set
}
$allprompt = get_option('aiautotool_prompt_options',array());
$auto = true;
// If prompt_mode is 'auto', always use auto mode
if ($prompt_mode === 'auto') {
$auto = true;
} else if(empty($allprompt)){
$auto = true;
}else{
if($aiautotool_prompt==''){
if(isset($allprompt['aiautotool_prompt_artcile']))
{
$artcle_prompt = $allprompt['aiautotool_prompt_artcile'];
}
}else{
$artcle_prompt = $aiautotool_prompt;
}
$content='';
$cate = '';
$blogtitle = '';
$prompt = $this->aiautotool_fix_question($artcle_prompt,$title,$lang,$blogtitle,$cate,$content);
$auto = false;
}
// Get selected provider/model from AI Provider settings.
$selected_model = get_option('aiautotool_autoblogging_model', '');
// Get provider_id from settings if available
$provider_id = '';
if (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($auto){
// Use new article generation function with full analysis (same as manual writing)
$newcontent = $this->generate_article_from_title($title, $lang, $selected_model, $provider_id);
// If generation failed, fallback to old method
if ($newcontent === false || empty($newcontent)) {
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$newcontent = $bardGenContent->bardcontentfull($title, $lang, $selected_model);
}
}else{
$newcontent = $bardGenContent->bardcontentmore($prompt,$lang, $selected_model);
}
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content by bard api'));
if (!empty($newcontent)) {
$listimg = false;
if (!$this->is_auto_image_disabled()) {
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content by bard api success next step search img'));
$listimg = $bardGenContent->searchimg($title);
} else {
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'auto image disabled, skip image search'));
}
$current_content = apply_filters('the_content', $current_content);
$current_content = str_replace(']]>', ']]>', $current_content);
$current_content = preg_replace('#]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
$listimg1 = $matches[1];
$imgUploaded = array();
$attachThumbnail = 0;
if (!empty($listimg1)){
foreach ($listimg1 as $post_image_url){
try {
$image_url_new = $this->kct_aiautotool_save_image($post_image_url,$postname);
if (!empty($image_url_new)){
$imgUploaded[] = $image_url_new;
if ($attachThumbnail == 0) {
$attachThumbnail = $image_url_new['attach_id'];
}
}
}catch (Exception $e) {
}
}
}
foreach ($imgUploaded as $img){
$updated_content = str_replace($img['url'],$img['baseurl'],$updated_content);
}
if($auto_generate_title!=0){
$title = $bardGenContent->gentitle($title,$lang);
}
// Set thumbnail: use existing or generate AI thumbnail
// Wrap in try-catch to prevent errors from blocking post publish
try {
if ($attachThumbnail ) {
set_post_thumbnail($post_id, $attachThumbnail);
} elseif (!$this->is_auto_image_disabled()) {
// Generate AI thumbnail using Pollinations if no thumbnail exists
// Let the generator fetch content from post_id automatically
$ai_thumbnail_id = AIAutoTool_Thumbnail_Generator::generate_thumbnail($post_id, $title, '');
if ($ai_thumbnail_id) {
set_post_thumbnail($post_id, $ai_thumbnail_id);
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
}
} catch (Exception $e) {
// Log error but don't block post publishing
$log->set_log('schedule_publish',array(
'post_id'=>$post_id,
'post_title'=>get_the_title(),
'msg'=>'Thumbnail generation error: ' . $e->getMessage()
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
$post_data = array(
'ID' => $post_id,
'post_title'=>$title,
'post_content' => $updated_content,
'post_status'=>'draft'
);
$post_id = wp_update_post($post_data);
$this->update_and_publish_post( $post_id );
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Publish post '.get_the_title()));
$this->aiautotool_update_usage();
}else{
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content Error 1 '.$title));
}
}else{
$this->notice->add_notice(
AIAUTOTOOL_TITLE_UPGRADE,
'notice-error',
null,
true,
$this->name_plan
);
}
set_transient('aiautotool_draft_posts_public', $draft_posts, 24 * HOUR_IN_SECONDS);
} else {
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'star run bard api and next step: publish post has content post.'));
$result = $this->update_and_publish_post( $post_id );
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Publish post '.get_the_title()));
}
wp_reset_postdata();
}
/**
* Cron job: Publish draft posts that have content
* This function finds draft posts with content and publishes them automatically
*/
public function autoblogging_cron_publish_draft_posts() {
// Ensure textdomain is loaded (important for cron jobs)
// Only load if 'init' action has fired (WordPress 6.7.0+ requirement)
if (!is_textdomain_loaded('ai-auto-tool') || !is_textdomain_loaded('aiautotool-cron-widget')) {
if (did_action('init')) {
if (function_exists('aiautotool_load_textdomain')) {
aiautotool_load_textdomain();
}
}
}
// Load required classes
if (!class_exists('BardGenContent')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
}
if (!class_exists('Imagescontent')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/imageinsert.php';
}
if (!class_exists('AIautoTool_log')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/AIautotool_logall.php';
}
set_time_limit(300);
$log = new AIautoTool_log();
$cron_widget = $this->get_cron_widget();
// Debug: Start cron task
$log->set_log('cron_task_debug', array(
'step' => 'START',
'msg' => 'Cron task bắt đầu chạy',
'timestamp' => current_time('mysql')
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
// Update cron status - starting publish task
$this->update_cron_progress($cron_widget, __('Searching for posts to publish...', 'aiautotool-cron-widget'), '', 10);
$number_post = get_option('aiautotool_draft_public_number_post', 1);
$args = array(
'post_type' => 'post',
'post_status' => 'draft',
'posts_per_page' => $number_post,
);
$draft_posts = new WP_Query($args);
// Debug: Found posts
$log->set_log('cron_task_debug', array(
'step' => 'FIND_POSTS',
'msg' => 'Tìm thấy ' . $draft_posts->found_posts . ' bài viết draft',
'posts_count' => $draft_posts->found_posts,
'posts_per_page' => $number_post
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
if ($draft_posts->have_posts()) {
$post_index = 0;
while ($draft_posts->have_posts()) {
$draft_posts->the_post();
$post_id = get_the_ID();
$post_index++;
$post_title = get_the_title($post_id);
$content_post = get_post($post_id);
$current_content = $content_post->post_content;
// Debug: Start processing post
$log->set_log('cron_task_debug', array(
'step' => 'PROCESS_POST',
'post_id' => $post_id,
'post_title' => $post_title,
'post_index' => $post_index,
'total_posts' => $draft_posts->found_posts,
'current_content_length' => strlen($current_content),
'msg' => "Bắt đầu xử lý bài viết #{$post_index}: {$post_title} (ID: {$post_id})"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
if(strlen($current_content) < 255){
if($this->aiautotool_checklimit($this->config)){
// Initialize variables before using them
$auto_generate_title = 0;
$aiautotool_prompt = get_post_meta($post_id, 'aiautotool_prompt', true);
$lang = get_post_meta($post_id, 'lang', 'Vietnamese');
if (empty($lang) || $lang === 'Vietnamese') {
$default_language = get_option('aiautotool_default_language', 'vi');
$lang = $this->languageCodes[$default_language] ?? 'Vietnamese';
}
$aiautotool_linkin = get_post_meta($post_id, 'aiautotool_linkin', true);
$bardGenContent = new BardGenContent();
$Imagescontent = new Imagescontent();
$title = self::fix_years(get_the_title($post_id));
// Get prompt_mode for this post
$prompt_mode = get_post_meta($post_id, 'prompt_selection_mode', true);
if (empty($prompt_mode)) {
$prompt_mode = 'single'; // Default to single if not set
}
$allprompt = get_option('aiautotool_prompt_options',array());
$auto = true;
// If prompt_mode is 'auto', always use auto mode
if ($prompt_mode === 'auto') {
$auto = true;
} else if(empty($allprompt)){
$auto = true;
}else{
if($aiautotool_prompt==''){
if(isset($allprompt['aiautotool_prompt_artcile']))
{
$artcle_prompt = $allprompt['aiautotool_prompt_artcile'];
}
}else{
$artcle_prompt = $aiautotool_prompt;
}
$artcle_prompt = str_replace('%%title%%',$title,$artcle_prompt);
$content='';
$cate = '';
$blogtitle = '';
$prompt = $this->aiautotool_fix_question($artcle_prompt,$title,$lang,$blogtitle,$cate,$content);
$auto = false;
}
// Get selected provider/model from AI Provider settings.
$selected_model = get_option('aiautotool_autoblogging_model', '');
// Debug: Content generation type
$content_gen_type = $auto ? 'AUTO' : 'MANUAL_PROMPT';
$log->set_log('cron_task_debug', array(
'step' => 'CONTENT_GEN_TYPE',
'post_id' => $post_id,
'post_title' => $title,
'content_gen_type' => $content_gen_type,
'prompt_mode' => $prompt_mode,
'selected_model' => $selected_model,
'language' => $lang,
'msg' => "Loại gen content: {$content_gen_type} | Model: {$selected_model} | Ngôn ngữ: {$lang}"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
if (!$auto) {
}
}
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'star run bard api'));
// Update status - found post to process
$this->update_cron_progress($cron_widget, __('Creating content for post to publish...', 'aiautotool-cron-widget'), get_the_title($post_id), 20);
// Update status - calling AI
$this->update_cron_progress($cron_widget, __('Calling AI to generate content...', 'aiautotool-cron-widget'), $title, 40);
// Get provider_id from settings if available
$provider_id = '';
if (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();
}
}
// Debug: Before calling AI
$log->set_log('cron_task_debug', array(
'step' => 'CALLING_AI',
'post_id' => $post_id,
'post_title' => $title,
'content_gen_type' => $content_gen_type,
'msg' => "Đang gọi AI để gen content..."
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
if($auto){
// Use new article generation function with full analysis (same as manual writing)
$log->set_log('cron_task_debug', array(
'step' => 'AI_GENERATE_AUTO',
'post_id' => $post_id,
'post_title' => $title,
'method' => 'generate_article_from_title',
'msg' => "Sử dụng phương thức AUTO: generate_article_from_title"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$newcontent = $this->generate_article_from_title($title, $lang, $selected_model, $provider_id);
// If generation failed, fallback to old method
if ($newcontent === false || empty($newcontent)) {
$log->set_log('cron_task_debug', array(
'step' => 'AI_FALLBACK',
'post_id' => $post_id,
'post_title' => $title,
'method' => 'bardcontentfull',
'msg' => "AUTO generation failed, fallback sang bardcontentfull"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$this->update_cron_progress($cron_widget, __('Trying alternative method...', 'aiautotool-cron-widget'), $title, 45);
$newcontent = $bardGenContent->bardcontentfull($title, $lang, $selected_model);
}
}else{
$log->set_log('cron_task_debug', array(
'step' => 'AI_GENERATE_MANUAL',
'post_id' => $post_id,
'post_title' => $title,
'method' => 'bardcontentmore',
'msg' => "Sử dụng phương thức MANUAL: bardcontentmore với prompt"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$newcontent = $bardGenContent->bardcontentmore($prompt,$lang, $selected_model);
}
// Update progress after AI call completes
$this->update_cron_progress($cron_widget, __('Processing AI response...', 'aiautotool-cron-widget'), $title, 50);
// Debug: After AI response
$content_length = is_string($newcontent) ? strlen($newcontent) : 0;
$log->set_log('cron_task_debug', array(
'step' => 'AI_RESPONSE',
'post_id' => $post_id,
'post_title' => $title,
'content_length' => $content_length,
'is_array' => is_array($newcontent),
'msg' => "AI đã trả về response. Độ dài: {$content_length} ký tự"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
if (is_array($newcontent)) {
}
}
// $log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>$title,'msg'=>'Prompt with create contet post'.$prompt));
// Check if content is valid string (not array from API error)
if (is_array($newcontent)) {
$error_msg = isset($newcontent['msg']) ? $newcontent['msg'] : 'API returned error';
$error_code = isset($newcontent['code']) ? $newcontent['code'] : 'unknown';
$log->set_log('schedule_publish',array(
'post_id'=>$post_id,
'post_title'=>get_the_title(),
'msg'=>'API Error - Code: '.$error_code.', Message: '.$error_msg,
'response'=>$newcontent
));
$newcontent = ''; // Reset to empty string to prevent saving array
} else {
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content by bard api'));
// Update progress after content validation
$this->update_cron_progress($cron_widget, __('Content generated successfully', 'aiautotool-cron-widget'), $title, 55);
}
if (!empty($newcontent) && is_string($newcontent)) {
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content by bard api success next step search img'));
// Debug: Content created successfully
$log->set_log('cron_task_debug', array(
'step' => 'CONTENT_CREATED',
'post_id' => $post_id,
'post_title' => $title,
'content_length' => strlen($newcontent),
'msg' => "Content đã được tạo thành công. Bước tiếp theo: tìm ảnh"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$listimg = false;
if (!$this->is_auto_image_disabled()) {
// Update status - content created, finding images
$this->update_cron_progress($cron_widget, __('Searching for images...', 'aiautotool-cron-widget'), $title, 60);
$listimg = $bardGenContent->searchimg($title);
// Update progress after image search
$this->update_cron_progress($cron_widget, __('Images found, processing...', 'aiautotool-cron-widget'), $title, 65);
} else {
$this->update_cron_progress($cron_widget, __('Skipping image search...', 'aiautotool-cron-widget'), $title, 65);
}
// Debug: Image search result
$img_count = is_array($listimg) ? count($listimg) : 0;
$log->set_log('cron_task_debug', array(
'step' => 'SEARCH_IMAGES',
'post_id' => $post_id,
'post_title' => $title,
'images_found' => $img_count,
'msg' => "Tìm thấy {$img_count} ảnh"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
// $content_post = get_post($post_id);
// $current_content = $content_post->post_content;
$current_content = apply_filters('the_content', $current_content);
$current_content = str_replace(']]>', ']]>', $current_content);
$current_content = preg_replace('#
]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
$listimg1 = $matches[1];
// Debug: Images extracted from content
$extracted_img_count = count($listimg1);
$log->set_log('cron_task_debug', array(
'step' => 'EXTRACT_IMAGES',
'post_id' => $post_id,
'post_title' => $title,
'images_extracted' => $extracted_img_count,
'msg' => "Đã trích xuất {$extracted_img_count} ảnh từ content"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$imgUploaded = array();
$attachThumbnail = 0;
if (!empty($listimg1)){
$total_images = count($listimg1);
$upload_success = 0;
$upload_failed = 0;
foreach ($listimg1 as $img_index => $post_image_url){
$img_index_1 = $img_index + 1;
// Update progress during image upload loop
$upload_progress = 75 + (($img_index_1 / $total_images) * 5); // 75% to 80%
$this->update_cron_progress($cron_widget, sprintf(__('Uploading image %d/%d...', 'aiautotool-cron-widget'), $img_index_1, $total_images), $title, round($upload_progress));
try {
$image_url_new = $this->kct_aiautotool_save_image($post_image_url,$postname);
if (!empty($image_url_new)){
$imgUploaded[] = $image_url_new;
$upload_success++;
if ($attachThumbnail == 0) {
$attachThumbnail = $image_url_new['attach_id'];
}
} else {
$upload_failed++;
}
}catch (Exception $e) {
$upload_failed++;
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
}
// Debug: Image upload results
$log->set_log('cron_task_debug', array(
'step' => 'UPLOAD_IMAGES',
'post_id' => $post_id,
'post_title' => $title,
'upload_success' => $upload_success,
'upload_failed' => $upload_failed,
'thumbnail_id' => $attachThumbnail,
'msg' => "Upload ảnh: {$upload_success} thành công, {$upload_failed} thất bại"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
if ($attachThumbnail > 0) {
}
}
}
foreach ($imgUploaded as $img){
$updated_content = str_replace($img['url'],$img['baseurl'],$updated_content);
}
if($auto_generate_title!=0){
$title = $bardGenContent->gentitle($title,$lang);
}
// Set thumbnail: use existing or generate AI thumbnail
// Wrap in try-catch to prevent errors from blocking post publish
try {
if ($attachThumbnail != 0) {
set_post_thumbnail($post_id, $attachThumbnail);
} elseif (!$this->is_auto_image_disabled()) {
// Generate content excerpt for AI thumbnail
$content_excerpt = wp_trim_words(strip_tags($updated_content), 50);
// Generate AI thumbnail using Pollinations if no thumbnail exists
$ai_thumbnail_id = AIAutoTool_Thumbnail_Generator::generate_thumbnail($post_id, $title, $content_excerpt);
if ($ai_thumbnail_id) {
set_post_thumbnail($post_id, $ai_thumbnail_id);
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
}
} catch (Exception $e) {
// Log error but don't block post publishing
$log->set_log('schedule_publish',array(
'post_id'=>$post_id,
'post_title'=>get_the_title(),
'msg'=>'Thumbnail generation error: ' . $e->getMessage()
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
// Debug: Before publishing
$log->set_log('cron_task_debug', array(
'step' => 'BEFORE_PUBLISH',
'post_id' => $post_id,
'post_title' => $title,
'final_content_length' => strlen($updated_content),
'msg' => "Chuẩn bị publish bài viết. Độ dài content cuối: " . strlen($updated_content) . " ký tự"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
// Update status - publishing post
$this->update_cron_progress($cron_widget, __('Publishing post...', 'aiautotool-cron-widget'), $title, 90);
$post_data = array(
'ID' => $post_id,
'post_title'=>$title,
'post_content' => $updated_content,
'post_status'=>'draft'
);
$post_id = wp_update_post($post_data);
// Auto generate tags with AI if enabled
$auto_generate_tags = get_post_meta($post_id, 'auto_generate_tags', true);
if ($auto_generate_tags == 1) {
$log->set_log('cron_task_debug', array(
'step' => 'GENERATE_TAGS',
'post_id' => $post_id,
'post_title' => $title,
'msg' => "Đang tự động gen tags cho bài viết"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
try {
$this->generate_tags_for_post($post_id, $title, $updated_content, $lang);
$log->set_log('cron_task_debug', array(
'step' => 'GENERATE_TAGS_SUCCESS',
'post_id' => $post_id,
'post_title' => $title,
'msg' => "Gen tags thành công"
));
} catch (Exception $e) {
$log->set_log('schedule_publish', array(
'post_id' => $post_id,
'post_title' => get_the_title(),
'msg' => 'Auto generate tags error: ' . $e->getMessage()
));
$log->set_log('cron_task_debug', array(
'step' => 'GENERATE_TAGS_ERROR',
'post_id' => $post_id,
'post_title' => $title,
'error' => $e->getMessage(),
'msg' => "Lỗi khi gen tags: " . $e->getMessage()
));
}
}
$this->update_and_publish_post( $post_id );
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Publish post '.get_the_title()));
// Debug: Post published
$log->set_log('cron_task_debug', array(
'step' => 'POST_PUBLISHED',
'post_id' => $post_id,
'post_title' => $title,
'msg' => "Bài viết đã được publish thành công!"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$this->aiautotool_update_usage();
// Update status - completed
$this->update_cron_progress($cron_widget, __('Content creation completed', 'aiautotool-cron-widget'), $title, 100, __('Auto Content', 'aiautotool-cron-widget'), false);
// Debug: Post processing completed
$log->set_log('cron_task_debug', array(
'step' => 'POST_COMPLETED',
'post_id' => $post_id,
'post_title' => $title,
'post_index' => $post_index,
'msg' => "Hoàn thành xử lý bài viết #{$post_index}: {$title}"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}else{
// Debug: Content creation failed
$log->set_log('cron_task_debug', array(
'step' => 'CONTENT_CREATION_FAILED',
'post_id' => $post_id,
'post_title' => $title,
'content_gen_type' => $content_gen_type,
'msg' => "Lỗi: Không thể tạo content cho bài viết"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'create content Error 1 '.$title));
// Update status - error
$this->update_cron_progress($cron_widget, __('Error: Unable to create content', 'aiautotool-cron-widget'), $title, 100, __('Auto Content', 'aiautotool-cron-widget'), false);
}
}else{
// Debug: Quota exceeded
$log->set_log('cron_task_debug', array(
'step' => 'QUOTA_EXCEEDED',
'post_id' => $post_id,
'post_title' => $title,
'msg' => "Đã vượt quá giới hạn sử dụng, không thể xử lý bài viết"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$this->notice->add_notice(
AIAUTOTOOL_TITLE_UPGRADE,
'notice-error',
null,
true,
$this->name_plan
);
// Update status - quota exceeded
$this->update_cron_progress($cron_widget, __('Usage limit exceeded', 'aiautotool-cron-widget'), '', 100, __('Auto Content', 'aiautotool-cron-widget'), false);
}
}else{
// Debug: Post already has content
$log->set_log('cron_task_debug', array(
'step' => 'POST_HAS_CONTENT',
'post_id' => $post_id,
'post_title' => get_the_title($post_id),
'content_length' => strlen($current_content),
'msg' => "Bài viết đã có content đủ dài, chỉ cần publish"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'star run bard api and next step: publish post has content post.'));
// Update status - publishing existing content
$this->update_cron_progress($cron_widget, __('Publishing post with existing content...', 'aiautotool-cron-widget'), get_the_title($post_id), 90);
$result = $this->update_and_publish_post( $post_id );
$log->set_log('schedule_publish',array('post_id'=>$post_id,'post_title'=>get_the_title(),'msg'=>'Publish post '.get_the_title()));
// Debug: Post with existing content published
$log->set_log('cron_task_debug', array(
'step' => 'POST_PUBLISHED_EXISTING',
'post_id' => $post_id,
'post_title' => get_the_title($post_id),
'msg' => "Đã publish bài viết có sẵn content"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
// Update status - completed
$this->update_cron_progress($cron_widget, __('Post published successfully', 'aiautotool-cron-widget'), get_the_title($post_id), 100, __('Auto Content', 'aiautotool-cron-widget'), false);
}
}
// Debug: All posts processed
$log->set_log('cron_task_debug', array(
'step' => 'ALL_POSTS_PROCESSED',
'total_posts' => $draft_posts->found_posts,
'msg' => "Đã xử lý xong tất cả {$draft_posts->found_posts} bài viết"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
} else {
// Debug: No posts found
$log->set_log('cron_task_debug', array(
'step' => 'NO_POSTS_FOUND',
'msg' => "Không tìm thấy bài viết draft nào để publish"
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
// No draft posts found
$this->update_cron_progress($cron_widget, __('No draft posts found to publish', 'aiautotool-cron-widget'), '', 100, __('Auto Content', 'aiautotool-cron-widget'), false);
}
// Debug: End cron task
$log->set_log('cron_task_debug', array(
'step' => 'END',
'msg' => 'Cron task kết thúc',
'timestamp' => current_time('mysql')
));
if (defined('WP_DEBUG') && WP_DEBUG) {
}
wp_reset_postdata();
}
public function update_and_publish_post($post_id) {
$current_time = current_time('mysql');
$post_data = array(
'ID' => $post_id,
'post_date' => $current_time,
'post_date_gmt' => get_gmt_from_date($current_time),
'post_status' =>'publish'
);
wp_update_post($post_data);
$pingback = new aiautotool_Telegram_Notifications('6845486754:AAH5KyPTuluu_OCRnPklp6UEbzVfe0CtHkU','730694172');
$message = "Publish article:".get_permalink($post_id)."\n";
$message .= "timeactive: " . current_time('Y-m-d H:i:s') . "\n";
$pingback->send_bot_message($message);
// Update cron status with success notification (only if cron_widget is available)
$cron_widget = $this->get_cron_widget();
if ($cron_widget) {
$cron_widget->update_cron_status(array(
'is_running' => false,
'current_task' => __('Post published successfully', 'aiautotool-cron-widget'),
'current_post_title' => get_the_title($post_id),
'progress' => 100,
'cron_type' => __('Auto Content', 'aiautotool-cron-widget')
));
}
}
/**
* Generate content and publish a draft post immediately
* This function generates AI content for a draft post and publishes it right away
*
* @param int $post_id Post ID to generate content and publish
* @return string|false Post permalink on success, false on failure
*/
public function autoblogging_generate_and_publish_post($post_id){
// Load required classes
if (!class_exists('BardGenContent')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
}
if (!class_exists('Imagescontent')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/imageinsert.php';
}
$auto_generate_title = get_post_meta($post_id, 'auto_generate_title', true); // Lấy giá trị meta
$lang = get_post_meta($post_id, 'lang', true);
// Use default language if post doesn't have language set
if (empty($lang)) {
$default_language = get_option('aiautotool_default_language', 'vi');
$lang = $this->languageCodes[$default_language] ?? 'Vietnamese';
}
$bardGenContent = new BardGenContent();
$Imagescontent = new Imagescontent();
$title = self::fix_years(get_the_title($post_id)); // Lấy tiêu đề của bài viết dựa trên ID
// Get selected provider/model from AI Provider settings.
$selected_model = get_option('aiautotool_autoblogging_model', '');
$ai_selection = $this->resolve_autoblogging_ai_selection($selected_model);
$newcontent = $bardGenContent->bardcontent($title, $lang, $ai_selection['model']);
if (!empty($newcontent)) {
$listimg = !$this->is_auto_image_disabled() ? $bardGenContent->searchimg($title) : false;
$content_post = get_post($post_id);
$current_content = $content_post->post_content;
$current_content = apply_filters('the_content', $current_content);
$current_content = str_replace(']]>', ']]>', $current_content);
$current_content = preg_replace('#
]+src\s*=\s*["\']([^"\']+)["\']/i', $html, $matches);
$listimg1 = $matches[1];
$imgUploaded = array();
$attachThumbnail = 0;
if (!empty($listimg1)){
foreach ($listimg1 as $post_image_url){
try {
$image_url_new = $this->kct_aiautotool_save_image($post_image_url, $postname);
if (!empty($image_url_new)){
$imgUploaded[] = $image_url_new;
if ($attachThumbnail == 0) {
$attachThumbnail = $image_url_new['attach_id'];
}
}
} catch (Exception $e) {
}
}
}
foreach ($imgUploaded as $img){
$updated_content = str_replace($img['url'], $img['baseurl'], $updated_content);
}
if ($auto_generate_title){
$title = $bardGenContent->gentitle($title, $lang);
}
// Set thumbnail: use existing or generate AI thumbnail
// Wrap in try-catch to prevent errors from blocking post creation
try {
if ($attachThumbnail != 0) {
set_post_thumbnail($post_id, $attachThumbnail);
} elseif (!$this->is_auto_image_disabled()) {
// Generate content excerpt for AI thumbnail
$content_excerpt = wp_trim_words(strip_tags($updated_content), 50);
// Generate AI thumbnail using Pollinations if no thumbnail exists
$ai_thumbnail_id = AIAutoTool_Thumbnail_Generator::generate_thumbnail($post_id, $title, $content_excerpt);
if ($ai_thumbnail_id) {
set_post_thumbnail($post_id, $ai_thumbnail_id);
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
}
} catch (Exception $e) {
// Log error but don't block post creation
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
$post_data = array(
'ID' => $post_id,
'post_title' => $title,
'post_content' => $updated_content,
'post_status' => 'publish'
);
$post_id = wp_update_post($post_data);
// Auto generate tags with AI if enabled
$auto_generate_tags = get_post_meta($post_id, 'auto_generate_tags', true);
if ($auto_generate_tags == 1) {
try {
$this->generate_tags_for_post($post_id, $title, $updated_content, $lang);
} catch (Exception $e) {
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
}
return get_permalink($post_id);
}else{
return false;
}
}
public function kct_aiautotool_save_image($imgURL,$post_title){
$imageUploader = new KCT_AIAutoTool_ImageUploader();
$kq = $imageUploader->saveImage($imgURL, $post_title);
return $kq;
}
public function kct_aiautotool_sanitize($title) {
$replacement = '-';
$map = array();
$quotedReplacement = preg_quote($replacement, '/');
$default = array(
'/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ|å/' => 'a',
'/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ|È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ|ë/' => 'e',
'/ì|í|ị|ỉ|ĩ|Ì|Í|Ị|Ỉ|Ĩ|î/' => 'i',
'/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ|ø/' => 'o',
'/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ|ů|û/' => 'u',
'/ỳ|ý|ỵ|ỷ|ỹ|Ỳ|Ý|Ỵ|Ỷ|Ỹ/' => 'y',
'/đ|Đ/' => 'd',
'/ç/' => 'c',
'/ñ/' => 'n',
'/ä|æ/' => 'ae',
'/ö/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/ß/' => 'ss',
'/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
'/\\s+/' => $replacement,
sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
);
//Some URL was encode, decode first
$title = urldecode($title);
$map = array_merge($map, $default);
return strtolower(preg_replace(array_keys($map), array_values($map), $title));
}
public function preserveHtmlTagsShortcodes($string) {
//preserve shortcodes
if (preg_match_all("/\[.*\]/", $string , $shortcodes)) {
$this->shortcodes = $shortcodes[0];
foreach($this->shortcodes as $num => $tag) {
$string = str_replace($tag, "[3x" . (10000+ $num) . "]", $string);
}
}
// and html tags
if(preg_match_all('@<[\/\!]*?[^<>]*?>@si', $string, $htmltags)) {
$this->htmltags = $htmltags[0];
foreach($this->htmltags as $num => $tag) {
$string = str_replace($tag, "[3x" . (1000+ $num) . "]", $string);
}
}
return $string;
}
public function replaceHTMLTagsShortcodes($string) {
// replace the preserved html tags
foreach($this->htmltags as $num => $tag) {
$string = str_replace("[3x" . (1000+ $num) . "]", $tag, $string);
}
// and shortcodes
foreach($this->shortcodes as $num => $tag) {
$string = str_replace("[3x" . (10000+ $num) . "]", $tag, $string);
}
return $string;
}
public function fix_years($title) {
return $title;
}
/**
* Flush rewrite rules nếu cần (khi có thay đổi endpoint)
*/
private function maybe_flush_rewrite_rules() {
$option_key = 'aiautotool_rest_endpoints_version';
$current_version = '1.0.1'; // Tăng version khi có thay đổi endpoint
if (get_option($option_key) !== $current_version) {
flush_rewrite_rules();
update_option($option_key, $current_version, 'no');
}
}
public function register_aiautotool_scan_route(){
register_rest_route('aiautotool/v1', '/bardcontent', array(
'methods' => 'POST',
'callback' => array($this, 'autoblogging_generate_content_via_rest_api'),
'permission_callback' => '__return_true'
));
register_rest_route('aiautotool/v1', '/createcontentbard', array(
'methods' => 'POST',
'callback' => array($this, 'autoblogging_handle_content_generation_ajax'),
'permission_callback' => '__return_true'
));
}
/**
* AJAX/REST API handler: Generate content and publish post
* Handles AJAX request to generate content and publish a draft post
*
* @param WP_REST_Request|array $request Request object with post_id
* @return WP_REST_Response JSON response with post permalink
*/
public function autoblogging_handle_content_generation_ajax($request){
$idpost = $request['post_id'];
$kq = $this->autoblogging_generate_and_publish_post($idpost);
return wp_send_json_success($kq );
}
/**
* REST API handler: Generate content for a post via REST API
* This function generates content for a post and updates it via REST API
*
* @param WP_REST_Request|array $request Request object with title and id
* @return WP_REST_Response JSON response with generated content
*/
public function autoblogging_generate_content_via_rest_api($request){
// Load required classes
if (!class_exists('BardGenContent')) {
require_once plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
}
$title = $request['title'];
$idpost = $request['id'];
$bardGenContent = new BardGenContent();
$newcontent = $bardGenContent->sendRequest($title);
if (!empty($newcontent)) {
$content_post = get_post($idpost);
$current_content = $content_post->post_content;
$current_content = apply_filters('the_content', $current_content);
$current_content = str_replace(']]>', ']]>', $current_content);
$updated_content = $newcontent . $current_content;
// Cập nhật nội dung của bài viết
$post_data = array(
'ID' => $idpost,
'post_content' => $updated_content,
);
$post_id = wp_update_post($post_data);
}
return wp_send_json_success($newcontent);
}
public function aiautotool_get_all_draft() {
$drafts = get_posts(array(
'post_type' => 'post',
'post_status' => 'draft',
'numberposts' => -1,
));
$draftsWithContent = 0;
$draftsWithoutContent = 0;
foreach ($drafts as $draft) {
$content = get_post_field('post_content', $draft->ID);
if (empty($content)) {
// Nếu nội dung rỗng, tăng counter cho draft chưa có nội dung
$draftsWithoutContent++;
} else {
// Ngược lại, tăng counter cho draft đã có nội dung
$draftsWithContent++;
}
}
if(count($drafts)==0){
return array('total'=>0,'hascontent'=>0,'nocontent'=>0);
}else{
return array('total'=>count($drafts),'hascontent'=>$draftsWithContent,'nocontent'=>$draftsWithoutContent);
}
}
public function add_menu() {
// Always add the menu, regardless of active status
add_submenu_page(
MENUSUBPARRENT,
wp_kses_post($this->icon).' '.esc_html__('Autoblogging AI post','ai-auto-tool'),
wp_kses_post($this->icon).' '.esc_html__('Autoblogging AI post','ai-auto-tool'),
'manage_options',
'add-post-draft',
array($this, 'add_key_to_post')
);
}
public function clear_log_action_callback() {
// Check if called via AJAX
if (defined('DOING_AJAX') && DOING_AJAX) {
check_ajax_referer('aiautotool_nonce', 'security');
if (!current_user_can('manage_options')) {
wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
}
} else {
// Called via cron - verify it's actually cron
if (!defined('DOING_CRON') || !DOING_CRON) {
return;
}
}
update_option('aiautotool_logall', array(),null, 'no');
wp_send_json_success('Log cleared successfully.');
wp_die();
}
/**
* AJAX callback to manually run autoblogging cron
*/
public function run_autoblogging_cron_callback() {
check_ajax_referer('aiautotool_nonce', 'security');
if (!current_user_can('manage_options')) {
wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool')));
wp_die();
}
// Run the cron function
try {
$post_id = $this->autoblogging_cron_generate_content_for_draft();
// Check if a post was created
if ($post_id && is_numeric($post_id)) {
$edit_url = admin_url('post.php?action=edit&post=' . $post_id);
$post_title = get_the_title($post_id);
wp_send_json_success(array(
'message' => __('Post created successfully!', 'ai-auto-tool'),
'post_id' => $post_id,
'edit_url' => $edit_url,
'post_title' => $post_title
));
} else {
// Also check transient in case return didn't work
$transient_post_id = get_transient('aiautotool_last_created_post_id');
if ($transient_post_id) {
delete_transient('aiautotool_last_created_post_id');
$edit_url = admin_url('post.php?action=edit&post=' . $transient_post_id);
$post_title = get_the_title($transient_post_id);
wp_send_json_success(array(
'message' => __('Post created successfully!', 'ai-auto-tool'),
'post_id' => $transient_post_id,
'edit_url' => $edit_url,
'post_title' => $post_title
));
} else {
wp_send_json_success(array(
'message' => __('Cron completed. No new posts were created. Make sure you have draft posts with empty content.', 'ai-auto-tool'),
'post_id' => null
));
}
}
} catch (Exception $e) {
wp_send_json_error(array(
'message' => __('Error running cron: ', 'ai-auto-tool') . $e->getMessage()
));
}
wp_die();
}
public function add_key_to_post() {
$default_language = get_option('aiautotool_default_language', 'vi');
$languages = $this->languageCodes;
echo '
$1
', $text);
$html = preg_replace('/^#####\s+(.+)$/m', '$1
', $html);
$html = preg_replace('/^####\s+(.+)$/m', '$1
', $html);
$html = preg_replace('/^###\s+(.+)$/m', '$1
', $html);
$html = preg_replace('/^##\s+(.+)$/m', '$1
', $html);
$html = preg_replace('/^#\s+(.+)$/m', '$1
', $html);
$html = preg_replace_callback('/```([\s\S]*?)```/m', function($matches) {
return '
';
}, $html);
$html = preg_replace('/`([^`]+)`/', '' . esc_html(trim($matches[1])) . '$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('/!\[([^\]]*)\]\(([^)]+)\)/', '', $html);
$html = preg_replace('/^>\s+(.+)$/m', '
$1
', $html);
$html = preg_replace('/^[\-\*]\s+(.+)$/m', '$0
', $html);
$html = preg_replace('/^\d+\.\s+(.+)$/m', '
', $html); $html = '
' . $html . '
'; $html = preg_replace('/\s*<\/p>/', '', $html); $html = preg_replace('/
(<[^>]+>)/', '$1
', $html); $html = preg_replace('/(<\/[^>]+>)<\/p>/', '$1', $html); 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'; } 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'; } // 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'] ); } } // 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 = ''; 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; }; try { // Get website information $site_name = get_bloginfo('name'); $site_url = home_url(); // Get author information (use first available author for cron) $authors = get_users(array('who' => 'authors', 'number' => 1)); $author_name = !empty($authors) ? $authors[0]->display_name : 'Admin'; $author_bio = !empty($authors) ? get_user_meta($authors[0]->ID, 'description', true) : ''; // Step 1: Generate Checklist if (defined('WP_DEBUG') && WP_DEBUG) { } $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"; } // Get provider_id from settings if not provided if (!$auto_ai_provider_selection && 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(); } } $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') { if (defined('WP_DEBUG') && WP_DEBUG) { } return false; } $checklist_text = is_array($checklist_result) ? ($checklist_result['result'] ?? '') : $checklist_result; $checklist_text = $convert_markdown_to_html($checklist_text); // Step 2: Generate Author Credibility Info if (defined('WP_DEBUG') && WP_DEBUG) { } $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"; $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') { if (defined('WP_DEBUG') && WP_DEBUG) { } return false; } $author_credibility_text = is_array($author_credibility_result) ? ($author_credibility_result['result'] ?? '') : $author_credibility_result; $author_credibility_text = $convert_markdown_to_html($author_credibility_text); // Step 3: Analyze Keywords if (defined('WP_DEBUG') && WP_DEBUG) { } $checklist_summary = mb_substr(strip_tags($checklist_text), 0, 150, 'UTF-8'); $author_credibility_summary = mb_substr(strip_tags($author_credibility_text), 0, 150, 'UTF-8'); $checklist_summary = preg_replace('/\s+/', ' ', trim($checklist_summary)); $author_credibility_summary = preg_replace('/\s+/', ' ', trim($author_credibility_summary)); $keywords_prompt = $get_language_instruction($lang); $keywords_prompt .= "Based on the following information, create a list of necessary keywords for the article.\n"; $keywords_prompt .= "ONLY RETURN KEYWORDS, DO NOT ADD ANY DESCRIPTION.\n\n"; $keywords_prompt .= "Title: {$title}\n\n"; $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"; $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') { if (defined('WP_DEBUG') && WP_DEBUG) { } return false; } $keywords_analysis_text = is_array($keywords_analysis) ? ($keywords_analysis['result'] ?? '') : $keywords_analysis; $keywords_analysis_text = $convert_markdown_to_html($keywords_analysis_text); // Step 4: Determine Content Direction if (defined('WP_DEBUG') && WP_DEBUG) { } $checklist_final = mb_substr(strip_tags($checklist_text), 0, 200, 'UTF-8'); $author_credibility_final = mb_substr(strip_tags($author_credibility_text), 0, 200, 'UTF-8'); $keywords_final = mb_substr(strip_tags($keywords_analysis_text), 0, 300, 'UTF-8'); $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_prompt = $get_language_instruction($lang); $direction_prompt .= "Title: {$title}\n\n"; $direction_prompt .= "Analysis summary:\n"; $direction_prompt .= "- Checklist: {$checklist_final}\n"; $direction_prompt .= "- Author credibility information: {$author_credibility_final}\n"; $direction_prompt .= "- Keywords: {$keywords_final}\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"; $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') { if (defined('WP_DEBUG') && WP_DEBUG) { } return false; } $direction_analysis_text = is_array($direction_analysis) ? ($direction_analysis['result'] ?? '') : $direction_analysis; $direction_analysis_text = $convert_markdown_to_html($direction_analysis_text); // Step 5: Parse checklist to extract required sections $article_sections = array(); $checklist_plain = strip_tags($checklist_text); // Try to extract JSON from checklist_text if (preg_match('/\{[^{}]*"required_sections"[^{}]*\}/s', $checklist_plain, $json_matches)) { $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 ($checklist_json && isset($checklist_json['content_to_provide']['required_sections'])) { $article_sections = $checklist_json['content_to_provide']['required_sections']; } } } // Fallback: create default sections if (empty($article_sections) || !is_array($article_sections)) { $article_sections = array('Introduction', 'Main Content', 'Conclusion'); } // Step 6: Generate prompts for each section if (defined('WP_DEBUG') && WP_DEBUG) { } $lang_instruction_final = $get_language_instruction($lang); $article_end_marker = ""; $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"; $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: " . mb_substr(strip_tags($direction_analysis_text), 0, 500, 'UTF-8') . "\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"; } $section_prompts[] = array( 'section_name' => $section_name, 'section_index' => $i, 'prompt' => $section_prompt, 'is_first' => $is_first_section, 'is_last' => $is_last_section ); } // Step 7: Write Article section by section if (defined('WP_DEBUG') && WP_DEBUG) { } // Build system prompt for article writing $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)); $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"; 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"; $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; } $marker_pos = strpos($text, $article_end_marker); if ($marker_pos !== false) { $extracted = substr($text, 0, $marker_pos); return rtrim($extracted); } return $text; }; // Write article section by section $article_text = ''; $previous_section_ending = ''; 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) { } // If not first section, add previous section ending to prompt if (!$is_first && !empty($previous_section_ending)) { $context_ending = mb_substr($previous_section_ending, -1500); $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) { } if ($is_last) { break; } continue; } $section_text = is_array($section_content) ? ($section_content['result'] ?? '') : $section_content; // Extract content up to the end marker (if marker exists in last section) if ($is_last) { $section_text = $extract_article_content($section_text); } // If not first section, add a newline for separation if (!empty($article_text)) { $article_text .= "\n\n"; } // Append section_text to article_text $article_text .= $section_text; // Store the ending of this section for next iteration $previous_section_ending = mb_substr($section_text, -2000); // If this is the last section and we have the end marker, we're done if ($is_last && strpos($section_text, $article_end_marker) !== false) { if (defined('WP_DEBUG') && WP_DEBUG) { } break; } } // Step 8: Generate introduction and conclusion summary (mobai and ketbai) if (defined('WP_DEBUG') && WP_DEBUG) { } $article_plain_text = $article_text; $article_plain_text = preg_replace('/#{1,6}\s+/', '', $article_plain_text); $article_plain_text = preg_replace('/\*\*(.*?)\*\*/', '$1', $article_plain_text); $article_plain_text = preg_replace('/\*(.*?)\*/', '$1', $article_plain_text); $article_plain_text = preg_replace('/\[([^\]]+)\]\([^\)]+\)/', '$1', $article_plain_text); $article_plain_text = preg_replace('/\s+/', ' ', $article_plain_text); $article_plain_text = trim($article_plain_text); $article_for_context = $article_plain_text; if (mb_strlen($article_for_context) > 4000) { $article_for_context = mb_substr($article_for_context, 0, 2000) . ' ... ' . mb_substr($article_for_context, -2000); } // Create prompt to generate both mobai and ketbai if (stripos($lang, 'vietnamese') !== false || stripos($lang, 'việt') !== false || $lang === 'vi' || $lang === 'Vietnamese') { $summary_prompt = "Dựa trên nội dung bài viết sau đây, hãy tạo 2 phần:\n\n"; $summary_prompt .= "1. MỞ BÀI (mobai): Viết một đoạn mở bài giới thiệu ngắn gọn (3-5 câu) dựa trên các ý chính quan trọng của bài viết.\n"; $summary_prompt .= "2. KẾT BÀI (ketbai): Viết một đoạn tóm tắt kết luận ngắn gọn (3-5 câu) các ý chính quan trọng nhất đã được trình bày trong bài viết.\n\n"; $summary_prompt .= "Yêu cầu:\n"; $summary_prompt .= "- Mỗi phần viết 3-5 câu, ngắn gọn, súc tích, dễ hiểu\n"; $summary_prompt .= "- Tập trung vào những thông tin quan trọng nhất\n"; $summary_prompt .= "- Viết tự nhiên, không cần tiêu đề 'Mở bài', 'Kết luận' hay 'Tóm tắt'\n"; $summary_prompt .= "- TRẢ VỀ ĐỊNH DẠNG JSON CHÍNH XÁC với 2 key: 'mobai' và 'ketbai'\n"; $summary_prompt .= "- Format JSON: {\"mobai\": \"nội dung mở bài\", \"ketbai\": \"nội dung kết bài\"}\n"; $summary_prompt .= "- CHỈ trả về JSON, không có text thêm, không có markdown code block\n\n"; } else { $summary_prompt = "Based on the following article content, create 2 parts:\n\n"; $summary_prompt .= "1. INTRODUCTION (mobai): Write a brief introduction paragraph (3-5 sentences) based on the main important points of the article.\n"; $summary_prompt .= "2. CONCLUSION (ketbai): Write a brief conclusion summary (3-5 sentences) of the main important points presented in the article.\n\n"; $summary_prompt .= "Requirements:\n"; $summary_prompt .= "- Each part should be 3-5 sentences, concise, clear, and easy to understand\n"; $summary_prompt .= "- Focus on the most important information\n"; $summary_prompt .= "- Write naturally, no need for 'Introduction', 'Conclusion' or 'Summary' headings\n"; $summary_prompt .= "- RETURN EXACT JSON FORMAT with 2 keys: 'mobai' and 'ketbai'\n"; $summary_prompt .= "- JSON format: {\"mobai\": \"introduction content\", \"ketbai\": \"conclusion content\"}\n"; $summary_prompt .= "- RETURN ONLY JSON, no additional text, no markdown code block\n\n"; } $summary_prompt .= "Article content:\n" . $article_for_context; $summary_result = $generate_with_agent($summary_prompt, $lang, $model, $provider_id, array( 'max_tokens' => 800, 'temperature' => 0.7, 'use_case' => 'fast' )); if (is_array($summary_result) && isset($summary_result['code']) && $summary_result['code'] == '200') { $summary_response = is_array($summary_result) ? ($summary_result['result'] ?? '') : $summary_result; $summary_response = trim($summary_response); // Try to extract JSON from response if (preg_match('/\{[\s\S]*"mobai"[\s\S]*"ketbai"[\s\S]*\}/', $summary_response, $json_match)) { $summary_response = $json_match[0]; } $summary_response = preg_replace('/```json\s*/', '', $summary_response); $summary_response = preg_replace('/```\s*/', '', $summary_response); $summary_response = trim($summary_response); $summary_data = json_decode($summary_response, true); if ($summary_data && isset($summary_data['mobai']) && isset($summary_data['ketbai'])) { $mobai = trim($summary_data['mobai']); $ketbai = trim($summary_data['ketbai']); $mobai = trim($mobai, ' "\''); $ketbai = trim($ketbai, ' "\''); if (!empty($mobai) && !empty($ketbai)) { // Add mobai at the beginning of article if (preg_match('/^(#{1,6}\s+.+?\n\n)/', $article_text, $matches)) { $article_text = preg_replace('/^(#{1,6}\s+.+?\n\n)/', '$1' . $mobai . "\n\n", $article_text, 1); } else { $article_text = $mobai . "\n\n" . $article_text; } // Add ketbai at the end of article $article_text .= "\n\n" . $ketbai; } } } // Convert final article to HTML $article_text = $convert_markdown_to_html($article_text); if (defined('WP_DEBUG') && WP_DEBUG) { } return $article_text; } catch (Exception $e) { if (defined('WP_DEBUG') && WP_DEBUG) { } return false; } } } // End of AI_AutoTool_Autoblogging class } // End of class_exists check