'; protected $table_name; public $limit = AIAUTOTOOL_FREE; private $plan_limit_aiautotool; public $name_plan; public $config = array(); public $notice; public function __construct() { global $wpdb; $this->table_name = $wpdb->prefix . 'aiautotool_keywords'; $this->name_plan = esc_html__('Autopost from Keyword', 'ai-auto-tool'); $this->plan_limit_aiautotool = 'plan_limit_aiautotool_' . $this->active_option_name; $this->notice = new aiautotool_Warning_Notice(); $this->active = get_option($this->active_option_name, true); if ($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_nopriv_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback')); add_action('wp_ajax_get_keyword_queue', array($this, 'get_keyword_queue_callback')); add_action('wp_ajax_run_keyword_cron_now', array($this, 'run_keyword_cron_now_callback')); add_action('wp_ajax_get_cron_status', array($this, 'get_cron_status_callback')); add_action('wp_ajax_bulk_delete_keywords', array($this, 'bulk_delete_keywords_callback')); add_action('wp_ajax_bulk_process_keywords', array($this, 'bulk_process_keywords_callback')); } public function create_keywords_table() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name} ( id mediumint(9) NOT NULL AUTO_INCREMENT, keyword varchar(255) NOT NULL, category_id int(11) DEFAULT 0, tags text, language varchar(10) DEFAULT 'vi', status varchar(20) DEFAULT 'pending', priority int(11) DEFAULT 0, created_at datetime DEFAULT CURRENT_TIMESTAMP, processed_at datetime NULL, post_id int(11) DEFAULT 0, error_message text, PRIMARY KEY (id), KEY status (status), KEY priority (priority) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } public function init() { $this->create_keywords_table(); $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 ($this->is_premium()->get_plan_name() == 'aiautotoolpro' || $this->is_premium()->get_plan_name() == 'premium') { $this->config = array( 'number_post' => -1, 'usage' => get_option($this->usage_option_name, 0, 'no'), 'time_exprice' => $this->is_premium()->_get_license()->expiration ); } 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')); if ($this->aiautotool_checklimit($this->config)) { add_filter('cron_schedules', array($this, 'keyword_autopost_schedule_cron_intervals')); if (!wp_next_scheduled('keyword_autopost_cron_event')) { wp_schedule_event(time(), 'keyword_autopost_schedule_cron_intervals', 'keyword_autopost_cron_event'); } add_action('keyword_autopost_cron_event', array($this, 'process_keyword_autopost')); } else { $this->notice->add_notice( AIAUTOTOOL_TITLE_UPGRADE, 'notice-error', null, true, 'aiautotool' ); } add_action('wp_ajax_add_keywords', array($this, 'add_keywords_callback')); add_action('wp_ajax_nopriv_add_keywords', array($this, 'add_keywords_callback')); add_action('wp_ajax_delete_keyword', array($this, 'delete_keyword_callback')); add_action('wp_ajax_clear_keywords_log', array($this, 'clear_keywords_log_callback')); } public function keyword_autopost_schedule_cron_intervals($schedules) { $current_interval = get_option('keyword_autopost_time', 5); $schedules['keyword_autopost_schedule_cron_intervals'] = array( 'interval' => intval($current_interval) * 60, 'display' => __('Keyword autopost interval', 'ai-auto-tool') ); return $schedules; } public function process_keyword_autopost() { global $wpdb; $log = new AIautoTool_log(); $cron_widget = AIAutoTool_Cron_Status_Widget::get_instance(); // Update last run time update_option('keyword_autopost_last_run', current_time('Y-m-d H:i:s')); // Update cron status - starting $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Searching for pending keywords...', 'aiautotool-cron-widget'), 'current_post_title' => '', 'progress' => 10, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); // Get pending keywords $pending_keywords = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->table_name} WHERE status = 'pending' ORDER BY priority DESC, created_at ASC LIMIT 1" ) ); if (empty($pending_keywords)) { $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('No pending keywords found', 'aiautotool-cron-widget'), 'current_post_title' => '', 'progress' => 100, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); return; } $keyword_data = $pending_keywords[0]; // Update status - found keyword $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Processing keyword...', 'aiautotool-cron-widget'), 'current_post_title' => $keyword_data->keyword, 'progress' => 20, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); try { // Mark as processing $wpdb->update( $this->table_name, array('status' => 'processing'), array('id' => $keyword_data->id) ); if ($this->aiautotool_checklimit($this->config)) { $log->set_log('keyword_autopost', array( 'keyword_id' => $keyword_data->id, 'keyword' => $keyword_data->keyword, 'msg' => 'Starting keyword processing' )); // Generate title from keyword $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Generating title from keyword...', 'aiautotool-cron-widget'), 'current_post_title' => $keyword_data->keyword, 'progress' => 30, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); $title = $this->generate_title_from_keyword($keyword_data->keyword, $keyword_data->language); if (!$title) { throw new Exception('Failed to generate title from keyword'); } // Generate content $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Generating content...', 'aiautotool-cron-widget'), 'current_post_title' => $title, 'progress' => 50, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); $content = $this->generate_content_from_keyword($keyword_data->keyword, $keyword_data->language); if (!$content) { throw new Exception('Failed to generate content from keyword'); } // Process images $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Processing images...', 'aiautotool-cron-widget'), 'current_post_title' => $title, 'progress' => 70, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); $content = $this->process_images_for_content($content, $title); // Validate and fix content before publishing (only if validation is enabled) if (get_option('keyword_autopost_content_validation', 1)) { $content = $this->validate_and_fix_content($content); } // Create and publish post $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Creating and publishing post...', 'aiautotool-cron-widget'), 'current_post_title' => $title, 'progress' => 90, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); $post_id = $this->create_and_publish_post($title, $content, $keyword_data); if ($post_id) { // Update keyword status $wpdb->update( $this->table_name, array( 'status' => 'completed', 'processed_at' => current_time('mysql'), 'post_id' => $post_id ), array('id' => $keyword_data->id) ); $this->aiautotool_update_usage(); $log->set_log('keyword_autopost', array( 'keyword_id' => $keyword_data->id, 'keyword' => $keyword_data->keyword, 'post_id' => $post_id, 'msg' => 'Successfully created and published post' )); $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('Post published successfully', 'aiautotool-cron-widget'), 'current_post_title' => $title, 'progress' => 100, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); } else { throw new Exception('Failed to create and publish post'); } } else { throw new Exception('Usage limit exceeded'); } } catch (Exception $e) { // Update keyword status to error $wpdb->update( $this->table_name, array( 'status' => 'error', 'error_message' => $e->getMessage(), 'processed_at' => current_time('mysql') ), array('id' => $keyword_data->id) ); $log->set_log('keyword_autopost', array( 'keyword_id' => $keyword_data->id, 'keyword' => $keyword_data->keyword, 'msg' => 'Error: ' . $e->getMessage() )); $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('Error: ' . $e->getMessage(), 'aiautotool-cron-widget'), 'current_post_title' => $keyword_data->keyword, 'progress' => 100, 'cron_type' => __('Keyword Autopost', 'aiautotool-cron-widget') )); } } private function generate_title_from_keyword($keyword, $language) { $bardGenContent = new BardGenContent(); $prompt = "Generate a compelling, SEO-friendly title for the keyword: '{$keyword}'. The title should be engaging and include the keyword naturally. Write in {$language}."; return $bardGenContent->gentitle($prompt, $language); } private function generate_content_from_keyword($keyword, $language) { $bardGenContent = new BardGenContent(); // Enhanced prompt to avoid markdown issues $prompt = "Write a comprehensive, informative article about '{$keyword}'. Requirements: - Write in {$language} - Minimum 1000 words - Use proper HTML formatting (h2, h3, p, ul, li, strong, em) - Do NOT use markdown code blocks or ``` symbols - Do NOT use
 tags
        - Do NOT include DOCTYPE, HTML, HEAD, BODY tags
        - Do NOT return a complete HTML document
        - Use proper paragraph breaks with 

