namespace, '/regenerate/(?P[\d]+)', array( array( 'methods' => WP_REST_Server::ALLMETHODS, 'callback' => array($this, 'regenerate_item'), 'permission_callback' => array($this, 'permissions_check'), 'args' => array( 'use_ai' => array( 'description' => __('Whether to use AI for generation.', 'ai-thumbnails-maker'), 'type' => 'boolean', 'default' => false, ), 'ai_service' => array( 'description' => __('AI service to use for generation.', 'ai-thumbnails-maker'), 'type' => 'string', 'default' => '', ), 'only_regenerate_missing_thumbnails' => array( 'description' => __('Whether to only regenerate missing thumbnails.', 'ai-thumbnails-maker'), 'type' => 'boolean', 'default' => true, ), 'delete_unregistered_thumbnail_files' => array( 'description' => __('Whether to delete unregistered thumbnail files.', 'ai-thumbnails-maker'), 'type' => 'boolean', 'default' => false, ), ), ), )); // Get attachment info endpoint register_rest_route($this->namespace, '/attachmentinfo/(?P[\d]+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array($this, 'attachment_info'), 'permission_callback' => array($this, 'permissions_check'), ), )); // Get statistics endpoint register_rest_route($this->namespace, '/statistics', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array($this, 'get_statistics'), 'permission_callback' => array($this, 'permissions_check'), 'args' => $this->get_paging_collection_params(), ), )); // Get featured images endpoint register_rest_route($this->namespace, '/featuredimages', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array($this, 'featured_images'), 'permission_callback' => array($this, 'permissions_check'), 'args' => $this->get_paging_collection_params(), ), )); // Test AI service endpoint register_rest_route($this->namespace, '/test-ai-service', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array($this, 'test_ai_service'), 'permission_callback' => array($this, 'permissions_check'), 'args' => array( 'service' => array( 'description' => __('AI service to test.', 'ai-thumbnails-maker'), 'type' => 'string', 'required' => true, ), ), ), )); // Save settings endpoint register_rest_route($this->namespace, '/settings', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array($this, 'save_settings'), 'permission_callback' => array($this, 'permissions_check'), 'args' => array( 'settings' => array( 'description' => __('Plugin settings.', 'ai-thumbnails-maker'), 'type' => 'object', 'required' => true, ), ), ), )); } /** * Register filters for media queries. */ public function register_filters() { add_filter('rest_attachment_query', array($this, 'maybe_filter_out_site_icons'), 10, 2); add_filter('rest_attachment_query', array($this, 'maybe_filter_mime_types'), 10, 2); } /** * Filter out site icons if requested. * * @param array $args Query args. * @param WP_REST_Request $request The request. * @return array */ public function maybe_filter_out_site_icons($args, $request) { if (empty($request['exclude_site_icons'])) { return $args; } if (!isset($args['meta_query'])) { $args['meta_query'] = array(); } $args['meta_query'][] = array( 'key' => '_wp_attachment_context', 'value' => 'site-icon', 'compare' => 'NOT EXISTS', ); return $args; } /** * Filter mime types if requested. * * @param array $args Query args. * @param WP_REST_Request $request The request. * @return array */ public function maybe_filter_mime_types($args, $request) { if (empty($request['is_regeneratable'])) { return $args; } $args['post_mime_type'] = array(); foreach (get_allowed_mime_types() as $mime_type) { if ('image/svg+xml' === $mime_type) { continue; } if ('application/pdf' == $mime_type || 'image/' == substr($mime_type, 0, 6)) { $args['post_mime_type'][] = $mime_type; } } return $args; } /** * Get paging collection parameters. * * @return array */ public function get_paging_collection_params() { return array_intersect_key( parent::get_collection_params(), array_flip(array('page', 'per_page')) ); } /** * Regenerate thumbnails for a specific attachment. * * @param WP_REST_Request $request Full data about the request. * @return WP_REST_Response|WP_Error */ public function regenerate_item($request) { $regenerator = AITM_Regenerator::get_instance($request->get_param('id')); if (is_wp_error($regenerator)) { return $regenerator; } $result = $regenerator->regenerate( $request->get_param('use_ai'), $request->get_param('ai_service'), array( 'only_regenerate_missing_thumbnails' => $request->get_param('only_regenerate_missing_thumbnails'), 'delete_unregistered_thumbnail_files' => $request->get_param('delete_unregistered_thumbnail_files'), ) ); if (is_wp_error($result)) { return $result; } return $this->attachment_info($request); } /** * Get attachment information. * * @param WP_REST_Request $request Full data about the request. * @return WP_REST_Response|WP_Error */ public function attachment_info($request) { $regenerator = AITM_Regenerator::get_instance($request->get_param('id')); if (is_wp_error($regenerator)) { return $regenerator; } $info = $this->get_attachment_info($regenerator); if (is_wp_error($info)) { return $info; } return rest_ensure_response($info); } /** * Get attachment information for display. * * @param AITM_Regenerator $regenerator Regenerator instance. * @return array|WP_Error */ private function get_attachment_info($regenerator) { $fullsizepath = $regenerator->get_fullsizepath(); if (is_wp_error($fullsizepath)) { return $fullsizepath; } $editor = wp_get_image_editor($fullsizepath); if (is_wp_error($editor)) { if ('image_no_editor' === $editor->get_error_code()) { $editor = new WP_Error('image_no_editor', __('The current image editor cannot process this file type.', 'ai-thumbnails-maker')); } $editor->add_data(array( 'attachment' => $regenerator->attachment, 'status' => 415, )); return $editor; } $metadata = wp_get_attachment_metadata($regenerator->attachment->ID); if (false === $metadata || !is_array($metadata)) { return new WP_Error( 'aitm_no_metadata', __('Unable to load the metadata for this attachment.', 'ai-thumbnails-maker'), array( 'status' => 404, 'attachment' => $regenerator->attachment, ) ); } if (!isset($metadata['sizes'])) { $metadata['sizes'] = array(); } $width = isset($metadata['width']) ? $metadata['width'] : null; $height = isset($metadata['height']) ? $metadata['height'] : null; // Load image functions if not already available if (!function_exists('file_is_displayable_image')) { require_once(ABSPATH . 'wp-admin/includes/image.php'); } $preview = false; if (file_is_displayable_image($fullsizepath)) { $preview = wp_get_attachment_url($regenerator->attachment->ID); } $response = array( 'id' => $regenerator->attachment->ID, // translators: %d is the attachment ID number 'name' => $regenerator->attachment->post_title ? $regenerator->attachment->post_title : sprintf(__('Attachment %d', 'ai-thumbnails-maker'), $regenerator->attachment->ID), 'preview' => $preview, 'relative_path' => _wp_get_attachment_relative_path($fullsizepath) . DIRECTORY_SEPARATOR . wp_basename($fullsizepath), 'edit_url' => get_edit_post_link($regenerator->attachment->ID, 'raw'), 'width' => $width, 'height' => $height, 'registered_sizes' => array(), 'unregistered_sizes' => array(), ); $wp_upload_dir = dirname($fullsizepath) . DIRECTORY_SEPARATOR; $registered_sizes = $this->get_thumbnail_sizes(); // Check registered sizes foreach ($registered_sizes as $size) { if ($width && $height) { $thumbnail = $regenerator->get_thumbnail($editor, $width, $height, $size['width'], $size['height'], $size['crop']); if ($thumbnail) { $size['filename'] = wp_basename($thumbnail['filename']); $size['fileexists'] = file_exists($thumbnail['filename']); } else { $size['filename'] = false; $size['fileexists'] = false; } } elseif (!empty($metadata['sizes'][$size['label']]['file'])) { $size['filename'] = wp_basename($metadata['sizes'][$size['label']]['file']); $size['fileexists'] = file_exists($wp_upload_dir . $metadata['sizes'][$size['label']]['file']); } else { $size['filename'] = false; $size['fileexists'] = false; } $response['registered_sizes'][] = $size; } // Check unregistered sizes foreach ($metadata['sizes'] as $label => $size) { if (!file_exists($wp_upload_dir . $size['file'])) { continue; } // Skip if this size is registered $is_registered = false; foreach ($response['registered_sizes'] as $registered_size) { if ($size['file'] === $registered_size['filename']) { $is_registered = true; break; } } if ($is_registered) { continue; } if (!empty($registered_sizes[$label])) { // translators: %s is the thumbnail size name $label = sprintf(__('%s (old)', 'ai-thumbnails-maker'), $label); } $response['unregistered_sizes'][] = array( 'label' => $label, 'width' => $size['width'], 'height' => $size['height'], 'filename' => $size['file'], 'fileexists' => true, ); } return $response; } /** * 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; } /** * Get statistics. * * @param WP_REST_Request $request Full data about the request. * @return WP_REST_Response|WP_Error */ public function get_statistics($request) { $statistics_manager = new AITM_Statistics_Manager(); $statistics = $statistics_manager->get_statistics($request->get_param('page'), $request->get_param('per_page')); return rest_ensure_response($statistics); } /** * Get featured images. * * @param WP_REST_Request $request Full data about the request. * @return WP_REST_Response|WP_Error */ public function featured_images($request) { global $wpdb; $page = $request->get_param('page'); $per_page = $request->get_param('per_page'); if (0 == $per_page) { $per_page = 10; } $cache_key = 'aitm_featured_images_' . $page . '_' . $per_page; $featured_image_ids = wp_cache_get($cache_key, 'aitm_rest'); if (false === $featured_image_ids) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Query with caching for featured images $featured_image_ids = $wpdb->get_results($wpdb->prepare( "SELECT SQL_CALC_FOUND_ROWS meta_value AS id FROM {$wpdb->postmeta} WHERE meta_key = '_thumbnail_id' GROUP BY meta_value ORDER BY MIN(meta_id) LIMIT %d OFFSET %d", $per_page, ($per_page * $page) - $per_page )); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- FOUND_ROWS() must be called immediately $total = $wpdb->get_var("SELECT FOUND_ROWS()"); wp_cache_set($cache_key, $featured_image_ids, 'aitm_rest', 300); // Cache for 5 minutes } else { // Get total from cache metadata or recalculate $cache_key_total = 'aitm_featured_images_total_' . $per_page; $total = wp_cache_get($cache_key_total, 'aitm_rest'); if (false === $total) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Count query $total = $wpdb->get_var("SELECT COUNT(DISTINCT meta_value) FROM {$wpdb->postmeta} WHERE meta_key = '_thumbnail_id'"); wp_cache_set($cache_key_total, $total, 'aitm_rest', 300); } } $max_pages = ceil($total / $per_page); if ($page > $max_pages && $total > 0) { return new WP_Error('rest_post_invalid_page_number', __('The page number requested is larger than the number of pages available.', 'ai-thumbnails-maker'), array('status' => 400)); } $response = rest_ensure_response($featured_image_ids); $response->header('X-WP-Total', (int) $total); $response->header('X-WP-TotalPages', (int) $max_pages); $request_params = $request->get_query_params(); $base = add_query_arg($request_params, rest_url($this->namespace . '/featuredimages')); if ($page > 1) { $prev_page = $page - 1; if ($prev_page > $max_pages) { $prev_page = $max_pages; } $prev_link = add_query_arg('page', $prev_page, $base); $response->link_header('prev', $prev_link); } if ($max_pages > $page) { $next_page = $page + 1; $next_link = add_query_arg('page', $next_page, $base); $response->link_header('next', $next_link); } return $response; } /** * Test AI service. * * @param WP_REST_Request $request Full data about the request. * @return WP_REST_Response|WP_Error */ public function test_ai_service($request) { $service_name = $request->get_param('service'); // Get service instance directly $services = array( 'dall_e_3' => 'AITM_AI_DALL_E', 'midjourney' => 'AITM_AI_Midjourney', ); if (!isset($services[$service_name])) { return new WP_Error('aitm_service_not_found', __('AI service not found.', 'ai-thumbnails-maker')); } $service_class = $services[$service_name]; if (!class_exists($service_class)) { return new WP_Error('aitm_service_class_not_found', __('AI service class not found.', 'ai-thumbnails-maker')); } $service_instance = new $service_class(); $result = $service_instance->test_connection(); if (is_wp_error($result)) { return $result; } return rest_ensure_response(array('message' => __('AI service test successful.', 'ai-thumbnails-maker'))); } /** * Save settings. * * @param WP_REST_Request $request Full data about the request. * @return WP_REST_Response|WP_Error */ public function save_settings($request) { $settings = $request->get_param('settings'); $result = update_option('aitm_settings', $settings); if ($result) { return rest_ensure_response(array('message' => __('Settings saved successfully.', 'ai-thumbnails-maker'))); } else { return new WP_Error('aitm_save_settings_failed', __('Failed to save settings.', 'ai-thumbnails-maker'), array('status' => 500)); } } /** * Check permissions. * * @param WP_REST_Request $request Full data about the request. * @return bool */ public function permissions_check($request) { return current_user_can(aitm()->capability); } }