table_name = $wpdb->prefix . 'aiautotool_image404_report'; $this->table_name_thumbs = $wpdb->prefix . 'aiautotool_missing_thumbs'; $this->table_name_alt = $wpdb->prefix . 'aiautotool_missing_alt'; $this->table_name_format = $wpdb->prefix . 'aiautotool_image_format'; $this->active = get_option($this->active_option_name, false); // Create tables on activation $this->create_report_table(); $this->create_thumbs_table(); $this->create_alt_table(); $this->create_format_table(); if ($this->active == 'true') { $this->init(); } // AJAX handlers add_action('wp_ajax_update_active_option_canonical_' . $this->active_option_name, array($this, 'update_active_option_callback')); add_action('wp_ajax_aiautotool_scan_images_manual', array($this, 'ajax_scan_images_manual')); add_action('wp_ajax_aiautotool_scan_comprehensive', array($this, 'ajax_scan_comprehensive')); add_action('wp_ajax_aiautotool_fix_404_images', array($this, 'ajax_fix_404_images')); add_action('wp_ajax_aiautotool_generate_thumbnails_ai', array($this, 'ajax_generate_thumbnails_ai')); add_action('wp_ajax_aiautotool_fix_missing_alt', array($this, 'ajax_fix_missing_alt')); add_action('wp_ajax_aiautotool_clear_report', array($this, 'ajax_clear_report')); add_action('wp_ajax_aiautotool_get_scan_progress', array($this, 'ajax_get_scan_progress')); add_action('wp_ajax_aiautotool_download_remote_images', array($this, 'ajax_download_remote_images')); add_action('wp_ajax_aiautotool_download_remote_from_post', array($this, 'ajax_download_remote_from_post')); } /** * Create database table for 404 image reports */ private function create_report_table() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name} ( id bigint(20) NOT NULL AUTO_INCREMENT, post_id bigint(20) NOT NULL, post_title text NOT NULL, image_url text NOT NULL, image_type varchar(50) NOT NULL, error_message text, status varchar(20) DEFAULT 'pending', created_at datetime DEFAULT CURRENT_TIMESTAMP, fixed_at datetime DEFAULT NULL, PRIMARY KEY (id), KEY post_id (post_id), KEY status (status) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } /** * Create table for missing thumbnails tracking */ private function create_thumbs_table() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name_thumbs} ( id bigint(20) NOT NULL AUTO_INCREMENT, post_id bigint(20) NOT NULL, post_title text NOT NULL, post_type varchar(50) NOT NULL, status varchar(20) DEFAULT 'pending', ai_generated tinyint(1) DEFAULT 0, thumbnail_id bigint(20) DEFAULT NULL, created_at datetime DEFAULT CURRENT_TIMESTAMP, generated_at datetime DEFAULT NULL, PRIMARY KEY (id), KEY post_id (post_id), KEY status (status) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } /** * Create table for missing alt text tracking */ private function create_alt_table() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name_alt} ( id bigint(20) NOT NULL AUTO_INCREMENT, post_id bigint(20) NOT NULL, post_title text NOT NULL, image_url text NOT NULL, attachment_id bigint(20) DEFAULT NULL, status varchar(20) DEFAULT 'pending', created_at datetime DEFAULT CURRENT_TIMESTAMP, fixed_at datetime DEFAULT NULL, PRIMARY KEY (id), KEY post_id (post_id), KEY status (status) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } /** * Create table for image format issues */ private function create_format_table() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE IF NOT EXISTS {$this->table_name_format} ( id bigint(20) NOT NULL AUTO_INCREMENT, post_id bigint(20) NOT NULL, post_title text NOT NULL, image_url text NOT NULL, issue_type varchar(50) NOT NULL, current_format varchar(10) NOT NULL, current_size varchar(50) NOT NULL, recommended_action text, status varchar(20) DEFAULT 'pending', created_at datetime DEFAULT CURRENT_TIMESTAMP, fixed_at datetime DEFAULT NULL, PRIMARY KEY (id), KEY post_id (post_id), KEY status (status), KEY issue_type (issue_type) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } /** * Update active option callback */ 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); // Clear cron on deactivation if ($active !== 'true') { wp_clear_scheduled_hook('aiautotool_cron_scan_404_images'); } echo $active; } wp_die(); } /** * Initialize plugin */ public function init() { $this->options = get_option('aiautotool_image404_options', array()); add_action('admin_init', array($this, 'init_page')); // Setup cron if enabled if (!wp_next_scheduled('aiautotool_cron_scan_404_images')) { wp_schedule_event(time(), 'daily', 'aiautotool_cron_scan_404_images'); } add_action('aiautotool_cron_scan_404_images', array($this, 'cron_scan_404_images')); // Auto download remote images on save post (if enabled) if (isset($this->options['enable_remote_download']) && $this->options['enable_remote_download'] == 1) { add_action('save_post', array($this, 'auto_download_on_save_post'), 10, 3); } // Add metabox for manual download in post editor add_action('add_meta_boxes', array($this, 'add_remote_download_metabox')); // Enqueue scripts for post editor add_action('admin_enqueue_scripts', array($this, 'enqueue_post_editor_scripts')); } /** * Render feature box */ public function render_feature() { require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php'; $autoToolBox = new AutoToolBox( " " . esc_html__('Image 404 Scanner & Fixer', 'ai-auto-tool'), esc_html__('Automatically scan and fix 404 images in your posts. Find broken images and remove them to improve site quality.', 'ai-auto-tool'), "https://doc.aiautotool.com/features/image-404-scanner", $this->active_option_name, $this->active, plugins_url('../../images/logo.svg', __FILE__) ); echo $autoToolBox->generateHTML(); } /** * Render tab setting */ public function render_tab_setting() { if ($this->active == 'true') { echo ''; } } /** * Render settings page */ public function render_setting() { global $wpdb; $auto_scan = isset($this->options['auto_scan']) ? $this->options['auto_scan'] : 1; $scan_interval = isset($this->options['scan_interval']) ? $this->options['scan_interval'] : 'daily'; $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post'); // Get statistics for all issue types $total_errors = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name} WHERE status='pending'"); $total_fixed = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name} WHERE status='fixed'"); $total_posts_with_errors = $wpdb->get_var("SELECT COUNT(DISTINCT post_id) FROM {$this->table_name} WHERE status='pending'"); // Missing thumbnails $missing_thumbs = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_thumbs} WHERE status='pending'"); $generated_thumbs = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_thumbs} WHERE status='generated'"); // Missing alt text $missing_alt = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_alt} WHERE status='pending'"); $fixed_alt = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_alt} WHERE status='fixed'"); // Format issues $format_issues = $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name_format} WHERE status='pending'"); // Get recent errors $recent_errors = $wpdb->get_results( "SELECT * FROM {$this->table_name} WHERE status='pending' ORDER BY created_at DESC LIMIT 50" ); ?> 'array', 'sanitize_callback' => array($this, 'sanitize_options') ) ); add_settings_section( 'aiautotool_image404_section', '', array($this, 'section_info'), 'aiautotool-image404' ); } /** * Sanitize options */ public function sanitize_options($input) { $new_input = array(); if (isset($input['auto_scan'])) { $new_input['auto_scan'] = 1; } else { $new_input['auto_scan'] = 0; } if (isset($input['enable_remote_download'])) { $new_input['enable_remote_download'] = 1; } else { $new_input['enable_remote_download'] = 0; } if (isset($input['scan_interval'])) { $new_input['scan_interval'] = sanitize_text_field($input['scan_interval']); } if (isset($input['post_types']) && is_array($input['post_types'])) { $new_input['post_types'] = array_map('sanitize_text_field', $input['post_types']); } else { $new_input['post_types'] = array('post'); } return $new_input; } /** * Section info */ public function section_info() { // Empty - description is in render_setting } /** * AJAX: Manual scan */ public function ajax_scan_images_manual() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $result = $this->scan_all_posts(); if ($result['success']) { wp_send_json_success(array( 'message' => sprintf( __('Scan completed! Found %d 404 images in %d posts.', 'ai-auto-tool'), $result['errors_found'], $result['posts_scanned'] ) )); } else { wp_send_json_error(array('message' => $result['message'])); } } /** * AJAX: Fix 404 images */ public function ajax_fix_404_images() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $result = $this->fix_all_404_images(); if ($result['success']) { wp_send_json_success(array( 'message' => sprintf( __('Fixed %d images in %d posts successfully!', 'ai-auto-tool'), $result['fixed_count'], $result['posts_fixed'] ) )); } else { wp_send_json_error(array('message' => $result['message'])); } } /** * AJAX: Clear report */ public function ajax_clear_report() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } global $wpdb; $wpdb->query("TRUNCATE TABLE {$this->table_name}"); $wpdb->query("TRUNCATE TABLE {$this->table_name_thumbs}"); $wpdb->query("TRUNCATE TABLE {$this->table_name_alt}"); $wpdb->query("TRUNCATE TABLE {$this->table_name_format}"); wp_send_json_success(array('message' => __('All reports cleared successfully!', 'ai-auto-tool'))); } /** * AJAX: Get scan progress */ public function ajax_get_scan_progress() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $progress = get_transient('aiautotool_scan_progress'); if ($progress === false) { wp_send_json_success(array( 'progress' => 0, 'status' => 'idle' )); } else { wp_send_json_success($progress); } } /** * Cron: Scan for 404 images */ public function cron_scan_404_images() { // 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')) { if (did_action('init')) { if (function_exists('aiautotool_load_textdomain')) { aiautotool_load_textdomain(); } } } $this->scan_all_posts(); } /** * Scan all posts for 404 images */ private function scan_all_posts() { global $wpdb; set_time_limit(0); $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post'); // Get all published posts $args = array( 'post_type' => $post_types, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids' ); $post_ids = get_posts($args); $total_posts = count($post_ids); $posts_scanned = 0; $errors_found = 0; // Initialize TODO list $todo_list = array( array('task' => __('Clear old reports', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Scan featured images', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Scan content images', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Generate report', 'ai-auto-tool'), 'status' => 'pending'), ); // Clear old pending reports $todo_list[0]['status'] = 'in_progress'; $this->update_progress(0, $total_posts, 0, 0, __('Clearing old reports...', 'ai-auto-tool'), '', $todo_list); $wpdb->query("DELETE FROM {$this->table_name} WHERE status='pending'"); $todo_list[0]['status'] = 'completed'; foreach ($post_ids as $post_id) { $post = get_post($post_id); $current_post_title = $post ? $post->post_title : __('Unknown', 'ai-auto-tool'); // Update task status if ($posts_scanned === 0) { $todo_list[1]['status'] = 'in_progress'; } if ($posts_scanned > 0 && $posts_scanned < $total_posts / 2) { $todo_list[2]['status'] = 'in_progress'; } // Update progress with current post info $this->update_progress( $posts_scanned, $total_posts, $errors_found, $post_id, __('Scanning post...', 'ai-auto-tool'), $current_post_title, $todo_list ); $post_errors = $this->scan_post_images($post_id); $errors_found += $post_errors; $posts_scanned++; } // Mark scanning tasks as completed $todo_list[1]['status'] = 'completed'; $todo_list[2]['status'] = 'completed'; $todo_list[3]['status'] = 'in_progress'; $this->update_progress( $posts_scanned, $total_posts, $errors_found, 0, __('Generating final report...', 'ai-auto-tool'), '', $todo_list ); // Final update $todo_list[3]['status'] = 'completed'; $this->update_progress( $posts_scanned, $total_posts, $errors_found, 0, __('Scan completed!', 'ai-auto-tool'), '', $todo_list ); // Keep final progress for 10 seconds before clearing sleep(2); delete_transient('aiautotool_scan_progress'); return array( 'success' => true, 'posts_scanned' => $posts_scanned, 'errors_found' => $errors_found ); } /** * Update scan progress * * @param int $scanned Number of posts scanned * @param int $total Total posts to scan * @param int $errors Errors found so far * @param int $current_post_id Current post being scanned * @param string $message Status message * @param string $current_post_title Current post title * @param array $todo_list TODO list with statuses */ private function update_progress($scanned, $total, $errors, $current_post_id, $message, $current_post_title, $todo_list) { $progress = array( 'progress' => $total > 0 ? round(($scanned / $total) * 100) : 0, 'status' => 'scanning', 'posts_scanned' => $scanned, 'total_posts' => $total, 'errors_found' => $errors, 'current_post_id' => $current_post_id, 'current_post_title' => $current_post_title, 'message' => $message, 'todo_list' => $todo_list, 'timestamp' => time() ); set_transient('aiautotool_scan_progress', $progress, 300); } /** * Scan single post for 404 images */ private function scan_post_images($post_id) { global $wpdb; $post = get_post($post_id); if (!$post) { return 0; } $errors_found = 0; // Check featured image if (has_post_thumbnail($post_id)) { $thumbnail_id = get_post_thumbnail_id($post_id); $thumbnail_url = wp_get_attachment_url($thumbnail_id); if (!$this->check_image_exists($thumbnail_url)) { $this->add_404_report($post_id, $post->post_title, $thumbnail_url, 'featured_image', 'Featured image not found (404)'); $errors_found++; } } // Check images in content $content = $post->post_content; $pattern = '/]*\bsrc=["\']([^"\']+)["\'][^>]*>/i'; $matches = array(); if (preg_match_all($pattern, $content, $matches)) { if (isset($matches[1])) { foreach ($matches[1] as $image_url) { // Clean URL $image_url = html_entity_decode($image_url); if (!$this->check_image_exists($image_url)) { $this->add_404_report($post_id, $post->post_title, $image_url, 'content_image', 'Image in content not found (404)'); $errors_found++; } } } } return $errors_found; } /** * Check if image exists */ private function check_image_exists($url) { if (empty($url)) { return false; } // Parse URL $url_parts = parse_url($url); if (!$url_parts) { return false; } // Check if it's a local image $home_url = parse_url(home_url()); if (isset($url_parts['host']) && $url_parts['host'] === $home_url['host']) { // Local image - check file system $upload_dir = wp_upload_dir(); $file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $url); return file_exists($file_path); } else { // External image - check HTTP status $response = wp_remote_head($url, array( 'timeout' => 5, 'redirection' => 5, 'sslverify' => false )); if (is_wp_error($response)) { return false; } $status_code = wp_remote_retrieve_response_code($response); return ($status_code >= 200 && $status_code < 400); } } /** * Add 404 report to database */ private function add_404_report($post_id, $post_title, $image_url, $image_type, $error_message) { global $wpdb; $wpdb->insert( $this->table_name, array( 'post_id' => $post_id, 'post_title' => $post_title, 'image_url' => $image_url, 'image_type' => $image_type, 'error_message' => $error_message, 'status' => 'pending', 'created_at' => current_time('mysql') ), array('%d', '%s', '%s', '%s', '%s', '%s', '%s') ); } /** * Fix all 404 images */ private function fix_all_404_images() { global $wpdb; set_time_limit(0); // Get all pending errors $errors = $wpdb->get_results( "SELECT * FROM {$this->table_name} WHERE status='pending' ORDER BY post_id" ); if (empty($errors)) { return array( 'success' => false, 'message' => __('No 404 images to fix', 'ai-auto-tool') ); } $posts_fixed = array(); $fixed_count = 0; foreach ($errors as $error) { $result = $this->fix_single_image($error); if ($result) { $fixed_count++; $posts_fixed[$error->post_id] = true; // Update status $wpdb->update( $this->table_name, array( 'status' => 'fixed', 'fixed_at' => current_time('mysql') ), array('id' => $error->id), array('%s', '%s'), array('%d') ); } } return array( 'success' => true, 'fixed_count' => $fixed_count, 'posts_fixed' => count($posts_fixed) ); } /** * Fix single image */ private function fix_single_image($error) { $post = get_post($error->post_id); if (!$post) { return false; } if ($error->image_type === 'featured_image') { // Remove featured image delete_post_thumbnail($error->post_id); return true; } elseif ($error->image_type === 'content_image') { // Remove image from content $content = $post->post_content; // Find and remove the img tag $pattern = '/]*\bsrc=["\']' . preg_quote($error->image_url, '/') . '["\'][^>]*>/i'; $new_content = preg_replace($pattern, '', $content); // Also remove any wrapping tags that might be empty now $new_content = preg_replace('/]*>\s*<\/a>/i', '', $new_content); // Update post wp_update_post(array( 'ID' => $error->post_id, 'post_content' => $new_content )); return true; } return false; } /** * AJAX: Download remote images * * Scans posts for external images and downloads them to media library */ public function ajax_download_remote_images() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $result = $this->download_all_remote_images(); if ($result['success']) { wp_send_json_success(array( 'message' => sprintf( __('Downloaded %d remote images from %d posts successfully!', 'ai-auto-tool'), $result['downloaded_count'], $result['posts_processed'] ) )); } else { wp_send_json_error(array('message' => $result['message'])); } } /** * Download all remote images from posts * * Scans all posts for external images and downloads them to WordPress media library. * Updates post content with new local URLs. * * @return array Result with success status and statistics */ private function download_all_remote_images() { global $wpdb; set_time_limit(0); // Check if feature is enabled if (!isset($this->options['enable_remote_download']) || $this->options['enable_remote_download'] != 1) { return array( 'success' => false, 'message' => __('Remote image download is not enabled. Please enable it in settings.', 'ai-auto-tool') ); } $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post'); // Get all published posts $args = array( 'post_type' => $post_types, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids' ); $post_ids = get_posts($args); $total_posts = count($post_ids); $posts_processed = 0; $downloaded_count = 0; // Initialize TODO list for download $todo_list = array( array('task' => __('Scan for remote images', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Download remote images', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Update post content', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Generate report', 'ai-auto-tool'), 'status' => 'pending'), ); $todo_list[0]['status'] = 'in_progress'; foreach ($post_ids as $post_id) { $post = get_post($post_id); $current_post_title = $post ? $post->post_title : __('Unknown', 'ai-auto-tool'); // Update task status if ($posts_processed === 0) { $todo_list[1]['status'] = 'in_progress'; } if ($posts_processed > $total_posts / 2) { $todo_list[2]['status'] = 'in_progress'; } // Update progress $this->update_progress( $posts_processed, $total_posts, $downloaded_count, $post_id, __('Processing post...', 'ai-auto-tool'), $current_post_title, $todo_list ); $downloaded = $this->download_remote_images_from_post($post_id); $downloaded_count += $downloaded; $posts_processed++; } // Mark tasks as completed $todo_list[0]['status'] = 'completed'; $todo_list[1]['status'] = 'completed'; $todo_list[2]['status'] = 'completed'; $todo_list[3]['status'] = 'in_progress'; $this->update_progress( $posts_processed, $total_posts, $downloaded_count, 0, __('Download completed!', 'ai-auto-tool'), '', $todo_list ); $todo_list[3]['status'] = 'completed'; sleep(2); delete_transient('aiautotool_scan_progress'); return array( 'success' => true, 'posts_processed' => $posts_processed, 'downloaded_count' => $downloaded_count ); } /** * Download remote images from a single post * * @param int $post_id Post ID to process * @return int Number of images downloaded */ private function download_remote_images_from_post($post_id) { $post = get_post($post_id); if (!$post) { return 0; } $downloaded_count = 0; $content = $post->post_content; $home_url = parse_url(home_url()); // Find all images in content $pattern = '/]*\bsrc=["\']([^"\']+)["\'][^>]*>/i'; $matches = array(); if (preg_match_all($pattern, $content, $matches)) { if (isset($matches[0]) && isset($matches[1])) { $full_tags = $matches[0]; $image_urls = $matches[1]; foreach ($image_urls as $index => $image_url) { $image_url = html_entity_decode($image_url); $url_parts = parse_url($image_url); // Check if it's an external image if (isset($url_parts['host']) && $url_parts['host'] !== $home_url['host']) { // This is an external image, download it $new_attachment_id = $this->download_remote_image($image_url, $post_id); if ($new_attachment_id) { // Get new local URL $new_url = wp_get_attachment_url($new_attachment_id); if ($new_url) { // Replace old URL with new URL in content $content = str_replace($image_url, $new_url, $content); $downloaded_count++; } } } } // Update post content if any images were downloaded if ($downloaded_count > 0) { wp_update_post(array( 'ID' => $post_id, 'post_content' => $content )); } } } return $downloaded_count; } /** * Download a single remote image to media library * * @param string $image_url Remote image URL * @param int $post_id Post ID to attach image to * @return int|false Attachment ID on success, false on failure */ private function download_remote_image($image_url, $post_id) { // Validate URL if (!filter_var($image_url, FILTER_VALIDATE_URL)) { return false; } // Check if image exists $response = wp_remote_head($image_url, array( 'timeout' => 10, 'redirection' => 5, 'sslverify' => false )); if (is_wp_error($response)) { return false; } $status_code = wp_remote_retrieve_response_code($response); if ($status_code !== 200) { return false; } // Check content type $content_type = wp_remote_retrieve_header($response, 'content-type'); if (strpos($content_type, 'image/') === false) { return false; } // Download image require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); $tmp = download_url($image_url); if (is_wp_error($tmp)) { return false; } // Get file info $file_array = array(); $file_array['name'] = basename($image_url); $file_array['tmp_name'] = $tmp; // Check for file extension $ext = pathinfo($file_array['name'], PATHINFO_EXTENSION); if (!$ext) { // Try to get extension from content type $ext = $this->get_extension_from_content_type($content_type); if ($ext) { $file_array['name'] = 'image-' . time() . '.' . $ext; } } // Upload to media library $attachment_id = media_handle_sideload($file_array, $post_id); // Check for upload errors if (is_wp_error($attachment_id)) { @unlink($tmp); return false; } return $attachment_id; } /** * Get file extension from content type * * @param string $content_type Content type header * @return string|false File extension or false */ private function get_extension_from_content_type($content_type) { $type_map = array( 'image/jpeg' => 'jpg', 'image/jpg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp', 'image/svg+xml' => 'svg', 'image/bmp' => 'bmp', ); $content_type = strtolower(trim($content_type)); return isset($type_map[$content_type]) ? $type_map[$content_type] : false; } /** * Auto download remote images when saving/publishing post * * Triggered by save_post hook when enable_remote_download is enabled. * Prevents infinite loops and only runs on actual post saves. * * @param int $post_id Post ID * @param WP_Post $post Post object * @param bool $update Whether this is an update */ public function auto_download_on_save_post($post_id, $post, $update) { // Avoid infinite loops if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } // Check permissions if (!current_user_can('edit_post', $post_id)) { return; } // Only for allowed post types $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post'); if (!in_array($post->post_type, $post_types)) { return; } // Only on publish or update if ($post->post_status !== 'publish') { return; } // Check if there are remote images if (!$this->has_remote_images($post->post_content)) { return; } // Remove this hook temporarily to prevent infinite loop remove_action('save_post', array($this, 'auto_download_on_save_post'), 10); // Download remote images $this->download_remote_images_from_post($post_id); // Re-add the hook add_action('save_post', array($this, 'auto_download_on_save_post'), 10, 3); // Set admin notice set_transient('aiautotool_remote_download_notice_' . $post_id, true, 30); } /** * Check if content has remote images * * @param string $content Post content * @return bool True if has remote images */ private function has_remote_images($content) { $pattern = '/]*\bsrc=["\']([^"\']+)["\'][^>]*>/i'; $matches = array(); if (preg_match_all($pattern, $content, $matches)) { if (isset($matches[1])) { $home_url = parse_url(home_url()); foreach ($matches[1] as $image_url) { $image_url = html_entity_decode($image_url); $url_parts = parse_url($image_url); // Check if external if (isset($url_parts['host']) && $url_parts['host'] !== $home_url['host']) { return true; } } } } return false; } /** * Add metabox to post editor for manual remote image download */ public function add_remote_download_metabox() { $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post'); foreach ($post_types as $post_type) { add_meta_box( 'aiautotool_remote_download', ' ' . __('Remote Images', 'ai-auto-tool'), array($this, 'render_remote_download_metabox'), $post_type, 'side', 'default' ); } } /** * Render metabox content * * @param WP_Post $post Current post object */ public function render_remote_download_metabox($post) { // Check if feature is enabled $is_enabled = isset($this->options['enable_remote_download']) && $this->options['enable_remote_download'] == 1; // Count remote images $remote_count = $this->count_remote_images($post->post_content); wp_nonce_field('aiautotool_download_remote_nonce', 'aiautotool_download_remote_nonce'); ?>