tags - Include relevant headings with

and

tags - Use bullet points with
    and
  • tags when appropriate - Make it SEO-friendly with natural keyword usage - Include practical information and examples - Write in a conversational, engaging tone Structure the article with: 1. Introduction paragraph 2. Main content with 3-4 sections 3. Conclusion paragraph Return ONLY the article content with HTML formatting, NOT a complete HTML document."; $content = $bardGenContent->bardcontentfull($prompt, $language); // Post-process the content to fix any remaining issues (only if validation is enabled) if (get_option('keyword_autopost_content_validation', 1)) { $content = $this->clean_and_format_content($content); } return $content; } private function clean_and_format_content($content) { // Remove DOCTYPE, HTML, HEAD, BODY tags and other unwanted elements $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/<\/html>/i', '', $content); $content = preg_replace('/]*>.*?<\/head>/is', '', $content); $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/<\/body>/i', '', $content); $content = preg_replace('/]*>.*?<\/title>/is', '', $content); $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/]*>.*?<\/script>/is', '', $content); $content = preg_replace('/]*>.*?<\/style>/is', '', $content); // Remove any markdown code blocks $content = preg_replace('/```[a-zA-Z]*\n(.*?)\n```/s', '

    $1

    ', $content); $content = preg_replace('/`([^`]+)`/', '$1', $content); // Fix broken pre/code tags $content = preg_replace('/
    ]*>/', '

    ', $content); $content = preg_replace('/<\/code><\/pre>/', '

    ', $content); $content = preg_replace('/
    /', '

    ', $content); $content = preg_replace('/<\/code><\/pre>/', '

    ', $content); // Remove any remaining pre tags $content = preg_replace('/]*>(.*?)<\/pre>/s', '

    $1

    ', $content); // Fix common markdown issues $content = preg_replace('/\*\*(.*?)\*\*/', '$1', $content); $content = preg_replace('/\*(.*?)\*/', '$1', $content); // Fix heading formatting $content = preg_replace('/^### (.*?)$/m', '

    $1

    ', $content); $content = preg_replace('/^## (.*?)$/m', '

    $1

    ', $content); $content = preg_replace('/^# (.*?)$/m', '

    $1

    ', $content); // Fix list formatting $content = preg_replace('/^- (.*?)$/m', '
  • $1
  • ', $content); $content = preg_replace('/^\* (.*?)$/m', '
  • $1
  • ', $content); // Wrap consecutive li elements in ul tags $content = preg_replace('/(
  • .*?<\/li>)+/s', '
      $0
    ', $content); // Ensure paragraphs are properly wrapped $content = preg_replace('/^(?!<[h|u|o]|
  • )(.*?)$/m', '

    $1

    ', $content); // Remove empty paragraphs $content = preg_replace('/

    \s*<\/p>/', '', $content); // Fix double line breaks $content = preg_replace('/\n\s*\n/', '

    ', $content); // Clean up any remaining markdown artifacts $content = str_replace(['```', '`'], '', $content); // Remove any language attributes from code tags $content = preg_replace('//', '', $content); // Remove any remaining HTML comments $content = preg_replace('//s', '', $content); // Remove any remaining unwanted HTML tags $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/<\/div>/i', '', $content); $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/<\/span>/i', '', $content); // Remove any empty or malformed paragraph tags $content = preg_replace('/

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

    /', '

    ', $content); $content = preg_replace('/<\/p><\/p>/', '

    ', $content); // Ensure proper HTML structure $content = $this->ensure_proper_html_structure($content); return $content; } private function ensure_proper_html_structure($content) { // Split content into lines $lines = explode("\n", $content); $formatted_lines = array(); $in_list = false; foreach ($lines as $line) { $line = trim($line); if (empty($line)) { if ($in_list) { $formatted_lines[] = '
'; $in_list = false; } continue; } // Handle headings if (preg_match('/^/', $line)) { if ($in_list) { $formatted_lines[] = ''; $in_list = false; } $formatted_lines[] = $line; continue; } // Handle list items if (preg_match('/^
  • /', $line)) { if (!$in_list) { $formatted_lines[] = '
      '; $in_list = true; } $formatted_lines[] = $line; continue; } // Handle paragraphs if (preg_match('/^

      /', $line)) { if ($in_list) { $formatted_lines[] = '

    '; $in_list = false; } $formatted_lines[] = $line; continue; } // Handle other content if ($in_list) { $formatted_lines[] = ''; $in_list = false; } // Wrap plain text in paragraphs if (!preg_match('/^' . $line . '

    '; } else { $formatted_lines[] = $line; } } // Close any open list if ($in_list) { $formatted_lines[] = ''; } return implode("\n", $formatted_lines); } private function process_images_for_content($content, $title) { $bardGenContent = new BardGenContent(); $Imagescontent = new Imagescontent(); $listimg = $bardGenContent->searchimg($title); if ($listimg) { $listimg10 = array_slice($listimg, 0, 10); shuffle($listimg10); $content = $Imagescontent->insertImages($content, $listimg10); } return $content; } private function create_and_publish_post($title, $content, $keyword_data) { $user_ids = get_users(array('fields' => 'ID')); $random_user_id = $user_ids[array_rand($user_ids)]; // Generate automatic tags from content (only if enabled) $auto_tags = ''; if (get_option('keyword_autopost_auto_tags', 1)) { $auto_tags = $this->generate_tags_from_content($content, $keyword_data->keyword, $keyword_data->language); } // Combine user-provided tags with auto-generated tags $final_tags = $keyword_data->tags; if (!empty($auto_tags)) { if (!empty($final_tags)) { $final_tags .= ', ' . $auto_tags; } else { $final_tags = $auto_tags; } } // Clean up tags (remove duplicates, extra spaces) $tag_array = array_map('trim', explode(',', $final_tags)); $tag_array = array_unique($tag_array); $tag_array = array_filter($tag_array, function($tag) { return !empty($tag) && strlen($tag) > 1; }); $final_tags = implode(', ', $tag_array); $post_data = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'publish', 'post_author' => $random_user_id, 'post_category' => array($keyword_data->category_id), 'tags_input' => $final_tags, 'post_type' => 'post' ); $post_id = wp_insert_post($post_data); if ($post_id) { // Set language if Polylang is active if (in_array('polylang/polylang.php', apply_filters('active_plugins', get_option('active_plugins')))) { pll_set_post_language($post_id, $keyword_data->language); } // Send Telegram notification with tags info $pingback = new aiautotool_Telegram_Notifications('6845486754:AAH5KyPTuluu_OCRnPklp6UEbzVfe0CtHkU', '730694172'); $message = "Keyword Autopost: " . get_permalink($post_id) . "\n"; $message .= "Keyword: " . $keyword_data->keyword . "\n"; $message .= "Tags: " . $final_tags . "\n"; $message .= "Time: " . current_time('Y-m-d H:i:s') . "\n"; $pingback->send_bot_message($message); } return $post_id; } public function add_keywords_callback() { check_ajax_referer('aiautotool_nonce', 'security'); $keywords = sanitize_textarea_field($_POST['keywords']); $category_id = intval($_POST['category_id']); $tags = sanitize_text_field($_POST['tags']); $language = sanitize_text_field($_POST['language']); $priority = intval($_POST['priority']); $keyword_list = explode(PHP_EOL, $keywords); $results = array(); global $wpdb; foreach ($keyword_list as $keyword) { $keyword = trim($keyword); if (empty($keyword)) continue; $inserted = $wpdb->insert( $this->table_name, array( 'keyword' => $keyword, 'category_id' => $category_id, 'tags' => $tags, 'language' => $language, 'priority' => $priority, 'status' => 'pending' ), array('%s', '%d', '%s', '%s', '%d', '%s') ); if ($inserted) { $results[] = array( 'keyword' => $keyword, 'status' => 'added' ); } else { $results[] = array( 'keyword' => $keyword, 'status' => 'error' ); } } wp_send_json_success($results); } public function delete_keyword_callback() { check_ajax_referer('aiautotool_nonce', 'security'); $keyword_id = intval($_POST['keyword_id']); global $wpdb; $deleted = $wpdb->delete( $this->table_name, array('id' => $keyword_id), array('%d') ); if ($deleted) { wp_send_json_success('Keyword deleted successfully'); } else { wp_send_json_error('Failed to delete keyword'); } } public function clear_keywords_log_callback() { check_ajax_referer('aiautotool_nonce', 'security'); global $wpdb; $wpdb->query("DELETE FROM {$this->table_name} WHERE status IN ('completed', 'error')"); wp_send_json_success('Keywords log cleared successfully'); } public function get_keyword_queue_callback() { check_ajax_referer('aiautotool_nonce', 'security'); $page = isset($_POST['page']) ? intval($_POST['page']) : 1; $filter = isset($_POST['filter']) ? sanitize_text_field($_POST['filter']) : 'all'; $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : ''; $sort_order = isset($_POST['sort_order']) ? sanitize_text_field($_POST['sort_order']) : 'recent-completed'; $html = $this->render_keyword_queue_table($page, 20, $filter, $search, $sort_order); wp_send_json_success($html); } private function get_status_icon($status) { switch ($status) { case 'pending': return ''; case 'processing': return ''; case 'completed': return ''; case 'error': return ''; default: return ''; } } private function get_priority_badge($priority) { switch ($priority) { case 10: return 'Urgent'; case 5: return 'High'; case 1: return 'Low'; default: return 'Normal'; } } private function calculate_processing_time($keyword) { if ($keyword->status == 'pending') { return esc_html__('Not started', 'ai-auto-tool'); } if ($keyword->status == 'processing') { $start_time = strtotime($keyword->created_at); $elapsed = time() - $start_time; return $this->format_time($elapsed); } if ($keyword->processed_at) { $start_time = strtotime($keyword->created_at); $end_time = strtotime($keyword->processed_at); $duration = $end_time - $start_time; return $this->format_time($duration); } return esc_html__('Unknown', 'ai-auto-tool'); } private function format_time($seconds) { if ($seconds < 60) { return $seconds . 's'; } elseif ($seconds < 3600) { return round($seconds / 60, 1) . 'm'; } else { $hours = floor($seconds / 3600); $minutes = round(($seconds % 3600) / 60); return $hours . 'h ' . $minutes . 'm'; } } public function run_keyword_cron_now_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error('Insufficient permissions'); } // Update last run time update_option('keyword_autopost_last_run', current_time('Y-m-d H:i:s')); // Trigger the cron event manually do_action('keyword_autopost_cron_event'); wp_send_json_success('Cron job executed successfully'); } public function get_cron_status_callback() { check_ajax_referer('aiautototool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error('Insufficient permissions'); } global $wpdb; // Get cron status $next_run = wp_next_scheduled('keyword_autopost_cron_event'); $status_html = ''; if ($next_run) { $status_html = ' Active'; } else { $status_html = ' Inactive'; } // Get next run time $next_run_html = ''; if ($next_run) { $next_run_html = '' . esc_html(date('Y-m-d H:i:s', $next_run)) . ''; } else { $next_run_html = '' . esc_html__('Not scheduled', 'ai-auto-tool') . ''; } // Get last run time $last_run = get_option('keyword_autopost_last_run', ''); $last_run_html = $last_run ? esc_html($last_run) : esc_html__('Never', 'ai-auto-tool'); // Get current processing status $processing_keyword = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}aiautotool_keywords WHERE status = 'processing' ORDER BY created_at DESC LIMIT 1" ); $processing_html = ''; if ($processing_keyword) { $processing_html = '
    '; $processing_html .= '
    ' . esc_html($processing_keyword->keyword) . '
    '; $processing_html .= '
    ' . esc_html__('Started:', 'ai-auto-tool') . ' ' . esc_html($processing_keyword->created_at) . '
    '; $processing_html .= '
    '; $processing_html .= '
    '; $processing_html .= '
    '; $processing_html .= '
    '; $processing_html .= 'Processing...'; $processing_html .= '
    '; $processing_html .= '
    '; } else { $processing_html = '
    '; $processing_html .= '
    ' . esc_html__('No keywords currently being processed', 'ai-auto-tool') . '
    '; $processing_html .= '
    '; } wp_send_json_success(array( 'status' => $status_html, 'next_run' => $next_run_html, 'last_run' => $last_run_html, 'processing_html' => $processing_html )); } public static function check_quota() { return parent::check_quota(); } public function get_keywords_stats() { global $wpdb; $stats = $wpdb->get_results(" SELECT status, COUNT(*) as count FROM {$this->table_name} GROUP BY status "); $result = array( 'pending' => 0, 'processing' => 0, 'completed' => 0, 'error' => 0 ); foreach ($stats as $stat) { $result[$stat->status] = $stat->count; } return $result; } private function calculate_estimated_completion_time($stats) { global $wpdb; // Get average processing time from recent completed keywords $avg_time = $wpdb->get_var( $wpdb->prepare( "SELECT AVG(TIMESTAMPDIFF(SECOND, created_at, processed_at)) FROM {$this->table_name} WHERE status = 'completed' AND processed_at IS NOT NULL AND processed_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)" ) ); if (!$avg_time || $avg_time <= 0) { $avg_time = 60; // Default 60 seconds if no data } // Calculate remaining keywords $remaining = $stats['pending'] + $stats['processing']; // Get cron interval in seconds $cron_interval = get_option('keyword_autopost_time', 5) * 60; // Calculate estimated time $estimated_seconds = ($remaining * $avg_time) / ($cron_interval / 60); // keywords per minute if ($estimated_seconds < 60) { return round($estimated_seconds) . ' ' . esc_html__('seconds', 'ai-auto-tool'); } elseif ($estimated_seconds < 3600) { return round($estimated_seconds / 60, 1) . ' ' . esc_html__('minutes', 'ai-auto-tool'); } else { $hours = floor($estimated_seconds / 3600); $minutes = round(($estimated_seconds % 3600) / 60); return $hours . ' ' . esc_html__('hours', 'ai-auto-tool') . ' ' . $minutes . ' ' . esc_html__('minutes', 'ai-auto-tool'); } } private function get_average_processing_time() { global $wpdb; $avg_time = $wpdb->get_var( $wpdb->prepare( "SELECT AVG(TIMESTAMPDIFF(SECOND, created_at, processed_at)) FROM {$this->table_name} WHERE status = 'completed' AND processed_at IS NOT NULL AND processed_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)" ) ); if (!$avg_time || $avg_time <= 0) { return esc_html__('No data available', 'ai-auto-tool'); } if ($avg_time < 60) { return round($avg_time) . ' ' . esc_html__('seconds', 'ai-auto-tool'); } else { return round($avg_time / 60, 1) . ' ' . esc_html__('minutes', 'ai-auto-tool'); } } public function render_setting() { ?> '; } $current_interval = get_option('keyword_autopost_time', 5); ?>

    active == 'true') { echo ''; } } public function render_feature() { $autoToolBox = new AutoToolBox( wp_kses_post($this->icon) . ' ' . esc_html__('Keyword Autopost', 'ai-auto-tool'), "Automatically generate and publish articles from keywords. The system processes keywords from a queue and creates complete articles with AI-generated content and images.", "https://doc.aiautotool.com/integrations/keyword-autopost-guide", $this->active_option_name, $this->active, esc_url(plugins_url('../images/logo.svg', __FILE__)) ); echo ($autoToolBox->generateHTML()); } public function add_menu() { add_submenu_page( MENUSUBPARRENT, wp_kses_post($this->icon) . ' ' . esc_html__('Keyword Autopost', 'ai-auto-tool'), wp_kses_post($this->icon) . ' ' . esc_html__('Keyword Autopost', 'ai-auto-tool'), 'manage_options', 'keyword-autopost', array($this, 'render_keyword_autopost_page') ); } public function render_keyword_autopost_page() { $default_language = get_option('aiautotool_default_language', 'vi'); $languages = $this->languageCodes; $stats = $this->get_keywords_stats(); echo '
    '; ?>

    icon); ?>

    'category_id', 'show_option_all' => 'Select a category', 'hide_empty' => 0, 'hierarchical' => 1 )); ?>

    roles; if (!in_array('administrator', $user_roles) && !is_super_admin()) { return; } wp_localize_script('jquery', 'aiautotool_js_setting', array( 'ajax_url' => admin_url('admin-ajax.php'), 'security' => wp_create_nonce('aiautotool_nonce'), 'is_admin' => true )); } // Inherit methods from parent class 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 (isset($_POST['active'])) { $active = sanitize_text_field($_POST['active']); update_option($this->active_option_name, $active, null, 'no'); print_r($active); } wp_die(); } public function bulk_delete_keywords_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error('Insufficient permissions'); } $keyword_ids = isset($_POST['keyword_ids']) ? array_map('intval', $_POST['keyword_ids']) : array(); if (empty($keyword_ids)) { wp_send_json_error('No keywords selected'); } global $wpdb; $deleted_count = 0; foreach ($keyword_ids as $keyword_id) { $deleted = $wpdb->delete( $this->table_name, array('id' => $keyword_id), array('%d') ); if ($deleted) { $deleted_count++; } } wp_send_json_success(array( 'message' => sprintf(__('%d keywords deleted successfully', 'ai-auto-tool'), $deleted_count), 'deleted_count' => $deleted_count )); } public function bulk_process_keywords_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error('Insufficient permissions'); } $keyword_ids = isset($_POST['keyword_ids']) ? array_map('intval', $_POST['keyword_ids']) : array(); if (empty($keyword_ids)) { wp_send_json_error('No keywords selected'); } global $wpdb; $updated_count = 0; foreach ($keyword_ids as $keyword_id) { $updated = $wpdb->update( $this->table_name, array('status' => 'pending'), array('id' => $keyword_id, 'status' => 'error'), array('%s'), array('%d', '%s') ); if ($updated) { $updated_count++; } } wp_send_json_success(array( 'message' => sprintf(__('%d keywords queued for processing', 'ai-auto-tool'), $updated_count), 'updated_count' => $updated_count )); } public function render_keyword_queue_table($page = 1, $per_page = 20, $filter = 'all', $search = '', $sort_order = 'recent-completed') { global $wpdb; $offset = ($page - 1) * $per_page; $where_conditions = array(); $where_values = array(); // Apply status filter if ($filter !== 'all') { $where_conditions[] = 'status = %s'; $where_values[] = $filter; } // Apply search filter if (!empty($search)) { $where_conditions[] = 'keyword LIKE %s'; $where_values[] = '%' . $wpdb->esc_like($search) . '%'; } $where_clause = ''; if (!empty($where_conditions)) { $where_clause = 'WHERE ' . implode(' AND ', $where_conditions); } // Get total count for pagination $count_query = "SELECT COUNT(*) FROM {$this->table_name} {$where_clause}"; if (!empty($where_values)) { $total_keywords = $wpdb->get_var($wpdb->prepare($count_query, $where_values)); } else { $total_keywords = $wpdb->get_var($count_query); } // Build ORDER BY clause based on sort order $order_by = $this->build_order_by_clause($sort_order); // Get keywords for current page $keywords_query = "SELECT * FROM {$this->table_name} {$where_clause} {$order_by} LIMIT %d OFFSET %d"; $query_values = array_merge($where_values, array($per_page, $offset)); $keywords = $wpdb->get_results($wpdb->prepare($keywords_query, $query_values)); $total_pages = ceil($total_keywords / $per_page); $html = '
    '; $html .= '
    '; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= '
    '; $html .= '
    '; $html .= ''; $html .= ''; $html .= '
    '; $html .= '
    '; $html .= '
    '; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; if ($keywords) { foreach ($keywords as $keyword) { $status_class = 'status-' . $keyword->status; $status_icon = $this->get_status_icon($keyword->status); $processing_time = $this->calculate_processing_time($keyword); $priority_badge = $this->get_priority_badge($keyword->priority); $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; // Error details row (hidden by default) if ($keyword->status == 'error' && !empty($keyword->error_message)) { $html .= ''; $html .= ''; $html .= ''; } } } else { $html .= ''; } $html .= ''; $html .= '
    ' . esc_html__('Keyword', 'ai-auto-tool') . '' . esc_html__('Status', 'ai-auto-tool') . '' . esc_html__('Priority', 'ai-auto-tool') . '' . esc_html__('Tags', 'ai-auto-tool') . '' . esc_html__('Created', 'ai-auto-tool') . '' . esc_html__('Completed', 'ai-auto-tool') . '' . esc_html__('Processing Time', 'ai-auto-tool') . '' . esc_html__('Actions', 'ai-auto-tool') . '
    ' . esc_html($keyword->keyword) . '' . $status_icon . ' ' . esc_html(ucfirst($keyword->status)) . '' . $priority_badge . '' . $this->format_tags_display($keyword->tags) . '' . esc_html(date('Y-m-d H:i', strtotime($keyword->created_at))) . '' . ($keyword->processed_at ? esc_html(date('Y-m-d H:i', strtotime($keyword->processed_at))) : '' . esc_html__('Not completed', 'ai-auto-tool') . '' ) . '' . esc_html($processing_time) . ''; if ($keyword->status == 'pending') { $html .= ''; } if ($keyword->status == 'error') { $html .= ''; } if ($keyword->post_id > 0) { $html .= ''; } $html .= '
    ' . esc_html__('No keywords found', 'ai-auto-tool') . '
    '; $html .= '
    '; // Pagination if ($total_pages > 1) { $html .= $this->render_pagination($page, $total_pages, $filter, $search); } return $html; } private function render_pagination($current_page, $total_pages, $filter, $search) { $html = '
    '; $html .= '
    '; $html .= '' . sprintf(esc_html__('Page %d of %d', 'ai-auto-tool'), $current_page, $total_pages) . ''; $html .= '
    '; $html .= '
    '; // Previous button if ($current_page > 1) { $html .= ''; } // Page numbers $start_page = max(1, $current_page - 2); $end_page = min($total_pages, $current_page + 2); for ($i = $start_page; $i <= $end_page; $i++) { $active_class = ($i == $current_page) ? 'active' : ''; $html .= ''; } // Next button if ($current_page < $total_pages) { $html .= ''; } $html .= '
    '; $html .= '
    '; return $html; } private function validate_and_fix_content($content) { // Final validation and cleanup $issues_found = array(); // Check for common markdown issues if (strpos($content, '```') !== false) { $issues_found[] = 'Found markdown code blocks'; $content = preg_replace('/```[a-zA-Z]*\n(.*?)\n```/s', '

    $1

    ', $content); } if (strpos($content, '
    ]*>/', '

    ', $content); $content = preg_replace('/<\/code><\/pre>/', '

    ', $content); $content = preg_replace('/
    /', '

    ', $content); $content = preg_replace('/<\/code><\/pre>/', '

    ', $content); } if (strpos($content, 'language-') !== false) { $issues_found[] = 'Found language attributes'; $content = preg_replace('/class="[^"]*language-[^"]*"/', '', $content); } // Check for DOCTYPE and HTML document tags if (strpos($content, ']*>/i', '', $content); } if (strpos($content, ']*>/i', '', $content); $content = preg_replace('/<\/html>/i', '', $content); } if (strpos($content, ']*>.*?<\/head>/is', '', $content); } if (strpos($content, ']*>/i', '', $content); $content = preg_replace('/<\/body>/i', '', $content); } // Check for malformed paragraph tags if (strpos($content, '

    ') !== false) { $issues_found[] = 'Found malformed paragraph tags'; $content = preg_replace('/

    /', '

    ', $content); $content = preg_replace('/<\/p><\/p>/', '

    ', $content); } // Check for unclosed tags $open_tags = array(); preg_match_all('/<(\/?)([a-zA-Z0-9]+)/', $content, $matches); foreach ($matches[2] as $index => $tag) { if ($matches[1][$index] === '/') { // Closing tag if (end($open_tags) === $tag) { array_pop($open_tags); } } else { // Opening tag (skip self-closing tags) if (!in_array($tag, array('img', 'br', 'hr', 'input', 'meta', 'link'))) { $open_tags[] = $tag; } } } if (!empty($open_tags)) { $issues_found[] = 'Found unclosed tags: ' . implode(', ', $open_tags); // Close any remaining open tags foreach (array_reverse($open_tags) as $tag) { $content .= ""; } } // Ensure minimum content length $text_content = strip_tags($content); if (strlen($text_content) < 500) { $issues_found[] = 'Content too short'; } // Log any issues found if (!empty($issues_found)) { error_log('Keyword Autopost Content Issues: ' . implode(', ', $issues_found)); } // Final cleanup $content = $this->final_content_cleanup($content); return $content; } private function final_content_cleanup($content) { // Remove any remaining DOCTYPE and HTML document elements $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/<\/html>/i', '', $content); $content = preg_replace('/]*>.*?<\/head>/is', '', $content); $content = preg_replace('/]*>/i', '', $content); $content = preg_replace('/<\/body>/i', '', $content); // Remove any remaining markdown artifacts $content = str_replace(['```', '`'], '', $content); // Fix any double spaces $content = preg_replace('/\s{2,}/', ' ', $content); // Fix any double line breaks $content = preg_replace('/\n\s*\n/', "\n", $content); // Ensure proper spacing around HTML tags $content = preg_replace('/>\s+<', $content); // Remove any empty paragraphs $content = preg_replace('/

    \s*<\/p>/', '', $content); // Remove any malformed paragraph tags $content = preg_replace('/

    /', '

    ', $content); $content = preg_replace('/<\/p><\/p>/', '

    ', $content); // Ensure content starts and ends properly $content = trim($content); // Add a final paragraph wrapper if content doesn't start with a tag if (!preg_match('/^' . $content . '

    '; } return $content; } private function build_order_by_clause($sort_order) { switch ($sort_order) { case 'recent-completed': return "ORDER BY CASE WHEN status = 'completed' THEN 1 WHEN status = 'processing' THEN 2 WHEN status = 'pending' THEN 3 WHEN status = 'error' THEN 4 END, CASE WHEN status = 'completed' THEN processed_at ELSE created_at END DESC"; case 'oldest-first': return "ORDER BY created_at ASC"; case 'newest-first': return "ORDER BY created_at DESC"; case 'priority': return "ORDER BY priority DESC, created_at ASC"; default: return "ORDER BY CASE WHEN status = 'completed' THEN 1 WHEN status = 'processing' THEN 2 WHEN status = 'pending' THEN 3 WHEN status = 'error' THEN 4 END, CASE WHEN status = 'completed' THEN processed_at ELSE created_at END DESC"; } } private function generate_tags_from_content($content, $keyword, $language) { $bardGenContent = new BardGenContent(); // Extract text content for analysis $text_content = strip_tags($content); // Limit content length for API call $text_content = substr($text_content, 0, 2000); $prompt = "Analyze this article content and generate 5-8 relevant tags for SEO and content organization. Article keyword: '{$keyword}' Language: {$language} Content preview: " . substr($text_content, 0, 500) . "... Requirements: - Generate 5-8 relevant tags - Tags should be related to the main keyword and content topics - Use single words or short phrases (2-3 words max) - Separate tags with commas - Write in {$language} - Focus on SEO-friendly terms - Include the main keyword and related terms - Avoid generic terms like 'article', 'content', 'information' Return only the tags separated by commas, no additional text."; $tags_response = $bardGenContent->bardcontentfull($prompt, $language); if (!$tags_response) { // Fallback: return keyword-based tags return $keyword; } // Clean up the response $tags = trim($tags_response); // Remove any HTML tags that might be returned $tags = strip_tags($tags); // Remove quotes, extra punctuation $tags = str_replace(['"', "'", ';', '.'], '', $tags); // Split by commas and clean each tag $tag_array = array_map('trim', explode(',', $tags)); // Filter out empty tags and limit to 8 tags $tag_array = array_filter($tag_array, function($tag) { return !empty($tag) && strlen($tag) > 1; }); // Limit to 8 tags maximum $tag_array = array_slice($tag_array, 0, 8); // If no tags generated, use the keyword if (empty($tag_array)) { return $keyword; } return implode(',', $tag_array); } private function format_tags_display($tags) { if (empty($tags)) { return '' . esc_html__('No tags', 'ai-auto-tool') . ''; } $tag_array = array_map('trim', explode(',', $tags)); $tag_array = array_filter($tag_array, function($tag) { return !empty($tag) && strlen($tag) > 1; }); if (empty($tag_array)) { return '' . esc_html__('No tags', 'ai-auto-tool') . ''; } $formatted_tags = array(); foreach ($tag_array as $tag) { $formatted_tags[] = '' . esc_html($tag) . ''; } return implode(' ', $formatted_tags); } }