'; private $client = null; public $notices = []; public $limit = AIAUTOTOOL_FREE; private $plan_limit_aiautotool ; public $name_plan ; public $config = array(); public $notice ; public $aiautotool_setting_suggest_post_draft; public $arr_source_ai_model = array( 'Cloudfalre'=>array( '@cf/lykon/dreamshaper-8-lcm', '@cf/bytedance/stable-diffusion-xl-lightning' ), 'Huggingface'=>array( 'stabilityai/stable-diffusion-3-medium-diffusers', 'stablediffusionapi/realistic-stock-photo' ) ); public function __construct() { $this->name_plan = __('AI Sugges new Post','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); if ($this->active=='true') { $this->init(); } add_action('wp_ajax_update_active_option_canonical_'.$this->active_option_name, array($this, 'update_active_option_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() { if (!$this->aiautotool_checklimit($this->config)) { $this->notice->add_notice( AIAUTOTOOL_TITLE_UPGRADE, 'notice-error', null, true, 'aiautotool' ); return false; } $stored_data = get_option($this->plan_limit_aiautotool, array()); $current_date = date('Y-m-d'); if ($this->is_new_month($current_date, $stored_data['start_date'])) { // Nếu đã qua một tháng, đặt lại số lượng bài đăng và ngày bắt đầu $expiration = strtotime('+1 month', strtotime($current_date)); $expiration = date('Y-m-d', $expiration); update_option($this->plan_limit_aiautotool, array( 'start_date' => $current_date,'expiration'=>$expiration)); update_option($this->usage_option_name, 0,null, 'no'); } } private function is_new_month($current_date, $start_date) { $current_month = date('m', strtotime($current_date)); $start_month = date('m', strtotime($start_date)); return ($current_month != $start_month); } public function aiautotool_checklimit($config) { return $this->check_quota(); } public function aiautotool__update_usage() { $this->aiautotool_check_post_limit(); // Get the current usage value $current_value = get_option($this->usage_option_name, 0); // Increment the value by 1 $new_value = $current_value + 1; if($this->config['number_post']!=-1){ if($this->config['number_post'] >= $new_value){ update_option($this->usage_option_name, $new_value, 'no'); } }else{ update_option($this->usage_option_name, $new_value, 'no'); } return $new_value; } public function render_plan(){ if ($this->active=='true') { $quota = $this->config['number_post'] == -1 ? 'Unlimited' : esc_html($this->config['number_post']); echo wp_kses( '
' . $this->icon . ' ' . esc_html($this->name_plan) . ': Usage: ' . esc_html($this->config['usage']) . '
', [ 'p' => [], 'i' => ['class' => []], 'strong' => [], ] ); } } public function update_active_option_callback() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403)); } if (isset($_POST['active'])) { $active = sanitize_text_field($_POST['active']); update_option($this->active_option_name, $active,null, 'no'); print_r($active); } wp_die(); } function init(){ $configs = get_option($this->plan_limit_aiautotool, array()); $this->aiautotool_setting_suggest_post_draft = get_option('aiautotool_setting_suggest_post_draft'); if (!$this->aiautotool_has_plugin_data()) { $this->aiautotool_initialize_plugin_data(); $configs = get_option($this->plan_limit_aiautotool, array()); } if(isset($configs['expiration'])){ $this->config = array( 'number_post'=>$this->limit, 'usage'=>get_option($this->usage_option_name, 0, 'no'), 'time_exprice'=>$configs['expiration'] ); }else{ $this->config = array( 'number_post'=>$this->limit, 'usage'=>get_option($this->usage_option_name, 0, 'no'), 'time_exprice'=>'' ); } // 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'] : '' ); } add_action('admin_init', array($this, 'init_settings')); add_action('admin_init', array($this, 'aiautotool_check_post_limit')); add_action( 'admin_notices', [ $this, 'display_notices' ], 10, 1 ); if ($this->aiautotool_checklimit($this->config)) { add_filter('cron_schedules', array($this, 'aiautotool_schedule_suggest_post_draft_intervals')); if (!wp_next_scheduled('schedule_create_draft_suggest_post_event_new')) { wp_schedule_event(time(), 'aiautotool_schedule_suggest_post_draft_intervals', 'schedule_create_draft_suggest_post_event_new'); } add_action('schedule_create_draft_suggest_post_event_new', array($this, 'schedule_create_draft_suggest_post')); $setting = get_option('aiautotool_setting_suggest_post_draft'); }else{ $this->notice->add_notice( AIAUTOTOOL_TITLE_UPGRADE, 'notice-error', null, true, 'aiautotool' ); } } public function ai_autotool_add_meta_box() { // add_meta_box( // 'ai_autotool_meta_box', // ID of the metabox // 'AI AutoTool Image Creator', // Title of the metabox // array($this,'ai_autotool_meta_box_content'), // Callback function // 'post', // Post type where the metabox will appear (you can change it to 'page' or custom post types if needed) // 'side', // Context (normal, side, advanced) // 'high' // Priority (default, low, high) // ); } public function ai_autotool_meta_box_content($post) { } public function ai_autotool_save_meta_box_data($post_id) { } public function suggest_prompt() { check_ajax_referer('aiautotool_nonce', 'security'); $title = sanitize_text_field($_POST['title']); $prompt = $this->find_prompt_suggestion($title); header('Content-Type: application/json; charset=utf-8'); echo json_encode(array('prompt' => $prompt)); wp_die(); } private function find_prompt_suggestion($title) { return $this->find_prompt($title,''); } public function aiautotool_schedule_suggest_post_draft_intervals($schedules) { $setting = get_option('aiautotool_setting_suggest_post_draft'); $current_interval = 5; if(!empty($setting)){ if(isset($setting['time_suggest_post_draft'])){ $current_interval = $setting['time_suggest_post_draft']; } } $schedules['aiautotool_schedule_suggest_post_draft_intervals'] = array( 'interval' => $current_interval* 60, 'display' => 'Schedule auto suggest post title' ); return $schedules; } public function schedule_create_draft_suggest_post() { $cron_widget = AIAutoTool_Cron_Status_Widget::get_instance(); // Update cron status - starting $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => 'Đang tìm bài viết để tạo draft...', 'current_post_title' => '', 'progress' => 10, 'cron_type' => 'Auto Suggest' )); if (!$this->aiautotool_checklimit($this->config)) { $this->notice->add_notice( AIAUTOTOOL_TITLE_UPGRADE, 'notice-error', null, true, 'aiautotool' ); // Update status - quota exceeded $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 Suggest', 'aiautotool-cron-widget') )); return false; } global $wpdb; $setting = get_option('aiautotool_setting_suggest_post_draft'); $posttypearr = array('post'); if (isset($setting['post_type'])) { $posttypearr = $setting['post_type']; } // Query lấy ra 20 bài viết ngẫu nhiên $query = " SELECT ID, post_title FROM {$wpdb->prefix}posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY RAND() LIMIT 20"; $result = $wpdb->get_results($query); if ($result) { $titles = array_map(function($post) { return $post->post_title; }, $result); // Update status - calling AI for suggestions $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => 'Đang gọi AI để tạo gợi ý bài viết...', 'current_post_title' => 'Đang xử lý ' . count($titles) . ' bài viết', 'progress' => 40, 'cron_type' => 'Auto Suggest' )); // Gọi function find_sugget_title để lấy dữ liệu JSON $suggestions = $this->find_sugget_title($titles); // Duyệt qua các kết quả và cập nhật title của bài viết thành dạng draft if (is_array($suggestions)) { // Update status - processing suggestions $cron_widget->update_cron_status(array( 'is_running' => true, 'current_task' => __('Processing suggestions...', 'aiautotool-cron-widget'), 'current_post_title' => get_the_title($post_id), 'progress' => 80, 'cron_type' => __('Auto Suggest', 'aiautotool-cron-widget') )); $created_count = 0; foreach ($suggestions as $suggestion) { if (isset($suggestion['title'])) { global $wpdb; // Kiểm tra nếu tiêu đề đã tồn tại $title_exists = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}posts WHERE post_title = %s AND post_status = 'publish' AND post_type = 'post'", $suggestion['title'] )); if ($title_exists == 0) { $user_ids = get_users( array( 'fields' => 'ID', ) ); $random_user_id = $user_ids[array_rand($user_ids)]; $title = ucwords(mb_strtolower(html_entity_decode($suggestion['title']))); $random_user_id = $user_ids[array_rand($user_ids)]; $user_id = $random_user_id; $new_post = array( 'post_title' => $title, 'post_content' => '', // Có thể thêm nội dung nếu cần 'post_author'=>$user_id, 'post_status' => 'draft', 'post_type' => 'post', // Hoặc loại bài viết khác nếu cần ); $post_id = wp_insert_post($new_post); if ($post_id) { $created_count++; if (!empty($suggestion['categorie'])) { $categories = array_map('trim', explode(',', $suggestion['categorie'])); $category_ids = array(); foreach ($categories as $category) { // Kiểm tra xem danh mục đã tồn tại chưa $category_id = term_exists($category, 'category'); if (!$category_id) { // Nếu danh mục chưa tồn tại, tạo mới $category_id = wp_insert_term($category, 'category'); } if (!is_wp_error($category_id)) { $category_ids[] = is_array($category_id) ? $category_id['term_id'] : $category_id; } } if (!empty($category_ids)) { wp_set_post_categories($post_id, $category_ids); } } if (!empty($suggestion['tags'])) { $tags = array_map('trim', explode(',', $suggestion['tags'])); wp_set_post_tags($post_id, $tags); } } } } } // Update status - completed $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('Suggestion creation completed', 'aiautotool-cron-widget'), 'current_post_title' => get_the_title($post_id), 'progress' => 100, 'cron_type' => __('Auto Suggest', 'aiautotool-cron-widget') )); $this->aiautotool__update_usage(); } else { // Update status - error $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('Error: Unable to create suggestions', 'aiautotool-cron-widget'), 'current_post_title' => get_the_title($post_id), 'progress' => 100, 'cron_type' => __('Auto Suggest', 'aiautotool-cron-widget') )); } } else { // No posts found $cron_widget->update_cron_status(array( 'is_running' => false, 'current_task' => __('No posts found to suggest', 'aiautotool-cron-widget'), 'current_post_title' => '', 'progress' => 100, 'cron_type' => 'Auto Suggest' )); } } public function find_sugget_title($titles) { // Check if titles is an array if (!is_array($titles)) { return json_encode(array('error' => 'Invalid input')); } $setting = get_option('aiautotool_setting_suggest_post_draft'); $number_post_title_draft = $setting['number_post_title_draft']; // Create the prompt string using the titles $prompt = "the response must be in the SAME LANGUAGE as the original list of articles. Please suggest ".$number_post_title_draft." new titles for the following list of articles:\n\n"; foreach ($titles as $title) { $prompt .= "- $title\n"; } $prompt .= 'the response must be in the SAME LANGUAGE as the original list of articles. The answers must only be in JSON format, with this exact format, you have to fill empty values,Each item in comments has the form { \"title\": \"\",\"langue\": \"\",\"categorie\": \"\",\"tags\": \"\" }. the response must be in the SAME LANGUAGE as the original list of articles. If the title has a date (day, month, or year), the result must contain the latest year.The language of categorie and tags must match the language of the title.'; $bardGenContent = new BardGenContent(); // Use default language if setting doesn't have language specified $lang = isset($setting['lang']) ? $setting['lang'] : get_option('aiautotool_default_language', 'vi'); $json = $bardGenContent->bardcontentmore($prompt, $lang); $json = $this->aiautotool_fixjsonreturn($json); // print_r($json); if($json){ return $json; }else{ return false; } } private function generate_thumbnail_image($title, $content) { if($title){ $setting = get_option('aiautotool_setting_suggest_post_draft'); if($setting['source_img_ai']=='Cloudfalre'){ if(!empty($setting['id_account_cl'])&&!empty($setting['apikey'])){ $imgCloudflare = new ImgCloudflare($setting['id_account_cl'], $setting['apikey']); $image = $imgCloudflare->get_img($this->find_prompt($title,$content),$setting['model_ai']); if ($image) { $upload_dir = wp_upload_dir(); $filename = sanitize_file_name(strtolower($title)).'_'.time(). '.png'; if(wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } file_put_contents($file, $image); $image_size = @getimagesize($file); if ($image_size !== false) { return $file; }else{ return false; } } } }else if($setting['source_img_ai']=='Huggingface'){ if (!empty($setting['hunggingfacetoken'])&&!empty($setting['hunggingface_model_ai'])) { $imgCloudflare = new ImgCloudflare('',''); $image = $imgCloudflare->hungingfaceimg($setting['hunggingfacetoken'], $this->find_prompt($title,$content), $setting['hunggingface_model_ai']); if ($image) { $upload_dir = wp_upload_dir(); $filename = sanitize_file_name(strtolower($title)).'_'.time(). '.png'; if(wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } file_put_contents($file, $image); $image_size = @getimagesize($file); if ($image_size !== false) { return $file; }else{ return false; } } } return false; } return false; } } public function find_prompt($title,$content){ $string = "You are a prompt engineer. Your task is to carefully analyze the provided blog title and content. And create a prompt for the stable-diffusion-xl-lightning model, enabling the generation of a visual that matches the text. This prompt should concisely capture the essence, main themes, and nuances of the provided blog post, aiming to facilitate the creation of the most accurate and engaging image that reflects the main message and context without being overly complex or detailed. The prompt must be that is simple enough to generate an image and not too detailed. You must create a different prompt each time a request is sent. You must generate only a prompt. The prompt must be in English. Title: '{$title}, content : '".strip_tags($content); $bardGenContent = new BardGenContent(); // Use default language if setting doesn't have language specified $setting = get_option('aiautotool_setting_suggest_post_draft'); $lang = isset($setting['lang']) ? $setting['lang'] : get_option('aiautotool_default_language', 'vi'); $json = $bardGenContent->bardcontentmore($string, $lang); if($json){ return $json; }else{ return "Thumbnail for Article: ".$title; } } private function set_post_thumbnail($post_id, $image_url) { $upload_dir = wp_upload_dir(); $image_data = file_get_contents($image_url); $filename = basename($image_url); if(wp_mkdir_p($upload_dir['path'])) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } file_put_contents($file, $image_data); $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment($attachment, $file, $post_id); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata($attach_id, $file); wp_update_attachment_metadata($attach_id, $attach_data); // Set as post thumbnail set_post_thumbnail($post_id, $attach_id); } private function aiautotool_product_review(){ } private function aiautotool_fixcontent_PostContent($content) { $cleaned_content = strip_tags($content); // $cleaned_content = preg_replace('/[^\w\s]/', '', $cleaned_content); $cleaned_content = substr($cleaned_content, 0, 1000); return $cleaned_content; } public function aiautotool_fixjsonreturn($result){ // Check if result is a string, if not convert to string or return early if (!is_string($result)) { // If it's already an array, return it directly if (is_array($result)) { return $result; } // Try to convert to string if (is_object($result) || is_numeric($result) || is_bool($result)) { $result = (string) $result; } else { // If we can't convert, return empty array return array(); } } // If result is empty string, return empty array if (empty($result)) { return array(); } $pattern = '/\{(?:[^{}]|(?R))*\}/'; preg_match_all($pattern, $result, $matches); $arritem = array(); if (!isset($matches[0]) || empty($matches[0])) { return array(); } foreach ($matches[0] as $jsonString) { $decodedJson = json_decode($jsonString, true); if ($decodedJson !== null) { if(isset($decodedJson['comments'])) { foreach($decodedJson['comments'] as $item){ $arritem[] = $item; } }else{ $arritem[] = $decodedJson; } } else { // Don't return null on first error, continue processing other matches continue; } } // Return empty array if no valid JSON found, instead of null return empty($arritem) ? array() : $arritem; } 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 ) ) { return; } $class = 'notice instant-indexing-notice ' . $notice['class']; printf( '%2$s
' . esc_html__('Enter information and select Post Types.', 'ai-auto-tool') . '
'; } // Callback cho textarea thông tin public function submitindex_field_callback() { $value = get_option('aiautotool_setting_suggest_post_draft'); echo ''; } // Callback cho danh sách Post Types public function post_types_field_callback() { $post_types = get_post_types(array('public' => true), 'objects'); $selected_post_types = get_option('aiautotool_setting_post_types', array()); foreach ($post_types as $post_type) { $checked = in_array($post_type->name, $selected_post_types) ? 'checked' : ''; // Không cần "checked=\"checked\"" echo ' ' . esc_html($post_type->label) . '