settings = $settings; $this->generator = $generator; add_action('rest_api_init', array($this, 'register_routes')); // After Settings::enqueue_scripts() has localized aifiBulkData. add_action('admin_enqueue_scripts', array($this, 'add_script_strings'), 20); // Register bulk actions for enabled post types $post_types = $this->settings->get_enabled_post_types(); foreach ($post_types as $post_type) { add_filter("bulk_actions-edit-{$post_type}", array($this, 'register_bulk_action')); add_filter("handle_bulk_actions-edit-{$post_type}", array($this, 'handle_bulk_action'), 10, 3); } } /** * Check if user has premium license. * * @return bool */ private function is_premium_user() { return Providers::can_use_premium(); } /** * Whether the user may open the Bulk Generate tab: the plugin settings capability. * * @return bool */ private function can_manage_bulk() { return current_user_can(is_multisite() ? 'manage_network_options' : 'manage_options'); } /** * The provider a bulk, Posts list or automatic generation will use, checked before any * paid request. A Pro-only provider without a usable licence gets the same premium_required * error Generator::generate_image() returns; an unknown slug means OpenAI, as in the Generator. * * @param array $settings Plugin settings. * @return string|\WP_Error Provider slug, or a premium_required error. */ public static function usable_provider($settings) { $provider = (isset($settings['ai_provider']) && is_string($settings['ai_provider'])) ? $settings['ai_provider'] : 'openai'; if ( ! Providers::is_registered($provider)) { return 'openai'; } if ( ! Providers::is_available($provider)) { return new \WP_Error( 'premium_required', sprintf( /* translators: %s: provider name */ __('%s is a Pro feature. Please upgrade to use it, or switch to OpenAI or Grok.', 'ai-featured-image-generator'), Providers::label($provider) ), array('status' => 403) ); } return $provider; } /** * Strings bulk.js shows, added to aifiBulkData.i18n. * * @return array */ public static function script_strings() { return array( 'freePlanLabel' => __('Free Plan:', 'ai-featured-image-generator'), 'freePlanText' => __('unlimited images for Posts and Pages that have no featured image yet.', 'ai-featured-image-generator'), 'loadError' => __('Error loading posts.', 'ai-featured-image-generator'), 'loadPosts' => __('Load Posts', 'ai-featured-image-generator'), 'postsFoundOne' => __('1 post found', 'ai-featured-image-generator'), /* translators: %d: number of posts found. */ 'postsFound' => __('%d posts found', 'ai-featured-image-generator'), 'noTitle' => __('(No title)', 'ai-featured-image-generator'), /* translators: %d: number of posts on all pages. */ 'totalCount' => __('%d total', 'ai-featured-image-generator'), /* translators: 1: number of selected posts, 2: number of posts listed. */ 'selectedCount' => __('%1$d / %2$d selected', 'ai-featured-image-generator'), /* translators: %d: post ID. */ 'postNumber' => __('Post #%d', 'ai-featured-image-generator'), 'unknownError' => __('Unknown error', 'ai-featured-image-generator'), /* translators: 1: post title, 2: position in the run, 3: number of posts in the run. */ 'progress' => __('Processing: "%1$s" (%2$d of %3$d)', 'ai-featured-image-generator'), ); } /** * Adds script_strings() to aifiBulkData.i18n on the screens that load bulk.js. */ public function add_script_strings() { if ( ! wp_script_is('aifi-bulk', 'enqueued')) { return; } wp_add_inline_script( 'aifi-bulk', 'window.aifiBulkData = window.aifiBulkData || {}; aifiBulkData.i18n = Object.assign( aifiBulkData.i18n || {}, ' . wp_json_encode(self::script_strings()) . ' );', 'before' ); } /** * Register bulk action on post list pages. * * @param array $actions Existing bulk actions. * @return array */ public function register_bulk_action($actions) { // The action leads to the Bulk Generate tab, which only administrators can open. if ( ! $this->can_manage_bulk()) { return $actions; } $actions['aifi_bulk_generate'] = __('Generate AI Featured Images', 'ai-featured-image-generator'); return $actions; } /** * Handle bulk action from post list. * * @param string $redirect_url Redirect URL. * @param string $action Action name. * @param array $post_ids Selected post IDs. * @return string */ public function handle_bulk_action($redirect_url, $action, $post_ids) { if ($action !== 'aifi_bulk_generate' || ! $this->can_manage_bulk()) { return $redirect_url; } $ids = implode(',', array_map('absint', $post_ids)); $nonce = wp_create_nonce('aifi_bulk_generate'); return admin_url('admin.php?page=' . $this->parent_slug . '&tab=bulk&action=generate&post_ids=' . $ids . '&_wpnonce=' . $nonce); } /** * Register REST API routes. */ public function register_routes() { register_rest_route('aifi/v1', '/bulk-generate', array( 'methods' => 'POST', 'callback' => array($this, 'bulk_generate_image'), 'permission_callback' => array($this, 'check_bulk_permission'), 'args' => array( 'post_id' => array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ), 'overwrite' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'generate_prompt' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'use_brand_kit' => array( 'required' => false, 'type' => 'boolean', 'default' => true, 'sanitize_callback' => 'rest_sanitize_boolean', ), ), )); register_rest_route('aifi/v1', '/bulk-posts', array( 'methods' => 'GET', 'callback' => array($this, 'get_bulk_posts'), 'permission_callback' => array($this, 'check_bulk_permission_read'), 'args' => array( 'post_type' => array( 'required' => false, 'type' => 'string', 'default' => 'post', 'sanitize_callback' => 'sanitize_text_field', ), 'post_status' => array( 'required' => false, 'type' => 'string', 'default' => 'publish', 'sanitize_callback' => 'sanitize_text_field', ), 'has_thumbnail' => array( 'required' => false, 'type' => 'string', 'default' => 'any', 'sanitize_callback' => 'sanitize_text_field', ), 'date_from' => array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'date_to' => array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'per_page' => array( 'required' => false, 'type' => 'integer', 'default' => 50, 'sanitize_callback' => 'absint', ), 'page' => array( 'required' => false, 'type' => 'integer', 'default' => 1, 'sanitize_callback' => 'absint', ), ), )); } /** * Permission check for bulk generate endpoint. * * @param \WP_REST_Request $request Request object. * @return bool|\WP_Error */ public function check_bulk_permission($request) { // Only the plugin's own screens may call this, not an application password. if (!wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest')) { return new \WP_Error( 'rest_forbidden', __('Invalid nonce.', 'ai-featured-image-generator'), array('status' => rest_authorization_required_code()) ); } $post_id = absint($request['post_id']); if (!current_user_can('edit_post', $post_id)) { return new \WP_Error( 'rest_forbidden', __('Sorry, you are not allowed to edit this post.', 'ai-featured-image-generator'), array('status' => rest_authorization_required_code()) ); } // Bulk Generate is an admin tool: the same people who can open its page, never a // Contributor or Author calling the route directly. if (!$this->can_manage_bulk()) { return new \WP_Error( 'rest_forbidden', __('Sorry, you are not allowed to run Bulk Generate.', 'ai-featured-image-generator'), array('status' => rest_authorization_required_code()) ); } $post = get_post($post_id); if (!$post) { return new \WP_Error( 'rest_invalid_post', __('Invalid post.', 'ai-featured-image-generator'), array('status' => 404) ); } $enabled_post_types = $this->settings->get_enabled_post_types(); if (!in_array($post->post_type, $enabled_post_types, true)) { return new \WP_Error( 'rest_post_type_not_enabled', __('AI image generation is not enabled for this post type.', 'ai-featured-image-generator'), array('status' => 403) ); } return true; } /** * Permission check for bulk posts listing endpoint. * * @param \WP_REST_Request $request Request object. * @return bool|\WP_Error */ public function check_bulk_permission_read($request) { // The listing feeds the admin-only Bulk Generate tab, and lists other authors' drafts. if ( ! $this->can_manage_bulk()) { return new \WP_Error( 'rest_forbidden', __('Sorry, you are not allowed to view posts.', 'ai-featured-image-generator'), array('status' => rest_authorization_required_code()) ); } return true; } /** * Generate image for a single post (bulk endpoint). * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function bulk_generate_image($request) { // One generation per post at a time, shared with /generate, /list-generate, // auto-generate and the assistant, so parallel requests never pay twice. $lock_key = 'aifi_lock_' . absint($request['post_id']); if (!REST::take_lock($lock_key, REST::LOCK_TTL)) { return new \WP_Error( 'rate_limited', __('An image is already being made for this post. Try again in a moment.', 'ai-featured-image-generator'), array('status' => 429) ); } try { return $this->bulk_generate_locked($request); } finally { // Released straight away: a bulk run moves on to other posts, and Retry failed // may ask for this post again at once. delete_transient($lock_key); } } /** * The /bulk-generate work, run while the per-post lock is held. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ private function bulk_generate_locked($request) { $post_id = $request['post_id']; $overwrite = $request['overwrite']; $generate_prompt = $request['generate_prompt']; $use_brand_kit = !isset($request['use_brand_kit']) || rest_sanitize_boolean($request['use_brand_kit']); // Brand Kit and overwriting existing images are Pro-only, so free users never get them regardless of what was sent. if (!$this->is_premium_user()) { $use_brand_kit = false; $overwrite = false; } $post = get_post($post_id); if (!$post) { return new \WP_Error('invalid_post', __('Post not found.', 'ai-featured-image-generator'), array('status' => 404)); } // Skip if post already has a featured image and overwrite is off if (!$overwrite && has_post_thumbnail($post_id)) { return rest_ensure_response(array( 'success' => true, 'skipped' => true, 'post_id' => $post_id, 'post_title' => $post->post_title, 'reason' => __('Post already has a featured image.', 'ai-featured-image-generator'), )); } // Check the provider and its key before any paid request. $settings_data = $this->settings->get_settings(); $provider = self::usable_provider($settings_data); if (is_wp_error($provider)) { return $provider; } if ( ! Providers::has_api_key($settings_data, $provider)) { return new \WP_Error( 'no_api_key', sprintf( /* translators: %s: provider name */ __('API key not configured for %s.', 'ai-featured-image-generator'), Providers::label($provider) ), array('status' => 400) ); } // Optionally generate a content-based prompt before creating the image $prompt = ''; if ($generate_prompt) { $prompt_result = $this->generator->generate_prompt_from_content($post_id, $use_brand_kit); if (is_wp_error($prompt_result)) { // Log the failure but do not abort, fall back to title-only generation if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { error_log('AIFI: Prompt generation failed for post ' . $post_id . ': ' . $prompt_result->get_error_message()); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } } else { $prompt = $prompt_result; update_post_meta($post_id, '_aifi_custom_prompt', wp_slash($prompt)); } } // Generate image using existing generator (pass post title for filename) $result = $this->generator->generate_image($post_id, $prompt, '', $post->post_title, '', null, $use_brand_kit); if (is_wp_error($result)) { return $result; } $response = array( 'success' => true, 'skipped' => false, 'post_id' => $post_id, 'post_title' => $post->post_title, 'attachment_id' => $result, 'url' => wp_get_attachment_url($result), ); // Surface a non-fatal WebP-conversion fallback notice, if any. $webp_notice = $this->generator->get_last_webp_notice(); if ( $webp_notice ) { $response['webp_notice'] = $webp_notice['message']; $response['webp_notice_reason'] = $webp_notice['reason']; } return rest_ensure_response($response); } /** * Get posts for bulk generation page. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response */ public function get_bulk_posts($request) { $is_premium = $this->is_premium_user(); $post_type = $request['post_type']; $post_status = $request['post_status']; // Free cannot overwrite, so it lists only the posts it can actually fill. $has_thumbnail = $is_premium ? $request['has_thumbnail'] : 'no'; $date_from = $is_premium ? $request['date_from'] : ''; $date_to = $is_premium ? $request['date_to'] : ''; $per_page = min(100, max(1, $request['per_page'])); $page = max(1, $request['page']); // Validate post type is enabled $enabled_post_types = $this->settings->get_enabled_post_types(); if (!in_array($post_type, $enabled_post_types, true)) { return new \WP_Error( 'invalid_post_type', __('This post type is not enabled for AI image generation.', 'ai-featured-image-generator'), array('status' => 400) ); } // Validate and set post status $allowed_statuses = array('publish', 'draft'); if ($post_status === 'any') { $query_status = $allowed_statuses; } elseif (in_array($post_status, $allowed_statuses, true)) { $query_status = $post_status; } else { $query_status = 'publish'; } $args = array( 'post_type' => $post_type, 'post_status' => $query_status, 'posts_per_page' => $per_page, 'paged' => $page, 'orderby' => 'date', 'order' => 'DESC', ); // Filter by thumbnail status if ($has_thumbnail === 'no') { $args['meta_query'] = array( array( 'key' => '_thumbnail_id', 'compare' => 'NOT EXISTS', ), ); } elseif ($has_thumbnail === 'yes') { $args['meta_query'] = array( array( 'key' => '_thumbnail_id', 'compare' => 'EXISTS', ), ); } // Date range if (!empty($date_from) || !empty($date_to)) { $date_query = array(); if (!empty($date_from)) { $date_query['after'] = $date_from; } if (!empty($date_to)) { $date_query['before'] = $date_to; $date_query['inclusive'] = true; } $args['date_query'] = array($date_query); } $query = new \WP_Query($args); $posts = array(); foreach ($query->posts as $post) { $has_thumb = has_post_thumbnail($post->ID); $thumb_url = $has_thumb ? get_the_post_thumbnail_url($post->ID, 'thumbnail') : ''; $posts[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'has_thumbnail' => $has_thumb, 'thumbnail_url' => $thumb_url, 'edit_url' => get_edit_post_link($post->ID, 'raw'), 'date' => get_the_date('Y-m-d', $post), ); } return rest_ensure_response(array( 'posts' => $posts, 'total' => (int) $query->found_posts, 'total_pages' => (int) $query->max_num_pages, 'page' => $page, )); } }