init_hooks(); } /** * Initialize hooks and actions. */ private function init_hooks() { // Prevent fatals on old versions of WordPress if (!class_exists('WP_REST_Controller')) { return; } // Load plugin files $this->load_dependencies(); // Allow people to change what capability is required to use this plugin $this->capability = apply_filters('aitm_capability', $this->capability); // Initialize components add_action('init', array($this, 'init')); add_action('rest_api_init', array($this, 'init_rest_api')); add_action('admin_menu', array($this, 'add_admin_menu')); add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts')); add_action('wp_enqueue_scripts', array($this, 'frontend_enqueue_scripts')); add_action('admin_init', array($this, 'register_settings')); // Activation and deactivation hooks register_activation_hook(__FILE__, array($this, 'activate')); register_deactivation_hook(__FILE__, array($this, 'deactivate')); // AJAX handlers add_action('wp_ajax_aitm_get_attachment_ids', array($this, 'ajax_get_attachment_ids')); add_action('wp_ajax_aitm_get_featured_image_ids', array($this, 'ajax_get_featured_image_ids')); add_action('wp_ajax_aitm_get_failed_attachment_ids', array($this, 'ajax_get_failed_attachment_ids')); add_action('wp_ajax_aitm_get_posts_without_featured_images', array($this, 'ajax_get_posts_without_featured_images')); add_action('wp_ajax_aitm_get_statistics', array($this, 'ajax_get_statistics')); add_action('wp_ajax_aitm_regenerate_thumbnails', array($this, 'ajax_regenerate_thumbnails')); add_action('wp_ajax_aitm_generate_featured_image', array($this, 'ajax_generate_featured_image')); add_action('wp_ajax_aitm_delete_stat_entry', array($this, 'ajax_delete_stat_entry')); add_action('wp_ajax_aitm_clear_statistics', array($this, 'ajax_clear_statistics')); add_action('wp_ajax_aitm_save_settings', array($this, 'ajax_save_settings')); add_action('wp_ajax_aitm_test_ai_service', array($this, 'ajax_test_ai_service')); add_action('wp_ajax_aitm_check_cron_settings', array($this, 'ajax_check_cron_settings')); add_action('wp_ajax_aitm_add_to_cron_queue', array($this, 'ajax_add_to_cron_queue')); // Cron hooks add_action('aitm_cron_regenerate_thumbnails', array($this, 'cron_regenerate_thumbnails')); add_action('aitm_cron_process_queue', array($this, 'cron_process_queue')); // Media library integration add_filter('media_row_actions', array($this, 'add_regenerate_link_to_media_list_view'), 10, 2); add_action('attachment_submitbox_misc_actions', array($this, 'add_button_to_media_edit_page'), 99); add_filter('attachment_fields_to_edit', array($this, 'add_button_to_edit_media_modal_fields_area'), 99, 2); add_action('admin_head-upload.php', array($this, 'add_bulk_actions_via_javascript')); add_action('admin_action_bulk_regenerate_thumbnails', array($this, 'bulk_action_handler')); add_action('admin_action_-1', array($this, 'bulk_action_handler')); } /** * Load plugin dependencies. */ private function load_dependencies() { // Load interface first require_once AITM_PLUGIN_DIR . 'includes/class-aitm-ai-service-interface.php'; // Load core classes require_once AITM_PLUGIN_DIR . 'includes/class-aitm-regenerator.php'; require_once AITM_PLUGIN_DIR . 'includes/class-aitm-rest-controller.php'; require_once AITM_PLUGIN_DIR . 'includes/class-aitm-ai-service-manager.php'; require_once AITM_PLUGIN_DIR . 'includes/class-aitm-statistics-manager.php'; require_once AITM_PLUGIN_DIR . 'includes/class-aitm-cron-manager.php'; require_once AITM_PLUGIN_DIR . 'includes/class-aitm-settings-manager.php'; // Load AI service implementations require_once AITM_PLUGIN_DIR . 'includes/class-aitm-ai-dall-e.php'; require_once AITM_PLUGIN_DIR . 'includes/class-aitm-ai-midjourney.php'; } /** * Initialize plugin components. */ public function init() { // Initialize managers $this->ai_service_manager = new AITM_AI_Service_Manager(); $this->statistics_manager = new AITM_Statistics_Manager(); $this->cron_manager = new AITM_Cron_Manager(); // Load text domain // Note: load_plugin_textdomain() is deprecated since WP 4.6 // WordPress automatically loads translations from the wordpress.org repository // load_plugin_textdomain('ai-thumbnails-maker', false, dirname(plugin_basename(__FILE__)) . '/languages'); } /** * Initialize REST API. */ public function init_rest_api() { $this->rest_api = new AITM_REST_Controller(); $this->rest_api->register_routes(); } /** * Register plugin settings. */ public function register_settings() { // General settings register_setting('aitm_settings', 'aitm_settings', array( 'sanitize_callback' => array($this, 'sanitize_general_settings') )); // AI settings register_setting('aitm_ai_settings', 'aitm_ai_settings', array( 'sanitize_callback' => array($this, 'sanitize_ai_settings') )); } /** * Sanitize general settings. */ public function sanitize_general_settings($input) { $sanitized = array(); $sanitized['enable_ai_generation'] = isset($input['enable_ai_generation']) ? (bool) $input['enable_ai_generation'] : false; $sanitized['default_ai_service'] = sanitize_text_field($input['default_ai_service'] ?? 'dall_e_3'); $sanitized['auto_regenerate'] = isset($input['auto_regenerate']) ? (bool) $input['auto_regenerate'] : false; $sanitized['enable_cron_processing'] = isset($input['enable_cron_processing']) ? (bool) $input['enable_cron_processing'] : false; $sanitized['cron_interval'] = sanitize_text_field($input['cron_interval'] ?? 'aitm_every_minute'); $sanitized['stats_update_interval'] = max(10, min(300, intval($input['stats_update_interval'] ?? 30))); $sanitized['max_retries'] = max(1, min(10, intval($input['max_retries'] ?? 3))); $sanitized['thumbnail_quality'] = max(1, min(100, intval($input['thumbnail_quality'] ?? 90))); return $sanitized; } /** * Sanitize AI settings. */ public function sanitize_ai_settings($input) { $sanitized = array(); // DALL-E 3 settings if (isset($input['dall_e_3'])) { $sanitized['dall_e_3'] = array( 'api_key' => sanitize_text_field($input['dall_e_3']['api_key'] ?? ''), 'model' => sanitize_text_field($input['dall_e_3']['model'] ?? 'dall-e-3'), 'size' => sanitize_text_field($input['dall_e_3']['size'] ?? '1024x1024'), 'quality' => sanitize_text_field($input['dall_e_3']['quality'] ?? 'standard'), 'style' => sanitize_text_field($input['dall_e_3']['style'] ?? 'vivid'), ); } // Midjourney settings if (isset($input['midjourney'])) { $sanitized['midjourney'] = array( 'api_key' => sanitize_text_field($input['midjourney']['api_key'] ?? ''), 'server_id' => sanitize_text_field($input['midjourney']['server_id'] ?? ''), 'channel_id' => sanitize_text_field($input['midjourney']['channel_id'] ?? ''), 'size' => sanitize_text_field($input['midjourney']['size'] ?? '1024x1024'), ); } return $sanitized; } /** * Add admin menu pages. */ public function add_admin_menu() { // Main plugin page with tabs add_options_page( __('AI Thumbnails Maker', 'ai-thumbnails-maker'), __('AI Thumbnails Maker', 'ai-thumbnails-maker'), $this->capability, 'ai-thumbnails-maker', array($this, 'admin_page_main') ); } /** * Enqueue admin scripts and styles. */ public function admin_enqueue_scripts($hook_suffix) { // Load bulk actions script on upload.php (Media Library) if ($hook_suffix === 'upload.php') { wp_enqueue_script( 'aitm-bulk-actions', AITM_PLUGIN_URL . 'assets/js/admin-interactions.min.js', array('jquery'), $this->version, true ); wp_localize_script('aitm-bulk-actions', 'aitm_admin', array( 'strings' => array( 'regenerate_with_ai' => __('Regenerate with AI', 'ai-thumbnails-maker'), ) )); return; } // Only load on our plugin pages if (strpos($hook_suffix, 'ai-thumbnails') === false) { return; } wp_enqueue_script( 'aitm-admin', AITM_PLUGIN_URL . 'assets/js/admin.min.js', array('jquery', 'wp-api-request'), $this->version, true ); // Enqueue admin interactions script wp_enqueue_script( 'aitm-admin-interactions', AITM_PLUGIN_URL . 'assets/js/admin-interactions.min.js', array('jquery', 'aitm-admin'), $this->version, true ); wp_enqueue_style( 'aitm-admin', AITM_PLUGIN_URL . 'assets/css/admin.min.css', array(), $this->version ); // Localize script wp_localize_script('aitm-admin', 'aitm_admin', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('aitm_nonce'), 'reset_nonce' => wp_create_nonce('aitm_save_settings'), 'strings' => array( 'loading' => __('Loading...', 'ai-thumbnails-maker'), 'error' => __('Error occurred', 'ai-thumbnails-maker'), 'success' => __('Success', 'ai-thumbnails-maker'), 'confirm_regenerate' => __('Are you sure you want to regenerate thumbnails?', 'ai-thumbnails-maker'), 'confirm_reset' => __('Are you sure you want to reset all settings to defaults? This cannot be undone.', 'ai-thumbnails-maker'), 'regenerating' => __('Regenerating...', 'ai-thumbnails-maker'), 'completed' => __('Completed', 'ai-thumbnails-maker'), 'testing' => __('Testing...', 'ai-thumbnails-maker'), 'connection_successful' => __('Connection successful!', 'ai-thumbnails-maker'), 'connection_failed' => __('Connection failed:', 'ai-thumbnails-maker'), 'connection_failed_network' => __('Connection failed: Network error', 'ai-thumbnails-maker'), 'regenerate_with_ai' => __('Regenerate with AI', 'ai-thumbnails-maker'), ) )); } /** * Enqueue frontend scripts and styles. */ public function frontend_enqueue_scripts() { // Only load if needed if (!is_admin()) { // Frontend scripts can be added here if needed } } /** * Main admin page. */ public function admin_page_main() { include AITM_PLUGIN_DIR . 'templates/admin-main.php'; } /** * Settings admin page. */ public function admin_page_settings() { include AITM_PLUGIN_DIR . 'templates/admin-settings.php'; } /** * AI Services admin page. */ public function admin_page_ai_services() { include AITM_PLUGIN_DIR . 'templates/admin-ai-services.php'; } /** * AJAX handler for regenerating thumbnails. */ public function ajax_regenerate_thumbnails() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can($this->capability)) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0; $use_ai = isset($_POST['use_ai']) ? (bool) $_POST['use_ai'] : false; $ai_service = isset($_POST['ai_service']) ? sanitize_text_field(wp_unslash($_POST['ai_service'])) : ''; if (!$attachment_id) { wp_send_json_error(__('Invalid attachment ID.', 'ai-thumbnails-maker')); } $attachment = get_post($attachment_id); if (!$attachment || $attachment->post_type !== 'attachment') { wp_send_json_error(__('Attachment not found.', 'ai-thumbnails-maker')); } if (!wp_attachment_is_image($attachment)) { wp_send_json_error(__('File is not an image.', 'ai-thumbnails-maker')); } $regenerator = AITM_Regenerator::get_instance($attachment); $result = $regenerator->regenerate($use_ai, $ai_service); if (is_wp_error($result)) { wp_send_json_error($result->get_error_message()); } wp_send_json_success(__('Thumbnails regenerated successfully.', 'ai-thumbnails-maker')); } /** * AJAX handler for getting statistics. */ public function ajax_get_statistics() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can($this->capability)) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } $page = isset($_POST['page']) ? intval($_POST['page']) : 1; $per_page = 100; $statistics_manager = new AITM_Statistics_Manager(); $statistics = $statistics_manager->get_statistics($page, $per_page); wp_send_json_success($statistics); } /** * AJAX handler for saving settings. */ public function ajax_save_settings() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can($this->capability)) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } $settings = isset($_POST['settings']) ? array_map('sanitize_text_field', wp_unslash($_POST['settings'])) : array(); $result = update_option('aitm_settings', $settings); if ($result) { wp_send_json_success(__('Settings saved successfully.', 'ai-thumbnails-maker')); } else { wp_send_json_error(__('Failed to save settings.', 'ai-thumbnails-maker')); } } /** * AJAX handler for testing AI service. */ public function ajax_test_ai_service() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can($this->capability)) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } $service = isset($_POST['service']) ? sanitize_text_field(wp_unslash($_POST['service'])) : ''; $result = $this->ai_service_manager->test_service($service); if (is_wp_error($result)) { wp_send_json_error($result->get_error_message()); } else { wp_send_json_success(__('AI service test successful.', 'ai-thumbnails-maker')); } } /** * Cron job handler for regenerating thumbnails. */ public function cron_regenerate_thumbnails() { $this->cron_manager->process_scheduled_regeneration(); } /** * Cron job handler for processing queue. */ public function cron_process_queue() { $this->cron_manager->process_cron_queue(); } /** * Add regenerate link to media list view. */ public function add_regenerate_link_to_media_list_view($actions, $post) { if (!current_user_can($this->capability) || !$this->is_regeneratable($post)) { return $actions; } $url = add_query_arg(array( 'page' => 'ai-thumbnails-maker', 'action' => 'regenerate', 'id' => $post->ID ), admin_url('tools.php')); $actions['regenerate_thumbnails'] = '' . esc_html__('Regenerate with AI', 'ai-thumbnails-maker') . ''; return $actions; } /** * Add regenerate button to media edit page. */ public function add_button_to_media_edit_page() { global $post; if (!current_user_can($this->capability) || !$this->is_regeneratable($post)) { return; } $url = add_query_arg(array( 'page' => 'ai-thumbnails-maker', 'action' => 'regenerate', 'id' => $post->ID ), admin_url('tools.php')); echo '
'; echo '' . esc_html__('Regenerate with AI', 'ai-thumbnails-maker') . ''; echo '
'; } /** * Add regenerate button to edit media modal. */ public function add_button_to_edit_media_modal_fields_area($form_fields, $post) { if (!current_user_can($this->capability) || !$this->is_regeneratable($post)) { return $form_fields; } $url = add_query_arg(array( 'page' => 'ai-thumbnails-maker', 'action' => 'regenerate', 'id' => $post->ID ), admin_url('tools.php')); $form_fields['regenerate_thumbnails'] = array( 'label' => '', 'input' => 'html', 'html' => '' . esc_html__('Regenerate with AI', 'ai-thumbnails-maker') . '', 'show_in_modal' => true, 'show_in_edit' => false, ); return $form_fields; } /** * Add bulk actions via JavaScript. * Bulk actions are now handled in admin-interactions.js */ public function add_bulk_actions_via_javascript() { // Bulk actions are now handled by the admin-interactions.js file // which is enqueued in admin_enqueue_scripts method } /** * Handle bulk action submission. */ public function bulk_action_handler() { if ( empty($_REQUEST['action']) || empty($_REQUEST['action2']) || ('bulk_regenerate_thumbnails' != $_REQUEST['action'] && 'bulk_regenerate_thumbnails' != $_REQUEST['action2']) || empty($_REQUEST['media']) || !is_array($_REQUEST['media']) ) { return; } check_admin_referer('bulk-media'); wp_safe_redirect( add_query_arg( array( 'page' => 'ai-thumbnails-maker', 'ids' => rawurlencode(implode(',', array_map('intval', $_REQUEST['media']))), ), admin_url('tools.php') ) ); exit(); } /** * Check if attachment can be regenerated. */ public function is_regeneratable($post) { if ('site-icon' === get_post_meta($post->ID, '_wp_attachment_context', true)) { return false; } if (wp_attachment_is_image($post)) { return true; } if (function_exists('wp_get_original_image_path')) { $fullsize = wp_get_original_image_path($post->ID); } else { $fullsize = get_attached_file($post->ID); } if (!$fullsize || !file_exists($fullsize)) { return false; } $image_editor_args = array( 'path' => $fullsize, 'methods' => array('resize') ); $file_info = wp_check_filetype($image_editor_args['path']); if (isset($file_info) && $file_info['type']) { $image_editor_args['mime_type'] = $file_info['type']; } return (bool) _wp_image_editor_choose($image_editor_args); } /** * AJAX handler: Get all attachment IDs */ public function ajax_get_attachment_ids() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } $args = array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'post_status' => 'inherit', 'posts_per_page' => -1, 'fields' => 'ids' ); $attachments = get_posts($args); wp_send_json_success($attachments); } /** * AJAX handler: Get featured image IDs */ public function ajax_get_featured_image_ids() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } global $wpdb; $cache_key = 'aitm_featured_image_ids'; $featured_images = wp_cache_get($cache_key, 'aitm_ajax'); if (false === $featured_images) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Query with caching for featured images $featured_images = $wpdb->get_col( "SELECT DISTINCT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_thumbnail_id' AND meta_value != ''" ); wp_cache_set($cache_key, $featured_images, 'aitm_ajax', 300); // Cache for 5 minutes } wp_send_json_success(array_map('intval', $featured_images)); } /** * AJAX handler: Get failed attachment IDs */ public function ajax_get_failed_attachment_ids() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } $statistics_manager = new AITM_Statistics_Manager(); $failed_attachments = $statistics_manager->get_failed_attachment_ids(); wp_send_json_success($failed_attachments); } /** * AJAX handler: Get posts without featured images */ public function ajax_get_posts_without_featured_images() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } // Handle post_types parameter - can be array or comma-separated string $post_types_raw = isset($_POST['post_types']) ? $_POST['post_types'] : 'post'; if (is_string($post_types_raw)) { $post_types = array_map('sanitize_text_field', explode(',', $post_types_raw)); } else { $post_types = array_map('sanitize_text_field', wp_unslash($post_types_raw)); } // Handle special cases if (in_array('custom', $post_types)) { // Get all custom post types $custom_post_types = get_post_types(array('public' => true, '_builtin' => false), 'names'); $post_types = array_merge($post_types, $custom_post_types); $post_types = array_diff($post_types, array('custom')); // Remove 'custom' from array } $args = array( 'post_type' => $post_types, 'post_status' => 'publish', 'meta_query' => array( array( 'key' => '_thumbnail_id', 'compare' => 'NOT EXISTS' ) ), 'posts_per_page' => -1, 'fields' => 'ids' ); $posts = get_posts($args); wp_send_json_success($posts); } /** * AJAX handler: Generate featured image */ public function ajax_generate_featured_image() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; $method = isset($_POST['method']) ? sanitize_text_field(wp_unslash($_POST['method'])) : 'first_image'; $ai_service = isset($_POST['ai_service']) ? sanitize_text_field(wp_unslash($_POST['ai_service'])) : ''; if (!$post_id) { wp_send_json_error(__('Invalid post ID.', 'ai-thumbnails-maker')); } $post = get_post($post_id); if (!$post) { wp_send_json_error(__('Post not found.', 'ai-thumbnails-maker')); } // Check if post already has featured image if (has_post_thumbnail($post_id)) { wp_send_json_error(__('Post already has a featured image.', 'ai-thumbnails-maker')); } $result = $this->generate_featured_image_for_post($post, $method, $ai_service); if (is_wp_error($result)) { wp_send_json_error($result->get_error_message()); } // Get statistics data for the new entry $statistics_manager = new AITM_Statistics_Manager(); $stat_data = $statistics_manager->get_stat_by_id($result['stat_id']); wp_send_json_success(array( 'message' => __('Featured image generated successfully.', 'ai-thumbnails-maker'), 'stat' => $stat_data )); } /** * AJAX handler: Delete statistics entry */ public function ajax_delete_stat_entry() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } $stat_id = isset($_POST['stat_id']) ? intval($_POST['stat_id']) : 0; if (!$stat_id) { wp_send_json_error(__('Invalid statistics entry ID.', 'ai-thumbnails-maker')); } global $wpdb; $table_name = $wpdb->prefix . 'aitm_statistics'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Delete operation, caching not applicable $result = $wpdb->delete($table_name, array('id' => $stat_id), array('%d')); if ($result === false) { wp_send_json_error(__('Failed to delete statistics entry.', 'ai-thumbnails-maker')); } wp_send_json_success(__('Statistics entry deleted successfully.', 'ai-thumbnails-maker')); } /** * AJAX handler: Clear all statistics */ public function ajax_clear_statistics() { check_ajax_referer('aitm_nonce', 'nonce'); if (!current_user_can('manage_options')) { wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'ai-thumbnails-maker')); } global $wpdb; $table_name = $wpdb->prefix . 'aitm_statistics'; $result = $wpdb->query( $wpdb->prepare("TRUNCATE TABLE %i", $table_name) ); if ($result === false) { wp_send_json_error(__('Failed to clear statistics.', 'ai-thumbnails-maker')); } wp_send_json_success(__('Statistics cleared successfully.', 'ai-thumbnails-maker')); } /** * Generate featured image for a post */ public function generate_featured_image_for_post($post, $method, $ai_service) { if ($method === 'first_image') { return $this->generate_featured_from_first_image($post); } elseif ($method === 'ai_generate') { return $this->generate_featured_with_ai($post, $ai_service); } return new WP_Error('invalid_method', __('Invalid generation method.', 'ai-thumbnails-maker')); } /** * Generate featured image from first image in content */ private function generate_featured_from_first_image($post) { $content = $post->post_content; // Find first image in content (with full tag to extract class) preg_match('/]+>/i', $content, $img_tag_matches); if (empty($img_tag_matches[0])) { return new WP_Error('no_image', __('No image found in post content.', 'ai-thumbnails-maker')); } $img_tag = $img_tag_matches[0]; $attachment_id = 0; // Method 1: Try to extract attachment ID from wp-image-{id} class if (preg_match('/wp-image-(\d+)/i', $img_tag, $class_matches)) { $attachment_id = absint($class_matches[1]); // Verify this is a valid attachment if ($attachment_id && get_post_type($attachment_id) !== 'attachment') { $attachment_id = 0; } } // Method 2: Extract src URL and try to find attachment if (!$attachment_id) { preg_match('/src="([^"]+)"/i', $img_tag, $src_matches); if (empty($src_matches[1])) { return new WP_Error('no_image_src', __('No image source found in post content.', 'ai-thumbnails-maker')); } $image_url = $src_matches[1]; // Try to find attachment by URL $attachment_id = attachment_url_to_postid($image_url); // If not found and URL contains wp-content/uploads, try alternative methods if (!$attachment_id && strpos($image_url, 'wp-content/uploads') !== false) { global $wpdb; // Remove size suffix from filename (e.g., -150x150, -300x200) $base_url = preg_replace('/-\d+x\d+(\.[^.]+)$/i', '$1', $image_url); // Search by guid (full URL or base URL) // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $attachment_id = $wpdb->get_var($wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE (guid = %s OR guid = %s) AND post_type = 'attachment' LIMIT 1", $image_url, $base_url )); // If still not found, search by file basename in meta if (!$attachment_id) { $basename = basename($base_url); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $attachment_id = $wpdb->get_var($wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attached_file' AND meta_value LIKE %s LIMIT 1", '%' . $wpdb->esc_like($basename) )); } } // If still not found, try to download image (external URL) if (!$attachment_id) { $attachment_id = $this->create_attachment_from_url($image_url, $post->ID); if (is_wp_error($attachment_id)) { return $attachment_id; } } } // Final check if (!$attachment_id) { return new WP_Error('attachment_not_found', __('Could not find or create attachment from image.', 'ai-thumbnails-maker')); } // Set as featured image set_post_thumbnail($post->ID, $attachment_id); // Log the operation $stat_id = $this->log_featured_generation($post->ID, 'first_image', '', true); return array('success' => true, 'stat_id' => $stat_id); } /** * Generate featured image with AI */ private function generate_featured_with_ai($post, $ai_service) { // Check if AI generation is enabled $settings = get_option('aitm_settings', array()); if (!isset($settings['enable_ai_generation']) || !$settings['enable_ai_generation']) { return new WP_Error('ai_disabled', __('AI generation is disabled.', 'ai-thumbnails-maker')); } // Generate prompt from post title $prompt = $this->generate_ai_prompt_from_title($post->post_title); // Get AI service $ai_service_manager = new AITM_AI_Service_Manager(); $ai_service_instance = $ai_service_manager->get_service($ai_service); if (is_wp_error($ai_service_instance)) { return $ai_service_instance; } // Generate image $image_url = $ai_service_instance->generate_image($prompt); if (is_wp_error($image_url)) { $this->log_featured_generation($post->ID, 'ai', $ai_service, false, $image_url->get_error_message()); return $image_url; } // Download image and create attachment $attachment_id = $this->create_attachment_from_url($image_url, $post->ID); if (is_wp_error($attachment_id)) { $this->log_featured_generation($post->ID, 'ai', $ai_service, false, $attachment_id->get_error_message()); return $attachment_id; } // Set as featured image set_post_thumbnail($post->ID, $attachment_id); // Log the operation $stat_id = $this->log_featured_generation($post->ID, 'ai', $ai_service, true); return array('success' => true, 'stat_id' => $stat_id); } /** * Generate AI prompt from post title */ private function generate_ai_prompt_from_title($title) { // Clean and enhance the title for AI generation $prompt = sanitize_text_field($title); $prompt = str_replace(array('-', '_'), ' ', $prompt); $prompt = ucwords($prompt); // Add some context for better image generation $prompt = 'A professional, high-quality image representing: ' . $prompt; return $prompt; } /** * Create attachment from URL */ private function create_attachment_from_url($image_url, $post_id) { // Download image $response = wp_remote_get($image_url); if (is_wp_error($response)) { return $response; } $image_data = wp_remote_retrieve_body($response); if (empty($image_data)) { return new WP_Error('empty_image', __('Failed to download image.', 'ai-thumbnails-maker')); } // Get file extension $file_extension = pathinfo(wp_parse_url($image_url, PHP_URL_PATH), PATHINFO_EXTENSION); if (empty($file_extension)) { $file_extension = 'jpg'; } // Create filename $filename = 'featured-image-' . $post_id . '-' . time() . '.' . $file_extension; // Upload file $upload = wp_upload_bits($filename, null, $image_data); if ($upload['error']) { return new WP_Error('upload_error', $upload['error']); } // Create attachment $attachment = array( 'post_mime_type' => wp_check_filetype($filename)['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment($attachment, $upload['file'], $post_id); if (is_wp_error($attachment_id)) { return $attachment_id; } // Generate attachment metadata if (!function_exists('wp_generate_attachment_metadata')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); } $attachment_data = wp_generate_attachment_metadata($attachment_id, $upload['file']); wp_update_attachment_metadata($attachment_id, $attachment_data); return $attachment_id; } /** * Log featured image generation */ private function log_featured_generation($post_id, $method, $ai_service, $success, $error_message = '') { $statistics_manager = new AITM_Statistics_Manager(); return $statistics_manager->log_generation( $post_id, // attachment_id (post_id in this case) $post_id, // post_id get_post_type($post_id), // post_type $method, // generation_method $ai_service, // ai_service $success, // success $error_message // error_message ); } /** * Plugin activation. */ public function activate() { // Create database tables $this->create_tables(); // Set default options $this->set_default_options(); // Schedule cron events $cron_manager = new AITM_Cron_Manager(); $cron_manager->schedule_events(); } /** * Plugin deactivation. */ public function deactivate() { // Clear cron events $cron_manager = new AITM_Cron_Manager(); $cron_manager->clear_events(); } /** * Create database tables. */ private function create_tables() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = $wpdb->prefix . 'aitm_statistics'; $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, attachment_id bigint(20) NOT NULL, post_id bigint(20) DEFAULT NULL, post_type varchar(20) DEFAULT NULL, generation_method varchar(50) NOT NULL, ai_service varchar(50) DEFAULT NULL, success tinyint(1) NOT NULL DEFAULT 0, error_message text DEFAULT NULL, created_at datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY attachment_id (attachment_id), KEY post_id (post_id), KEY generation_method (generation_method), KEY success (success) ) $charset_collate;"; // Load database upgrade functions if not already available if (!function_exists('dbDelta')) { require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); } dbDelta($sql); // Create cron queue table $queue_table = $wpdb->prefix . 'aitm_cron_queue'; $queue_sql = "CREATE TABLE $queue_table ( id mediumint(9) NOT NULL AUTO_INCREMENT, task_type varchar(50) NOT NULL, attachment_id bigint(20) DEFAULT NULL, post_id bigint(20) DEFAULT NULL, method varchar(50) DEFAULT NULL, use_ai tinyint(1) NOT NULL DEFAULT 0, ai_service varchar(50) DEFAULT NULL, status varchar(20) NOT NULL DEFAULT 'pending', error_message text DEFAULT NULL, created_at datetime DEFAULT CURRENT_TIMESTAMP, completed_at datetime DEFAULT NULL, PRIMARY KEY (id), KEY task_type (task_type), KEY status (status), KEY attachment_id (attachment_id), KEY post_id (post_id) ) $charset_collate;"; dbDelta($queue_sql); } /** * Set default plugin options. */ private function set_default_options() { $default_settings = array( 'enable_ai_generation' => true, 'default_ai_service' => 'dall_e_3', 'auto_regenerate' => false, 'enable_cron_processing' => false, 'cron_interval' => 'aitm_every_minute', 'stats_update_interval' => 30, 'max_retries' => 3, 'thumbnail_quality' => 90, ); $default_ai_settings = array( 'dall_e_3' => array( 'api_key' => '', 'model' => 'dall-e-3', 'size' => '1024x1024', 'quality' => 'standard', 'style' => 'vivid', ), 'midjourney' => array( 'api_key' => '', 'server_id' => '', 'channel_id' => '', 'size' => '1024x1024', ), ); add_option('aitm_settings', $default_settings); add_option('aitm_ai_settings', $default_ai_settings); } } /** * Get the main plugin instance. * * @return AITM_Plugin */ function aitm() { return AITM_Plugin::instance(); } // Initialize the plugin aitm();