→

0): ?>

ID)): delete_transient('aiautotool_remote_download_notice_' . $post->ID); ?>

]*\bsrc=["\']([^"\']+)["\'][^>]*>/i'; $matches = array(); if (preg_match_all($pattern, $content, $matches)) { if (isset($matches[1])) { $home_url = parse_url(home_url()); foreach ($matches[1] as $image_url) { $image_url = html_entity_decode($image_url); $url_parts = parse_url($image_url); // Check if external if (isset($url_parts['host']) && $url_parts['host'] !== $home_url['host']) { $count++; } } } } return $count; } /** * Enqueue scripts for post editor */ public function enqueue_post_editor_scripts($hook) { // Only on post edit pages if (!in_array($hook, array('post.php', 'post-new.php'))) { return; } // Inline script for metabox functionality wp_add_inline_script('jquery', ' jQuery(document).ready(function($) { $("#aiautotool-download-remote-btn").on("click", function(e) { e.preventDefault(); var $btn = $(this); var $status = $("#aiautotool-download-status"); var $message = $("#aiautotool-download-message"); var $progress = $("#aiautotool-download-progress"); var $count = $("#aiautotool-remote-count"); // Get post ID var postId = $("#post_ID").val(); if (!postId) { alert("' . esc_js(__('Please save the post first.', 'ai-auto-tool')) . '"); return; } // Disable button $btn.prop("disabled", true).text("' . esc_js(__('Downloading...', 'ai-auto-tool')) . '"); $status.show(); $message.text("' . esc_js(__('Starting download...', 'ai-auto-tool')) . '"); $progress.css("width", "10%"); // AJAX request $.ajax({ url: ajaxurl, type: "POST", data: { action: "aiautotool_download_remote_from_post", post_id: postId, security: $("#aiautotool_download_remote_nonce").val() }, success: function(response) { if (response.success) { $progress.css("width", "100%"); $message.text(response.data.message); $count.text(response.data.remaining || 0); // Reload editor content after 2 seconds setTimeout(function() { location.reload(); }, 2000); } else { $message.text(response.data.message || "' . esc_js(__('An error occurred', 'ai-auto-tool')) . '"); $btn.prop("disabled", false).html(\' ' . esc_js(__('Download Now', 'ai-auto-tool')) . '\'); } }, error: function() { $message.text("' . esc_js(__('Request failed', 'ai-auto-tool')) . '"); $btn.prop("disabled", false).html(\' ' . esc_js(__('Download Now', 'ai-auto-tool')) . '\'); } }); }); }); '); } /** * AJAX handler for manual download from post editor */ public function ajax_download_remote_from_post() { check_ajax_referer('aiautotool_download_remote_nonce', 'security'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0; if (!$post_id) { wp_send_json_error(array('message' => __('Invalid post ID', 'ai-auto-tool'))); } // Check if feature is enabled if (!isset($this->options['enable_remote_download']) || $this->options['enable_remote_download'] != 1) { wp_send_json_error(array('message' => __('Remote image download is not enabled.', 'ai-auto-tool'))); } // Download images $downloaded = $this->download_remote_images_from_post($post_id); // Get updated post content to count remaining $post = get_post($post_id); $remaining = $this->count_remote_images($post->post_content); if ($downloaded > 0) { wp_send_json_success(array( 'message' => sprintf( __('Successfully downloaded %d remote images!', 'ai-auto-tool'), $downloaded ), 'downloaded' => $downloaded, 'remaining' => $remaining )); } elseif ($downloaded === 0 && $remaining === 0) { wp_send_json_success(array( 'message' => __('No remote images found or all images are already local.', 'ai-auto-tool'), 'downloaded' => 0, 'remaining' => 0 )); } else { wp_send_json_error(array( 'message' => __('Failed to download images. Please check the image URLs.', 'ai-auto-tool'), 'remaining' => $remaining )); } } /** * AJAX: Comprehensive scan (all image issues in one scan) */ public function ajax_scan_comprehensive() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $result = $this->comprehensive_scan(); if ($result['success']) { wp_send_json_success(array( 'message' => sprintf( __('Comprehensive scan completed! Found: %d 404 images, %d missing thumbnails, %d missing alt texts, %d format issues', 'ai-auto-tool'), $result['404_count'], $result['missing_thumbs'], $result['missing_alt'], $result['format_issues'] ), 'results' => $result )); } else { wp_send_json_error(array('message' => $result['message'])); } } /** * Comprehensive scan - all image checks */ private function comprehensive_scan() { global $wpdb; set_time_limit(0); $post_types = isset($this->options['post_types']) ? $this->options['post_types'] : array('post'); $args = array( 'post_type' => $post_types, 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids' ); $post_ids = get_posts($args); $total_posts = count($post_ids); $posts_scanned = 0; $counts = array( '404_count' => 0, 'missing_thumbs' => 0, 'missing_alt' => 0, 'format_issues' => 0 ); // Initialize TODO list $todo_list = array( array('task' => __('Clear old reports', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Scan 404 images', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Scan missing thumbnails', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Scan missing alt text', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Scan image formats', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Generate report', 'ai-auto-tool'), 'status' => 'pending'), ); // Clear old reports $todo_list[0]['status'] = 'in_progress'; $this->update_progress(0, $total_posts, 0, 0, __('Clearing old reports...', 'ai-auto-tool'), '', $todo_list); $wpdb->query("DELETE FROM {$this->table_name} WHERE status='pending'"); $wpdb->query("DELETE FROM {$this->table_name_thumbs} WHERE status='pending'"); $wpdb->query("DELETE FROM {$this->table_name_alt} WHERE status='pending'"); $wpdb->query("DELETE FROM {$this->table_name_format} WHERE status='pending'"); $todo_list[0]['status'] = 'completed'; // Scan all posts foreach ($post_ids as $post_id) { $post = get_post($post_id); $current_post_title = $post ? $post->post_title : __('Unknown', 'ai-auto-tool'); // Update task statuses based on progress if ($posts_scanned === 0) $todo_list[1]['status'] = 'in_progress'; if ($posts_scanned >= $total_posts * 0.2) { $todo_list[1]['status'] = 'completed'; $todo_list[2]['status'] = 'in_progress'; } if ($posts_scanned >= $total_posts * 0.4) { $todo_list[2]['status'] = 'completed'; $todo_list[3]['status'] = 'in_progress'; } if ($posts_scanned >= $total_posts * 0.6) { $todo_list[3]['status'] = 'completed'; $todo_list[4]['status'] = 'in_progress'; } if ($posts_scanned >= $total_posts * 0.8) { $todo_list[4]['status'] = 'completed'; } $this->update_progress($posts_scanned, $total_posts, 0, $post_id, __('Comprehensive scanning...', 'ai-auto-tool'), $current_post_title, $todo_list); // 1. Scan 404 images $counts['404_count'] += $this->scan_post_images($post_id); // 2. Check missing thumbnail if (!has_post_thumbnail($post_id)) { $wpdb->insert($this->table_name_thumbs, array( 'post_id' => $post_id, 'post_title' => $post->post_title, 'post_type' => $post->post_type, 'status' => 'pending', 'created_at' => current_time('mysql') ), array('%d', '%s', '%s', '%s', '%s')); $counts['missing_thumbs']++; } // 3. Check missing alt text $counts['missing_alt'] += $this->check_missing_alt($post_id, $post); // 4. Check image formats $counts['format_issues'] += $this->check_image_formats($post_id, $post); $posts_scanned++; } // Final report $todo_list[5]['status'] = 'in_progress'; $this->update_progress($posts_scanned, $total_posts, 0, 0, __('Generating report...', 'ai-auto-tool'), '', $todo_list); $todo_list[5]['status'] = 'completed'; sleep(1); delete_transient('aiautotool_scan_progress'); return array_merge(array('success' => true), $counts); } /** * Check missing alt text */ private function check_missing_alt($post_id, $post) { global $wpdb; $count = 0; $pattern = '/]*>/i'; if (preg_match_all($pattern, $post->post_content, $matches)) { foreach ($matches[0] as $img_tag) { if (!preg_match('/alt=["\'][^"\']*["\']/', $img_tag) || preg_match('/alt=["\']\s*["\']/', $img_tag)) { preg_match('/src=["\']([^"\']+)["\']/', $img_tag, $src_match); if (isset($src_match[1])) { $wpdb->insert($this->table_name_alt, array( 'post_id' => $post_id, 'post_title' => $post->post_title, 'image_url' => $src_match[1], 'status' => 'pending', 'created_at' => current_time('mysql') ), array('%d', '%s', '%s', '%s', '%s')); $count++; } } } } return $count; } /** * Check image formats and sizes */ private function check_image_formats($post_id, $post) { global $wpdb; $count = 0; $pattern = '/]*\bsrc=["\']([^"\']+)["\'][^>]*>/i'; if (preg_match_all($pattern, $post->post_content, $matches)) { foreach ($matches[1] as $image_url) { $image_url = html_entity_decode($image_url); $info = $this->get_image_info($image_url); if ($info && isset($info['issue'])) { $wpdb->insert($this->table_name_format, array( 'post_id' => $post_id, 'post_title' => $post->post_title, 'image_url' => $image_url, 'issue_type' => $info['issue'], 'current_format' => $info['format'], 'current_size' => $info['size'], 'recommended_action' => $info['recommendation'], 'status' => 'pending', 'created_at' => current_time('mysql') ), array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')); $count++; } } } return $count; } /** * Get image info for format checking */ private function get_image_info($url) { $home_url = parse_url(home_url()); $url_parts = parse_url($url); if (!isset($url_parts['host'])) return null; // Only check local images if ($url_parts['host'] !== $home_url['host']) { return null; } $upload_dir = wp_upload_dir(); $file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $url); if (!file_exists($file_path)) return null; $size = @getimagesize($file_path); if (!$size) return null; $width = $size[0]; $height = $size[1]; $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION)); $filesize = filesize($file_path); $issue = null; $recommendation = ''; // Check too small if ($width < 300 || $height < 300) { $issue = 'too_small'; $recommendation = __('Image too small for thumbnail. Minimum 300x300px recommended.', 'ai-auto-tool'); } // Check too large elseif ($filesize > 5 * 1024 * 1024) { $issue = 'too_large'; $recommendation = __('Image file size over 5MB. Consider optimization.', 'ai-auto-tool'); } // Check wrong format elseif (!in_array($ext, array('jpg', 'jpeg', 'png', 'webp', 'gif'))) { $issue = 'unsupported_format'; $recommendation = __('Unsupported format. Convert to JPG, PNG, or WebP.', 'ai-auto-tool'); } if ($issue) { return array( 'issue' => $issue, 'format' => $ext, 'size' => $width . 'x' . $height . ' (' . size_format($filesize) . ')', 'recommendation' => $recommendation ); } return null; } /** * AJAX: Generate thumbnails using AI */ public function ajax_generate_thumbnails_ai() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $result = $this->generate_all_thumbnails_ai(); if ($result['success']) { wp_send_json_success(array( 'message' => sprintf( __('Generated %d thumbnails for %d posts using AI!', 'ai-auto-tool'), $result['generated_count'], $result['posts_processed'] ) )); } else { wp_send_json_error(array('message' => $result['message'])); } } /** * Generate thumbnails for all posts without featured image */ private function generate_all_thumbnails_ai() { global $wpdb; set_time_limit(0); // Get posts without thumbnails $posts_without_thumbs = $wpdb->get_results( "SELECT post_id, post_title FROM {$this->table_name_thumbs} WHERE status='pending'" ); if (empty($posts_without_thumbs)) { return array('success' => false, 'message' => __('No posts without thumbnails', 'ai-auto-tool')); } $total = count($posts_without_thumbs); $generated = 0; $processed = 0; $todo_list = array( array('task' => __('Generate AI thumbnails', 'ai-auto-tool'), 'status' => 'in_progress'), array('task' => __('Upload to Media Library', 'ai-auto-tool'), 'status' => 'pending'), array('task' => __('Set as featured image', 'ai-auto-tool'), 'status' => 'pending'), ); foreach ($posts_without_thumbs as $item) { $this->update_progress($processed, $total, $generated, $item->post_id, __('Generating thumbnail...', 'ai-auto-tool'), $item->post_title, $todo_list); if ($processed === 0) $todo_list[1]['status'] = 'in_progress'; if ($processed > $total / 2) $todo_list[2]['status'] = 'in_progress'; $attachment_id = $this->generate_thumbnail_ai($item->post_id, $item->post_title); if ($attachment_id) { set_post_thumbnail($item->post_id, $attachment_id); $wpdb->update($this->table_name_thumbs, array('status' => 'generated', 'ai_generated' => 1, 'thumbnail_id' => $attachment_id, 'generated_at' => current_time('mysql')), array('post_id' => $item->post_id), array('%s', '%d', '%d', '%s'), array('%d') ); $generated++; } $processed++; } $todo_list[1]['status'] = 'completed'; $todo_list[2]['status'] = 'completed'; sleep(1); delete_transient('aiautotool_scan_progress'); return array('success' => true, 'posts_processed' => $processed, 'generated_count' => $generated); } /** * Generate AI thumbnail using Pollinations API with AI-enhanced prompt * * Uses Gemini/Bard AI to create optimized image prompt, then generates * high-quality thumbnail using Pollinations.ai * * @param int $post_id Post ID * @param string $title Post title * @return int|false Attachment ID on success, false on failure */ private function generate_thumbnail_ai($post_id, $title) { $post = get_post($post_id); if (!$post) return false; // Get post content excerpt $content_excerpt = wp_trim_words(strip_tags($post->post_content), 50); // Use AI to generate optimized image prompt $image_prompt = $this->generate_image_prompt_with_ai($title, $content_excerpt); // Fallback to simple prompt if AI fails if (empty($image_prompt)) { $image_prompt = $title . ', professional illustration, high quality, detailed, modern design'; } // Clean and encode prompt for Pollinations API $encoded_prompt = urlencode($image_prompt); // Pollinations API URL with optimal parameters $api_url = "https://image.pollinations.ai/prompt/{$encoded_prompt}?width=1200&height=630&nologo=true&enhance=true&model=flux"; // Download image with retry mechanism $max_retries = 2; $image_data = false; for ($i = 0; $i < $max_retries; $i++) { $response = wp_remote_get($api_url, array( 'timeout' => 30, 'sslverify' => false, 'headers' => array( 'User-Agent' => 'WordPress/' . get_bloginfo('version') . '; ' . home_url() ) )); if (!is_wp_error($response)) { $image_data = wp_remote_retrieve_body($response); if (!empty($image_data) && strlen($image_data) > 1000) { break; // Success } } // Wait before retry if ($i < $max_retries - 1) { sleep(2); } } if (empty($image_data)) return false; // Save to uploads directory $upload_dir = wp_upload_dir(); $safe_title = sanitize_file_name(substr($title, 0, 50)); $filename = $safe_title . '_ai_thumb_' . time() . '.png'; $file_path = $upload_dir['path'] . '/' . $filename; file_put_contents($file_path, $image_data); if (!file_exists($file_path)) return false; // Verify it's a valid image $image_size = @getimagesize($file_path); if ($image_size === false) { @unlink($file_path); return false; } // Create WordPress attachment $filetype = wp_check_filetype($filename); $attachment = array( 'guid' => $upload_dir['url'] . '/' . $filename, 'post_mime_type' => $filetype['type'], 'post_title' => $title, 'post_content' => 'AI-generated thumbnail: ' . $image_prompt, 'post_excerpt' => 'Generated by Pollinations AI', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment($attachment, $file_path, $post_id); if ($attachment_id) { require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata($attachment_id, $file_path); wp_update_attachment_metadata($attachment_id, $attach_data); // Set alt text update_post_meta($attachment_id, '_wp_attachment_image_alt', $title); // Store the prompt used update_post_meta($attachment_id, '_ai_image_prompt', $image_prompt); update_post_meta($attachment_id, '_ai_generated', 1); return $attachment_id; } return false; } /** * Generate optimized image prompt using AI * * Uses Gemini/Bard to create detailed, optimized prompt for image generation * * @param string $title Post title * @param string $content Post content excerpt * @return string AI-generated image prompt */ private function generate_image_prompt_with_ai($title, $content) { try { // Initialize Bard/Gemini content generator if (!class_exists('BardGenContent')) { require_once(plugin_dir_path(dirname(__FILE__)) . 'lib/bard.php'); } $bardGenContent = new BardGenContent(); // Create instruction for AI to generate image prompt $instruction = "Create a concise, visual description for a thumbnail image based on this article. Article Title: {$title} Article Excerpt: {$content} Generate a detailed image prompt (max 100 words) that describes: - Main subject/theme - Visual style (professional, modern, clean) - Colors and mood - Composition Output ONLY the image prompt, no explanations. Make it suitable for AI image generation."; // Call AI to generate prompt $ai_response = $bardGenContent->bardcontentRaw($instruction, 'English'); if (!empty($ai_response) && is_string($ai_response)) { // Clean up response $prompt = trim(strip_tags($ai_response)); $prompt = preg_replace('/\s+/', ' ', $prompt); // Limit length if (strlen($prompt) > 300) { $prompt = substr($prompt, 0, 300); } // Add quality enhancers $prompt .= ', professional, high quality, detailed'; return $prompt; } } catch (Exception $e) { // Log error but continue with fallback } // Fallback: Simple prompt from title return $title . ', professional article thumbnail, modern design, clean, high quality'; } /** * AJAX: Fix missing alt text */ public function ajax_fix_missing_alt() { check_ajax_referer('aiautotool_nonce', 'security'); if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => __('Permission denied', 'ai-auto-tool'))); } $result = $this->fix_all_missing_alt(); if ($result['success']) { wp_send_json_success(array( 'message' => sprintf( __('Added alt text to %d images in %d posts!', 'ai-auto-tool'), $result['fixed_count'], $result['posts_fixed'] ) )); } else { wp_send_json_error(array('message' => $result['message'])); } } /** * Fix all missing alt text using AI * * Generates unique, SEO-friendly alt text for each image using AI * - Max 70 characters * - Includes relevant keywords from post * - Each image gets unique alt text */ private function fix_all_missing_alt() { global $wpdb; set_time_limit(0); $items = $wpdb->get_results("SELECT * FROM {$this->table_name_alt} WHERE status='pending'"); if (empty($items)) { return array('success' => false, 'message' => __('No images with missing alt text', 'ai-auto-tool')); } $fixed = 0; $posts_data = array(); $used_alts = array(); // Track used alt texts to ensure uniqueness // Group by post to process efficiently foreach ($items as $item) { if (!isset($posts_data[$item->post_id])) { $posts_data[$item->post_id] = array( 'post' => get_post($item->post_id), 'images' => array(), 'image_count' => 0 ); } $posts_data[$item->post_id]['images'][] = $item; $posts_data[$item->post_id]['image_count']++; } // Process each post foreach ($posts_data as $post_id => $data) { $post = $data['post']; if (!$post) continue; $content = $post->post_content; $updated = false; // Process each image in this post foreach ($data['images'] as $index => $item) { // Generate unique AI alt text for this specific image $alt_text = $this->generate_alt_text_with_ai( $post->post_title, $item->image_url, $index + 1, // Image number in post $data['image_count'], // Total images in post $used_alts // Previously used alt texts ); // Ensure uniqueness $original_alt = $alt_text; $counter = 1; while (in_array($alt_text, $used_alts)) { $alt_text = $original_alt . ' ' . $counter; $counter++; // Trim if too long if (strlen($alt_text) > 70) { $alt_text = substr($original_alt, 0, 65) . ' ' . $counter; } } // Add to used alts $used_alts[] = $alt_text; // Replace in content - match the specific img tag $pattern = '/]*src=["\']' . preg_quote($item->image_url, '/') . '["\'][^>]*)>/i'; if (preg_match($pattern, $content, $matches)) { $img_tag = $matches[0]; // Check if already has alt if (preg_match('/alt=["\'][^"\']*["\']/', $img_tag)) { // Has alt but empty, replace it $new_tag = preg_replace('/alt=["\']\s*["\']/', 'alt="' . esc_attr($alt_text) . '"', $img_tag); } else { // No alt attribute, add it $new_tag = str_replace('update( $this->table_name_alt, array('status' => 'fixed', 'fixed_at' => current_time('mysql')), array('id' => $item->id), array('%s', '%s'), array('%d') ); $fixed++; } } // Update post content if any changes made if ($updated) { wp_update_post(array( 'ID' => $post->ID, 'post_content' => $content )); } } return array('success' => true, 'fixed_count' => $fixed, 'posts_fixed' => count($posts_data)); } /** * Generate unique alt text using AI * * Creates SEO-friendly, descriptive alt text for images: * - Max 70 characters * - Includes post keywords * - Unique for each image * - Context-aware * * @param string $post_title Post title * @param string $image_url Image URL (for context) * @param int $image_number Position of image in post (1-based) * @param int $total_images Total images in post * @param array $used_alts Already used alt texts * @return string Generated alt text */ private function generate_alt_text_with_ai($post_title, $image_url, $image_number, $total_images, $used_alts = array()) { try { // Initialize Bard/Gemini if (!class_exists('BardGenContent')) { require_once(plugin_dir_path(dirname(__FILE__)) . 'lib/bard.php'); } $bardGenContent = new BardGenContent(); // Get image filename for context $image_filename = basename($image_url); $image_name = pathinfo($image_filename, PATHINFO_FILENAME); // Create instruction for AI $instruction = "Generate a unique, SEO-friendly alt text for an image. Article Title: {$post_title} Image Position: Image {$image_number} of {$total_images} in the article Image Filename: {$image_name} Requirements: - Maximum 70 characters (strict limit) - Include relevant keywords from the article title - Describe what the image likely shows (based on context) - Be specific and descriptive - SEO-optimized - Natural language Output ONLY the alt text, nothing else. No quotes, no explanations."; // Call AI $ai_response = $bardGenContent->bardcontentRaw($instruction, 'English'); if (!empty($ai_response) && is_string($ai_response)) { // Clean response $alt_text = trim(strip_tags($ai_response)); $alt_text = str_replace(array('"', "'", "\n", "\r"), '', $alt_text); $alt_text = preg_replace('/\s+/', ' ', $alt_text); // Ensure max 70 characters if (strlen($alt_text) > 70) { $alt_text = substr($alt_text, 0, 67) . '...'; } // Remove common AI response prefixes $prefixes_to_remove = array( 'Alt text: ', 'Image alt text: ', 'Alt: ', 'Description: ', ); foreach ($prefixes_to_remove as $prefix) { if (stripos($alt_text, $prefix) === 0) { $alt_text = trim(substr($alt_text, strlen($prefix))); } } // Final length check if (strlen($alt_text) > 70) { $alt_text = substr($alt_text, 0, 67) . '...'; } // Ensure it's not empty and not duplicate if (!empty($alt_text) && strlen($alt_text) > 5 && !in_array($alt_text, $used_alts)) { return $alt_text; } } } catch (Exception $e) { } // Fallback: Create descriptive alt from post title + position $fallback_alt = $post_title; // Add context based on position if ($total_images > 1) { if ($image_number == 1) { $fallback_alt .= ' - featured image'; } elseif ($image_number == $total_images) { $fallback_alt .= ' - conclusion'; } else { $fallback_alt .= ' - figure ' . $image_number; } } // Trim to 70 characters if (strlen($fallback_alt) > 70) { $fallback_alt = substr($fallback_alt, 0, 67) . '...'; } return $fallback_alt; } }