404) ); } if ('attachment' !== get_post_type($attachment)) { return new WP_Error( 'aitm_regenerator_not_attachment', __('This item is not an attachment.', 'ai-thumbnails-maker'), array('status' => 400) ); } if (self::is_site_icon($attachment)) { return new WP_Error( 'aitm_regenerator_is_site_icon', __('This attachment is a site icon and should not be processed.', 'ai-thumbnails-maker'), array('status' => 415) ); } return new AITM_Regenerator($attachment); } /** * Constructor. * * @param WP_Post $attachment The attachment post object. */ private function __construct(WP_Post $attachment) { $this->attachment = $attachment; } /** * Check if attachment is a site icon. * * @param WP_Post $attachment The attachment post object. * @return bool */ public static function is_site_icon(WP_Post $attachment) { return ('site-icon' === get_post_meta($attachment->ID, '_wp_attachment_context', true)); } /** * Get AI service manager instance. * * @return AITM_AI_Service_Manager */ private function get_ai_service_manager() { if (!$this->ai_service_manager) { $this->ai_service_manager = new AITM_AI_Service_Manager(); } return $this->ai_service_manager; } /** * Get statistics manager instance. * * @return AITM_Statistics_Manager */ private function get_statistics_manager() { if (!$this->statistics_manager) { $this->statistics_manager = new AITM_Statistics_Manager(); } return $this->statistics_manager; } /** * Get the full size image path. * * @return string|WP_Error */ public function get_fullsizepath() { if ($this->fullsizepath) { return $this->fullsizepath; } if (function_exists('wp_get_original_image_path')) { $this->fullsizepath = wp_get_original_image_path($this->attachment->ID); } else { $this->fullsizepath = get_attached_file($this->attachment->ID); } if (false === $this->fullsizepath || !file_exists($this->fullsizepath)) { $error = new WP_Error( 'aitm_regenerator_file_not_found', sprintf( // translators: %s is the file path __('The fullsize image file cannot be found at %s.', 'ai-thumbnails-maker'), _wp_relative_upload_path($this->fullsizepath) ), array( 'status' => 404, 'fullsizepath' => _wp_relative_upload_path($this->fullsizepath), 'attachment' => $this->attachment, ) ); $this->fullsizepath = $error; } return $this->fullsizepath; } /** * Regenerate thumbnails for the attachment. * * @param bool $use_ai Whether to use AI for generation. * @param string $ai_service AI service to use. * @param array $args Additional arguments. * @return array|WP_Error */ public function regenerate($use_ai = false, $ai_service = '', $args = array()) { $args = wp_parse_args($args, array( 'only_regenerate_missing_thumbnails' => true, 'delete_unregistered_thumbnail_files' => false, 'update_post_contents' => false, )); $fullsizepath = $this->get_fullsizepath(); if (is_wp_error($fullsizepath)) { return $fullsizepath; } $old_metadata = wp_get_attachment_metadata($this->attachment->ID); // If using AI, try to generate new thumbnails if ($use_ai && $ai_service) { // Check if AI generation is enabled $settings = get_option('aitm_settings', array()); if (!isset($settings['enable_ai_generation']) || !$settings['enable_ai_generation']) { // AI generation is disabled, fall back to regular regeneration $use_ai = false; } else { $ai_result = $this->generate_ai_thumbnails($ai_service, $fullsizepath); if (is_wp_error($ai_result)) { // Don't log AI regeneration failures - only log Auto Featured Image operations // $this->log_generation_result('ai', $ai_service, false, $ai_result->get_error_message()); } else { // Don't log AI regeneration success - only log Auto Featured Image operations // $this->log_generation_result('ai', $ai_service, true); return $ai_result; } } } // Regular thumbnail regeneration if ($args['only_regenerate_missing_thumbnails']) { add_filter('intermediate_image_sizes_advanced', array($this, 'filter_image_sizes_to_only_missing_thumbnails'), 10, 2); } // Load image functions if not already available if (!function_exists('wp_generate_attachment_metadata')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); } $new_metadata = wp_generate_attachment_metadata($this->attachment->ID, $fullsizepath); if ($args['only_regenerate_missing_thumbnails']) { remove_filter('intermediate_image_sizes_advanced', array($this, 'filter_image_sizes_to_only_missing_thumbnails'), 10); } // Handle unregistered thumbnail files if ($args['delete_unregistered_thumbnail_files']) { $this->delete_unregistered_thumbnail_files($old_metadata, $new_metadata, $fullsizepath); } wp_update_attachment_metadata($this->attachment->ID, $new_metadata); // Don't log regular regeneration - only log Auto Featured Image operations // $this->log_generation_result('regular', '', true); return $new_metadata; } /** * Generate thumbnails using AI service. * * @param string $ai_service AI service to use. * @param string $fullsizepath Path to the full size image. * @return array|WP_Error */ private function generate_ai_thumbnails($ai_service, $fullsizepath) { $ai_service_instance = $this->get_ai_service_manager()->get_service($ai_service); if (is_wp_error($ai_service_instance)) { return $ai_service_instance; } // Get thumbnail sizes $thumbnail_sizes = $this->get_thumbnail_sizes(); // Generate prompt based on image content $prompt = $this->generate_ai_prompt($fullsizepath); $generated_images = array(); foreach ($thumbnail_sizes as $size_name => $size_data) { $result = $ai_service_instance->generate_thumbnail( $prompt, $size_data['width'], $size_data['height'], $size_data['crop'] ); if (is_wp_error($result)) { continue; } $generated_images[$size_name] = $result; } if (empty($generated_images)) { return new WP_Error( 'aitm_ai_generation_failed', __('Failed to generate any thumbnails using AI.', 'ai-thumbnails-maker') ); } // Save generated images and update metadata return $this->save_generated_thumbnails($generated_images); } /** * Generate AI prompt based on image content. * * @param string $image_path Path to the image. * @return string */ private function generate_ai_prompt($image_path) { // This is a simplified version. In a real implementation, // you might use image analysis to generate better prompts. $filename = basename($image_path); $name_without_ext = pathinfo($filename, PATHINFO_FILENAME); // Clean up filename to create a basic prompt $prompt = str_replace(array('-', '_'), ' ', $name_without_ext); $prompt = ucwords($prompt); // Add context based on post type if this is a featured image $post_id = $this->get_associated_post_id(); if ($post_id) { $post_type = get_post_type($post_id); $post_title = get_the_title($post_id); if ($post_title) { $prompt = $post_title . ' - ' . $prompt; } } return $prompt; } /** * Get the post ID associated with this attachment. * * @return int|null */ private function get_associated_post_id() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time query for post relation $post_id = $wpdb->get_var($wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_thumbnail_id' AND meta_value = %d LIMIT 1", $this->attachment->ID )); return $post_id ? intval($post_id) : null; } /** * Save generated thumbnails to the filesystem. * * @param array $generated_images Array of generated images. * @return array|WP_Error */ private function save_generated_thumbnails($generated_images) { $upload_dir = wp_upload_dir(); $attachment_dir = dirname($this->get_fullsizepath()); $new_metadata = wp_get_attachment_metadata($this->attachment->ID); if (!$new_metadata) { $new_metadata = array(); } if (!isset($new_metadata['sizes'])) { $new_metadata['sizes'] = array(); } foreach ($generated_images as $size_name => $image_data) { $filename = $this->generate_thumbnail_filename($size_name, $image_data); $file_path = $attachment_dir . '/' . $filename; // Save the image file if (file_put_contents($file_path, $image_data['content'])) { $new_metadata['sizes'][$size_name] = array( 'file' => $filename, 'width' => $image_data['width'], 'height' => $image_data['height'], 'mime-type' => $image_data['mime_type'], ); } } wp_update_attachment_metadata($this->attachment->ID, $new_metadata); return $new_metadata; } /** * Generate filename for thumbnail. * * @param string $size_name Thumbnail size name. * @param array $image_data Image data. * @return string */ private function generate_thumbnail_filename($size_name, $image_data) { $original_filename = basename($this->get_fullsizepath()); $pathinfo = pathinfo($original_filename); $suffix = $image_data['width'] . 'x' . $image_data['height']; $extension = $pathinfo['extension']; return $pathinfo['filename'] . '-' . $suffix . '.' . $extension; } /** * Filter image sizes to only missing thumbnails. * * @param array $sizes Image sizes. * @param array $fullsize_metadata Full size metadata. * @return array */ public function filter_image_sizes_to_only_missing_thumbnails($sizes, $fullsize_metadata) { if (!$sizes) { return $sizes; } $fullsizepath = $this->get_fullsizepath(); if (is_wp_error($fullsizepath)) { return $sizes; } $editor = wp_get_image_editor($fullsizepath); if (is_wp_error($editor)) { return $sizes; } $metadata = wp_get_attachment_metadata($this->attachment->ID); foreach ($sizes as $size => $size_data) { if (empty($metadata['sizes'][$size])) { continue; } if (!isset($size_data['width']) && !isset($size_data['height'])) { continue; } if (!isset($size_data['width'])) { $size_data['width'] = null; } if (!isset($size_data['height'])) { $size_data['height'] = null; } if (!isset($size_data['crop'])) { $size_data['crop'] = false; } $thumbnail = $this->get_thumbnail( $editor, $fullsize_metadata['width'], $fullsize_metadata['height'], $size_data['width'], $size_data['height'], $size_data['crop'] ); if ( false === $thumbnail || ( $thumbnail['width'] === $metadata['sizes'][$size]['width'] && $thumbnail['height'] === $metadata['sizes'][$size]['height'] && file_exists($thumbnail['filename']) ) ) { unset($sizes[$size]); } } return $sizes; } /** * Get thumbnail dimensions and filename. * * @param WP_Image_Editor $editor Image editor instance. * @param int $fullsize_width Full size width. * @param int $fullsize_height Full size height. * @param int $thumbnail_width Thumbnail width. * @param int $thumbnail_height Thumbnail height. * @param bool $crop Whether to crop. * @return array|false */ public function get_thumbnail($editor, $fullsize_width, $fullsize_height, $thumbnail_width, $thumbnail_height, $crop) { $dims = image_resize_dimensions($fullsize_width, $fullsize_height, $thumbnail_width, $thumbnail_height, $crop); if (!$dims) { return false; } list(, , , , $dst_w, $dst_h) = $dims; $suffix = "{$dst_w}x{$dst_h}"; $file_ext = strtolower(pathinfo($this->get_fullsizepath(), PATHINFO_EXTENSION)); return array( 'filename' => $editor->generate_filename($suffix, null, $file_ext), 'width' => $dst_w, 'height' => $dst_h, ); } /** * Get thumbnail sizes. * * @return array */ private function get_thumbnail_sizes() { global $_wp_additional_image_sizes; $thumbnail_sizes = array(); foreach (get_intermediate_image_sizes() as $size) { $thumbnail_sizes[$size]['label'] = $size; if (in_array($size, array('thumbnail', 'medium', 'medium_large', 'large'))) { $thumbnail_sizes[$size]['width'] = (int) get_option($size . '_size_w'); $thumbnail_sizes[$size]['height'] = (int) get_option($size . '_size_h'); $thumbnail_sizes[$size]['crop'] = ('thumbnail' == $size) ? (bool) get_option('thumbnail_crop') : false; } elseif (!empty($_wp_additional_image_sizes) && !empty($_wp_additional_image_sizes[$size])) { $thumbnail_sizes[$size]['width'] = (int) $_wp_additional_image_sizes[$size]['width']; $thumbnail_sizes[$size]['height'] = (int) $_wp_additional_image_sizes[$size]['height']; $thumbnail_sizes[$size]['crop'] = (bool) $_wp_additional_image_sizes[$size]['crop']; } } return $thumbnail_sizes; } /** * Delete unregistered thumbnail files. * * @param array $old_metadata Old metadata. * @param array $new_metadata New metadata. * @param string $fullsizepath Full size path. */ private function delete_unregistered_thumbnail_files($old_metadata, $new_metadata, $fullsizepath) { global $wpdb; $wp_upload_dir = dirname($fullsizepath) . DIRECTORY_SEPARATOR; $intermediate_image_sizes = get_intermediate_image_sizes(); foreach ($old_metadata['sizes'] as $old_size => $old_size_data) { if (in_array($old_size, $intermediate_image_sizes)) { continue; } wp_delete_file($wp_upload_dir . $old_size_data['file']); unset($new_metadata['sizes'][$old_size]); } } /** * Log generation result to statistics. * * @param string $method Generation method. * @param string $ai_service AI service used. * @param bool $success Whether generation was successful. * @param string $error_message Error message if failed. */ private function log_generation_result($method, $ai_service, $success, $error_message = '') { $post_id = $this->get_associated_post_id(); $post_type = $post_id ? get_post_type($post_id) : null; $this->get_statistics_manager()->log_generation( $this->attachment->ID, $post_id, $post_type, $method, $ai_service, $success, $error_message ); } }