'; public $name_plan; /** * Quota Management */ public $limit = AIAUTOTOOL_FREE; private $plan_limit_aiautotool; public $config = array(); /** * Helper Objects */ private $client = null; public $notices = []; public $notice; /** * Constructor - Initialize the Auto Comment feature */ public function __construct() { $this->name_plan = __('Auto Comments By AI', '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, false); // Initialize feature if active if ($this->active == 'true') { $this->init(); } // Register AJAX handlers add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback')); // Register manual comment generation AJAX handler add_action('wp_ajax_aiautotool_manual_generate_comments', array($this, 'manual_generate_comments_callback')); } /** * ======================================== * QUOTA & LIMIT MANAGEMENT * ======================================== */ /** * Check if plugin data exists * * @return bool */ private function aiautotool_has_plugin_data() { return get_option($this->plan_limit_aiautotool) !== false; } /** * Initialize plugin quota data */ private function aiautotool_initialize_plugin_data() { $current_date = date('Y-m-d'); $expiration = date('Y-m-d', strtotime('+1 month', strtotime($current_date))); update_option($this->plan_limit_aiautotool, array( 'start_date' => $current_date, 'expiration' => $expiration )); } /** * Check if usage limit is exceeded * * @return bool */ public function aiautotool_checklimit($config) { return $this->check_quota(); } /** * Check post limit and reset if new month * * @return bool */ public function aiautotool_check_post_limit() { if (!$this->aiautotool_checklimit($this->config)) { $this->show_upgrade_notice(); return false; } $stored_data = get_option($this->plan_limit_aiautotool, array()); $current_date = date('Y-m-d'); // Reset quota if new month if (isset($stored_data['start_date']) && $this->is_new_month($current_date, $stored_data['start_date'])) { $expiration = date('Y-m-d', strtotime('+1 month', strtotime($current_date))); update_option($this->plan_limit_aiautotool, array( 'start_date' => $current_date, 'expiration' => $expiration )); update_option($this->usage_option_name, 0, null, 'no'); } return true; } /** * Check if it's a new month * * @param string $current_date * @param string $start_date * @return bool */ 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); } /** * Update usage counter * * @return int New usage value */ public function aiautotool__update_usage() { $this->aiautotool_check_post_limit(); $current_value = get_option($this->usage_option_name, 0); $new_value = $current_value + 1; // Update only if within limit 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; } /** * Show upgrade notice */ private function show_upgrade_notice() { $title = sprintf( 'AI Auto Tool Limit Quota. Please Upgrade Pro', aiautotool_premium()->get_upgrade_url() ); $this->notice->add_notice($title, 'notice-error', null, true, 'aiautotool'); } /** * ======================================== * INITIALIZATION & SETUP * ======================================== */ /** * Initialize the feature */ function init() { // Initialize plugin data if not exists if (!$this->aiautotool_has_plugin_data()) { $this->aiautotool_initialize_plugin_data(); } $configs = get_option($this->plan_limit_aiautotool, array()); // Setup configuration $this->config = array( 'number_post' => $this->limit, 'usage' => get_option($this->usage_option_name, 0, 'no'), 'time_exprice' => isset($configs['expiration']) ? $configs['expiration'] : '' ); // Premium checks removed - always set unlimited limits $fs = $this->is_premium(); if ($fs && is_object($fs)) { $license = $fs->_get_license(); $expiration = (is_object($license) && isset($license->expiration)) ? $license->expiration : (isset($configs['expiration']) ? $configs['expiration'] : ''); $this->config = array( 'number_post' => -1, 'usage' => get_option($this->usage_option_name, 0, 'no'), 'time_exprice' => $expiration ); } else { // Even if Freemius not loaded, set unlimited $this->config = array( 'number_post' => -1, 'usage' => get_option($this->usage_option_name, 0, 'no'), 'time_exprice' => isset($configs['expiration']) ? $configs['expiration'] : '' ); } // Register hooks add_action('admin_init', array($this, 'init_settings')); add_action('admin_init', array($this, 'aiautotool_check_post_limit')); add_action('admin_notices', array($this, 'display_notices'), 10, 1); // Add meta box for manual comment generation add_action('add_meta_boxes', array($this, 'add_comment_generator_meta_box')); add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts')); // Setup cron if within limit if ($this->aiautotool_checklimit($this->config)) { $this->setup_cron_schedule(); } else { $this->show_upgrade_notice(); } } /** * Setup cron schedule for auto comment generation */ private function setup_cron_schedule() { add_filter('cron_schedules', array($this, 'aiautotool_schedule_autocomment_intervals')); if (!wp_next_scheduled('schedule_create_autocomment_event_new')) { wp_schedule_event(time(), 'aiautotool_schedule_autocomment_intervals', 'schedule_create_autocomment_event_new'); } add_action('schedule_create_autocomment_event_new', array($this, 'schedule_create_autocomments')); } /** * Define custom cron intervals * * @param array $schedules * @return array */ public function aiautotool_schedule_autocomment_intervals($schedules) { $setting = get_option($this->settings_option_name); $current_interval = 5; // Default 5 minutes if (!empty($setting) && isset($setting['time_comment'])) { $current_interval = intval($setting['time_comment']); } $schedules['aiautotool_schedule_autocomment_intervals'] = array( 'interval' => $current_interval * 60, 'display' => 'Schedule create auto Comment' ); return $schedules; } /** * ======================================== * COMMENT GENERATION - AUTO MODE * ======================================== */ /** * Main function: Auto generate comments for posts (Cron Job) */ public function schedule_create_autocomments() { // 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(); } } } $cron_widget = AIAutoTool_Cron_Status_Widget::get_instance(); // Update status - starting $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Searching for posts to comment...', 'aiautotool-cron-widget'), 'current_post_title' => '', 'progress' => 10, 'cron_type' => __('Auto Comment', 'aiautotool-cron-widget') )); // Check quota if (!$this->aiautotool_checklimit($this->config)) { $this->show_upgrade_notice(); $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('Usage limit exceeded', 'aiautotool-cron-widget'), 'current_post_title' => '', 'progress' => 100, 'cron_type' => __('Auto Comment', 'aiautotool-cron-widget') )); return false; } // Get post to process $post = $this->get_next_post_for_comment(); if (!$post) { $this->notice->add_notice( __('No Post find', 'ai-auto-tool'), 'notice-info', null, true, $this->name_plan ); $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('No posts found to comment', 'aiautotool-cron-widget'), 'current_post_title' => '', 'progress' => 100, 'cron_type' => __('Auto Comment', 'aiautotool-cron-widget') )); return; } // Generate comments for the post $result = $this->generate_comments_for_post($post, $cron_widget); if ($result) { $this->aiautotool__update_usage(); } } /** * Get next post for comment generation * * @return object|null WP_Post object or null */ private function get_next_post_for_comment() { $generated_posts = get_option($this->generated_posts_option, array()); $setting = get_option($this->settings_option_name); // Get post types from settings $post_types = array('post'); if (isset($setting['post_type']) && !empty($setting['post_type'])) { $post_types = array_map('sanitize_key', $setting['post_type']); } // Allow filtering post types $post_types = apply_filters('aiautotool_comment_post_types', $post_types); // Build WP_Query args $args = array( 'post_type' => $post_types, 'post_status' => 'publish', 'posts_per_page' => 1, 'orderby' => 'date', 'order' => 'DESC', 'post__not_in' => !empty($generated_posts) ? $generated_posts : array(), 'ignore_sticky_posts' => true, ); // Allow filtering query args $args = apply_filters('aiautotool_comment_query_args', $args); $query = new WP_Query($args); if ($query->have_posts()) { $post = $query->posts[0]; wp_reset_postdata(); return $post; } wp_reset_postdata(); return null; } /** * Generate comments for a specific post * * @param object $post WP_Post object * @param object $cron_widget Cron status widget instance * @return bool Success status */ private function generate_comments_for_post($post, $cron_widget = null) { $post_id = $post->ID; $post_title = $post->post_title; $post_content = $post->post_content; if ($cron_widget) { $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Found post to comment', 'aiautotool-cron-widget'), 'current_post_title' => get_the_title($post_id), 'progress' => 30, 'cron_type' => __('Auto Comment', 'aiautotool-cron-widget') )); } // Get AI-generated comments $comments_data = $this->get_ai_comments($post_title, $post_content, $post_id, $cron_widget); if (!$comments_data || count($comments_data) == 0) { if ($cron_widget) { $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('Error: Unable to create comments', 'aiautotool-cron-widget'), 'current_post_title' => get_the_title($post_id), 'progress' => 100, 'cron_type' => __('Auto Comment', 'aiautotool-cron-widget') )); } return false; } // Insert comments $success = $this->insert_comments($post, $comments_data, $cron_widget); if ($success) { // Mark post as processed $generated_posts = get_option($this->generated_posts_option, array()); $generated_posts[] = $post_id; update_option($this->generated_posts_option, $generated_posts); if ($cron_widget) { $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('Comment creation completed', 'aiautotool-cron-widget'), 'current_post_title' => $post_title, 'progress' => 100, 'cron_type' => __('Auto Comment', 'aiautotool-cron-widget') )); } } return $success; } /** * Get AI-generated comments for a post * * @param string $post_title * @param string $post_content * @param int $post_id * @param object $cron_widget * @return array|false Array of comment data or false on failure */ private function get_ai_comments($post_title, $post_content, $post_id, $cron_widget = null) { if ($cron_widget) { $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Calling AI for comments...', 'aiautotool-cron-widget'), 'current_post_title' => get_the_title($post_id), 'progress' => 50, 'cron_type' => __('Auto Comment', 'aiautotool-cron-widget') )); } $post = get_post($post_id); $bardGenContent = new BardGenContent(); // Build AI prompt with post context $num_comments = rand(8, 15); // Allow filtering number of comments $num_comments = apply_filters('aiautotool_comment_count', $num_comments, $post); $prompt = $this->build_comment_prompt($post_title, $num_comments, $post); // Get language - check multiple sources $lang = get_post_meta($post_id, 'lang', true); // Try to detect language from site locale if not set if (empty($lang)) { $site_locale = get_locale(); $lang_map = array( 'vi' => 'Vietnamese', 'en' => 'English', 'es' => 'Spanish', 'fr' => 'French', 'de' => 'German', 'ja' => 'Japanese', 'ko' => 'Korean', 'zh' => 'Chinese', ); $lang_code = substr($site_locale, 0, 2); $lang = isset($lang_map[$lang_code]) ? $lang_map[$lang_code] : 'the SAME LANGUAGE as the original text (text between "======")'; } // Allow filtering language $lang = apply_filters('aiautotool_comment_language', $lang, $post); // Call AI API $json_response = $bardGenContent->bardcontentmore($prompt, $lang); // Parse and validate response $comments_data = $this->aiautotool_fixjsonreturn($json_response); // Allow filtering generated comments before insert $comments_data = apply_filters('aiautotool_generated_comments', $comments_data, $post); return $comments_data; } /** * Build prompt for AI comment generation * * @param string $post_title * @param int $num_comments * @param object $post Optional post object for context * @return string */ private function build_comment_prompt($post_title, $num_comments, $post = null) { // Detect post type for customized prompts $post_type = $post ? $post->post_type : 'post'; $comment_type_text = 'comments'; // Customize based on post type switch ($post_type) { case 'product': $comment_type_text = 'product reviews'; break; case 'page': $comment_type_text = 'feedback comments'; break; default: $comment_type_text = 'comments'; break; } $prompt = "The most important: the response must be in the SAME LANGUAGE as the original text (text between \"======\"). Create $num_comments $comment_type_text from readers of the {$post_type}. Requirements: - Each comment must have a different tone: positive, negative, informative, argumentative, ironic, sarcastic, or comical - Commenters must have a \"$post_title\" intellectual level - Most comments should have several syntactic errors (to make them look natural) - Include neutral nicknames (unrelated to the topic) of one to two words separated by spaces - Comments should be realistic and varied in length - Some comments should be short (1-2 sentences), others longer (3-5 sentences)"; // Add specific instructions for products if ($post_type === 'product') { $prompt .= "\n- For products: include ratings perspective (quality, value, satisfaction)"; $prompt .= "\n- Some comments should mention usage experience"; } $prompt .= "\n\nThe {$post_type}'s title is: \"$post_title\" The answer must be in JSON format ONLY, with this exact structure: { \"nickname\": \"commenter name\", \"comment\": \"comment text\", \"tone\": \"tone type\" } Return an array of comment objects."; // Allow filtering the prompt $prompt = apply_filters('aiautotool_comment_prompt', $prompt, $post_title, $num_comments, $post); return $prompt; } /** * Insert comments into database * * @param object $post WP_Post object * @param array $comments_data Array of comment data * @param object $cron_widget Cron status widget instance * @return bool Success status */ private function insert_comments($post, $comments_data, $cron_widget = null) { if ($cron_widget) { $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Processing and saving comments...', 'aiautotool-cron-widget'), 'current_post_title' => $post->post_title, 'progress' => 80, 'cron_type' => __('Auto Comment', 'aiautotool-cron-widget') )); } $success = false; $post_id = $post->ID; $post_type = $post->post_type; // Get timezone $timezone = get_option('timezone_string'); if (!empty($timezone)) { date_default_timezone_set($timezone); } // Calculate timestamp range $post_publish_timestamp = strtotime($post->post_date); $current_timestamp = time(); $comments_inserted = 0; foreach ($comments_data as $comment_data) { $comment_data = (object) $comment_data; // Validate comment data if (!isset($comment_data->nickname) || !isset($comment_data->comment)) { continue; } $comment_author = sanitize_text_field($comment_data->nickname); $comment_content = sanitize_textarea_field($comment_data->comment); // Generate random comment timestamp $comment_timestamp = mt_rand($post_publish_timestamp, $current_timestamp); // Prepare base comment data $commentdata = array( 'comment_author' => $comment_author, 'comment_content' => $comment_content, 'comment_date' => date('Y-m-d H:i:s', $comment_timestamp), 'comment_date_gmt' => gmdate('Y-m-d H:i:s', $comment_timestamp), 'comment_post_ID' => $post_id, 'comment_parent' => 0, 'comment_approved' => 1, 'comment_author_email' => '', 'comment_author_url' => '', 'comment_author_IP' => '', 'comment_agent' => 'AI Auto Tool', ); // Customize comment type based on post type $comment_type = $this->get_comment_type_for_post_type($post_type); if ($comment_type) { $commentdata['comment_type'] = $comment_type; } // Allow filtering comment data before insert $commentdata = apply_filters('aiautotool_before_insert_comment', $commentdata, $post, $comment_data); // Insert comment $comment_id = wp_insert_comment($commentdata); if ($comment_id) { $success = true; $comments_inserted++; // Add meta to identify AI-generated comments add_comment_meta($comment_id, '_aiautotool_generated', true); add_comment_meta($comment_id, '_aiautotool_generated_date', current_time('mysql')); add_comment_meta($comment_id, '_aiautotool_post_type', $post_type); // Store tone if available if (isset($comment_data->tone)) { add_comment_meta($comment_id, '_aiautotool_comment_tone', $comment_data->tone); } // Fire action after comment inserted do_action('aiautotool_after_insert_comment', $comment_id, $post, $comment_data); } } if ($success && $comments_inserted > 0) { // Show notice with count $message = sprintf( 'Generated %1$d AI comments for %2$s: %4$s', $comments_inserted, $post_type, get_permalink($post_id), $post->post_title ); $this->notice->add_notice($message, 'notice-info', null, true, $this->name_plan); // Fire action after all comments inserted do_action('aiautotool_after_generate_comments', $post_id, $comments_inserted, $post); } return $success; } /** * Get comment type for specific post type * * @param string $post_type * @return string|null Comment type or null */ private function get_comment_type_for_post_type($post_type) { $comment_types = array( 'product' => 'review', // WooCommerce 'download' => 'review', // Easy Digital Downloads ); // Allow filtering comment types $comment_types = apply_filters('aiautotool_comment_types', $comment_types); return isset($comment_types[$post_type]) ? $comment_types[$post_type] : null; } /** * ======================================== * META BOX & MANUAL GENERATION UI * ======================================== */ /** * Add meta box for comment generation in post editor */ public function add_comment_generator_meta_box() { $setting = get_option($this->settings_option_name); $post_types = array('post'); if (isset($setting['post_type']) && !empty($setting['post_type'])) { $post_types = $setting['post_type']; } foreach ($post_types as $post_type) { add_meta_box( 'aiautotool_comment_generator', ' ' . __('AI Comment Generator', 'ai-auto-tool'), array($this, 'render_comment_generator_meta_box'), $post_type, 'side', 'default' ); } } /** * Render meta box content * * @param WP_Post $post Current post object */ public function render_comment_generator_meta_box($post) { wp_nonce_field('aiautotool_generate_comments', 'aiautotool_comment_nonce'); // Check if post is published $is_published = $post->post_status === 'publish'; $has_content = !empty($post->post_title) && !empty($post->post_content); // Get existing comments count $comments_count = wp_count_comments($post->ID); $approved_comments = $comments_count->approved; // Check if already generated $generated_posts = get_option($this->generated_posts_option, array()); $already_generated = in_array($post->ID, $generated_posts); ?>
active == "true") { echo ''; } } /** * Render feature box */ public function render_feature() { // Load feature descriptions require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php'; $autoToolBox = new AutoToolBox( $this->icon . ' ' . $this->name_plan, AiAutoTool_Feature_Descriptions::get('auto_comment'), "https://doc.aiautotool.com/features/auto-comment", $this->active_option_name, $this->active, plugins_url('../../images/logo.svg', __FILE__) ); echo $autoToolBox->generateHTML(); } /** * Render usage plan info */ 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' => [], ] ); } } /** * Section callback */ public function section_callback() { echo '' . esc_html__('Configure auto comment generation settings.', 'ai-auto-tool') . '
'; } /** * Display admin notices */ public function display_notices() { $screen = get_current_screen(); $stored = get_option('aiautotool_submitindex_notices', []); $this->notices = array_merge($stored, $this->notices); delete_option('aiautotool_submitindex_notices'); foreach ($this->notices as $notice) { if (!empty($notice['show_on']) && is_array($notice['show_on']) && !in_array($screen->id, $notice['show_on'], true)) { continue; } $class = 'notice instant-indexing-notice ' . $notice['class']; printf( '%2$s
config['usage']); ?> config['number_post'] != -1): ?> / config['number_post']); ?> /