string, 'message' => string, 'reason' => string ). * * @var array|null */ private $last_webp_notice = null; /** * Plain-language notes from the most recent generation, such as a model switch. * * @var string[] */ private $last_notes = array(); /** * Kind of file the last OpenAI call produced when it is not a still image: * 'gif' (animated) or 'svg' (vector). Empty for still images. save_image() reads it. * * @var string */ private $output_kind = ''; /** * Brand kit instance, built on first use. * * @var Brand_Kit|null */ private $brand_kit = null; /** * Initialize generator. */ public function __construct( $settings ) { $this->settings = $settings; } /** * Get the brand kit helper. * * @return Brand_Kit */ private function get_brand_kit() { if ( $this->brand_kit === null ) { $this->brand_kit = new Brand_Kit($this->settings); } return $this->brand_kit; } /** * Get the non-fatal notice (if any) produced by the most recent generation. * * Callers should read this immediately after generate_image() / * generate_inline_image() to surface a warning to the user. Returns null * when the last generation produced no notice. * * @return array|null array( 'code', 'message', 'reason' ) or null. */ public function get_last_webp_notice() { return $this->last_webp_notice; } /** * Notes from the most recent generation, for the person who asked for it. * * @return string[] */ public function get_last_notes() { return $this->last_notes; } /** * Record a note for the current generation (each text once). * * @param string $note Translated note. */ private function add_note( $note ) { if ( !in_array( $note, $this->last_notes, true ) ) { $this->last_notes[] = $note; } } /** * Whether this server can encode WebP (via GD or ImageMagick). * * Used both to warn users up-front and to explain a conversion fallback. * * @return bool True if WebP encoding is available. */ public static function webp_conversion_supported() { if ( function_exists( 'imagewebp' ) ) { return true; } if ( extension_loaded( 'imagick' ) && class_exists( 'Imagick' ) ) { try { $formats = \Imagick::queryFormats( 'WEBP' ); if ( !empty( $formats ) ) { return true; } } catch ( \Exception $e ) { // Fall through to false. } } return false; } /** * Generate image for a post. * * @param int $post_id Post ID. * @param string $prompt Optional custom prompt. * @param string $style Optional style override. * @param string $title Optional custom title. * @param string $custom_text Optional custom text for image. * @param int $quality Optional quality override. * @param bool $use_brand_kit Whether to apply the brand kit to this generation. * @param array $overrides Optional per-request settings, already validated by the caller. * Supports 'ai_provider', 'ai_model' and 'skip_featured' (save only, do not set as featured). * @return int|\WP_Error Attachment ID on success, WP_Error on failure. */ public function generate_image( $post_id, $prompt = '', $style = '', $title = '', $custom_text = '', $quality = null, $use_brand_kit = true, $overrides = array() ) { // Clear any notice from a previous generation on this instance. $this->last_webp_notice = null; $this->last_notes = array(); $settings = $this->apply_overrides( $this->settings->get_settings(), $overrides ); $this->output_kind = ''; $post = get_post( $post_id ); if ( !$post ) { return new \WP_Error('invalid_post', __( 'Invalid post ID.', 'ai-featured-image-generator' )); } // A featured image is never a vector file (themes and social previews need pixels). if ( !empty( $settings['aifi_vector'] ) ) { return new \WP_Error('vector_not_featured', __( 'Vector images cannot be used as featured images. Use them inline instead.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $extras = $this->check_gpt26_extras( $settings ); if ( is_wp_error( $extras ) ) { return $extras; } // Build prompt $base_prompt = ( !empty( $title ) ? $title : $post->post_title ); if ( !empty( $prompt ) ) { $base_prompt .= ' - ' . $prompt; } // Apply style $style = ( !empty( $style ) ? $style : $settings['default_style'] ); $final_prompt = $base_prompt; // The old Stability presets (sp_ prefix) are gone; a saved one means no style. if ( strpos( $style, 'sp_' ) === 0 ) { $style = 'none'; } $style_prompt = $this->get_style_prompt( $style ); // Only add style prompt if style is not 'none' and prompt is not empty if ( $style !== 'none' && $style_prompt !== '' ) { $final_prompt .= ' ' . $style_prompt; } // Handle allow_text setting if ( empty( $settings['allow_text'] ) || $settings['allow_text'] === false ) { $final_prompt .= ' no text, no captions, no words, no letters, no writing'; } else { // Use custom text if provided, otherwise use title $text_to_add = ( !empty( $custom_text ) ? $custom_text : $title ); if ( empty( $text_to_add ) ) { $text_to_add = $post->post_title; } $text_to_add = explode( '·', (string) $text_to_add )[0]; // Remove any WordPress admin suffixes if ( trim( $text_to_add ) !== '' ) { $final_prompt .= ' please add the "' . $text_to_add . '" text on the image '; } } if ( $use_brand_kit ) { $final_prompt = $this->apply_brand_kit( $final_prompt, $settings ); } // Allow filtering the prompt $final_prompt = apply_filters( 'aifi_build_prompt', $final_prompt, $post, $style ); // Capture old featured image alt text before generating (for preserve option) $old_alt_text = ''; $old_thumb_id = get_post_thumbnail_id( $post_id ); if ( $old_thumb_id ) { $old_alt_text = get_post_meta( $old_thumb_id, '_wp_attachment_image_alt', true ); } // Call AI API $image_data = $this->call_ai_api( $final_prompt, $settings, $quality ); if ( is_wp_error( $image_data ) ) { return $image_data; } // Download and save image. // Pass the local $settings so the brand-kit runtime signals reach save_image(). $attachment_id = $this->save_image( $image_data, $post_id, $title, $settings ); if ( is_wp_error( $attachment_id ) ) { return $attachment_id; } // Auto alt text -- prefer the frontend-provided $title over $post->post_title // because the post may not have been saved yet (e.g. still "Auto Draft") $effective_title = ( !empty( $title ) ? $title : $post->post_title ); $this->apply_auto_alt_text( $attachment_id, array( 'title' => $effective_title, 'prompt' => ( !empty( $prompt ) ? $prompt : $effective_title ), 'style' => $style, ), $old_alt_text ); // Set as featured image, unless the caller only wanted the file saved. if ( empty( $overrides['skip_featured'] ) ) { set_post_thumbnail( $post_id, $attachment_id ); } // Fire action hook do_action( 'aifi_after_generate', $attachment_id, $post_id ); return $attachment_id; } /** * Get style-specific prompt. * * @param string $style Style name. * @return string */ private function get_style_prompt( $style ) { // Handle custom styles (Pro users) if ( strpos( $style, 'custom_' ) === 0 ) { // get_custom_styles() is empty on Free, so saved Pro styles stop working after a downgrade. $custom_styles = $this->settings->get_custom_styles(); $idx = (int) substr( $style, 7 ); return ( isset( $custom_styles[$idx]['prompt'] ) ? $custom_styles[$idx]['prompt'] : '' ); } $styles = array( 'realistic' => 'in a realistic, photographic style', 'artistic' => 'in an artistic, painterly style', 'cartoon' => 'in a cartoon, animated style', 'sketch' => 'in a detailed sketch style', 'watercolor' => 'in a beautiful watercolor painting style', '3d' => 'as a high-quality 3D render', 'pixel' => 'in retro pixel art style', 'cyberpunk' => 'in a vibrant cyberpunk style', 'fantasy' => 'in a magical fantasy art style', 'anime' => 'in detailed anime style', 'minimalist' => 'in a clean minimalist style', 'technicolor' => 'in vivid technicolor style', 'toy' => 'as a glossy collectible toy figure displayed in a clear blister-pack box', 'miniature' => 'as a tiny tilt-shift miniature diorama world, like a detailed model set photographed up close', 'clay' => 'in a handmade claymation style with soft clay textures, like a stop-motion film', 'cinematic' => 'as a cinematic movie still with dramatic lighting and shallow depth of field', 'lofi' => 'in a cozy lo-fi illustration style with soft, warm, dim lighting and a calm mood', 'instant' => 'as a vintage instant-film photo with faded warm colors and soft grain', 'collage' => 'as a mixed-media magazine collage of cut-out photos, torn paper and bold shapes', 'papercut' => 'in a layered paper-cut craft style with soft shadows between the paper layers', ); return ( isset( $styles[$style] ) ? $styles[$style] : $styles['realistic'] ); } /** * Apply the brand kit to a pending generation. * * Writes runtime-only signals onto the caller's local settings copy; those keys * are never persisted back to the option. * * @param string $final_prompt Prompt built so far. * @param array $settings Local settings copy, passed by reference. * @return string Prompt with the brand fragment appended. */ private function apply_brand_kit( $final_prompt, &$settings ) { $brand = $this->get_brand_kit(); if ( !$brand->is_active() ) { return $final_prompt; } $provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' ); // Resolve the reference first: the prompt fragment differs depending on // whether the image is actually attached to the request. $reference = ( $provider === 'gemini' ? $brand->get_reference_payload() : null ); $final_prompt .= $brand->get_prompt_fragment( !empty( $reference ) ); if ( $provider === 'gemini' && !empty( $reference ) ) { $settings['aifi_brand_reference'] = $reference; } if ( $brand->has_logo() ) { $settings['aifi_apply_brand_logo'] = true; } return $final_prompt; } /** * Generate an image prompt from a post's title and content using the configured text AI. * * @param int $post_id Post ID. * @param bool $use_brand_kit Whether the Brand Kit should steer the written prompt. * @return string|\WP_Error Generated prompt string on success, WP_Error on failure. */ public function generate_prompt_from_content( $post_id, $use_brand_kit = true ) { $post = get_post( $post_id ); if ( !$post ) { return new \WP_Error('invalid_post', __( 'Invalid post ID.', 'ai-featured-image-generator' )); } $settings = $this->settings->get_settings(); $provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' ); // Gemini and Muse require premium 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, )); } // Extract and clean content $title = trim( $post->post_title ); $content = $post->post_content; $content = strip_shortcodes( $content ); $content = wp_strip_all_tags( $content ); $content = preg_replace( '/\\s+/', ' ', $content ); $content = trim( $content ); $content = mb_substr( $content, 0, 2000 ); if ( empty( $title ) && empty( $content ) ) { return new \WP_Error('empty_content', __( 'This post has no title or content to generate a prompt from.', 'ai-featured-image-generator' )); } // Resolve style for prompt context $style = ( isset( $settings['default_style'] ) ? $settings['default_style'] : 'realistic' ); $style_label = $this->get_style_prompt( $style ); if ( $style === 'none' || strpos( $style, 'sp_' ) === 0 ) { $style_label = ''; } if ( strpos( $style, 'custom_' ) === 0 ) { $custom_styles = $this->settings->get_custom_styles(); $idx = (int) substr( $style, 7 ); $style_label = ( isset( $custom_styles[$idx]['prompt'] ) ? $custom_styles[$idx]['prompt'] : '' ); } // Resolve text-on-image setting $allow_text = !empty( $settings['allow_text'] ) && $settings['allow_text'] !== false; // Resolve aspect ratio based on provider if ( $provider === 'gemini' ) { $aspect_ratio = ( isset( $settings['gemini_aspect_ratio'] ) ? $settings['gemini_aspect_ratio'] : '16:9' ); } elseif ( $provider === 'grok' ) { $aspect_ratio = ( isset( $settings['grok_aspect_ratio'] ) ? $settings['grok_aspect_ratio'] : '1:1' ); } elseif ( $provider === 'muse' ) { $aspect_ratio = ( isset( $settings['muse_aspect_ratio'] ) ? $settings['muse_aspect_ratio'] : '1:1' ); } else { $size = ( isset( $settings['default_size'] ) ? $settings['default_size'] : '1024x1024' ); $size_to_ratio = array( '1024x1024' => '1:1', '1536x1024' => '3:2', '1024x1536' => '2:3', ); $aspect_ratio = ( isset( $size_to_ratio[$size] ) ? $size_to_ratio[$size] : '1:1' ); } // Map aspect ratio to composition guidance $ratio_parts = explode( ':', $aspect_ratio ); $ratio_value = (int) $ratio_parts[0] / max( (int) $ratio_parts[1], 1 ); if ( $ratio_value > 1.3 ) { $composition_hint = 'wide/panoramic landscape orientation'; } elseif ( $ratio_value < 0.77 ) { $composition_hint = 'tall/vertical portrait orientation'; } else { $composition_hint = 'square format'; } $system_prompt = 'You are a world-class creative director writing image generation prompts for AI. Given an article title and content, create a single image prompt (2-3 sentences) for a premium blog featured image. Rules: - Describe a CONCRETE, real-world scene: real people, objects, environments, or nature. Never use abstract shapes, geometric patterns, data visualizations, or floating icons. - Use objects, settings, and elements that naturally belong to the article\'s subject area. Do not force metaphors from unrelated fields. - Avoid complex interfaces, dashboards, code snippets, or detailed text-heavy displays as these render poorly in AI-generated images. - Never include any text, typography, words, letters, labels, captions, or watermarks in the image. - VARY your visual approach. Do NOT default to "a person sitting at a desk." Consider: action shots, close-ups of hands working, aerial views, environmental wide shots, still life arrangements, or dramatic angles. Choose what best fits THIS specific article. - VARY lighting. Do NOT always use golden hour or soft diffused light. Consider: dramatic side lighting, cool blue tones, high-contrast chiaroscuro, bright overhead fluorescent, moody backlight, or warm tungsten. Choose lighting that matches the article\'s emotional tone. - The article\'s emotional tone MUST drive the scene. An article about urgency needs tense, dynamic energy, not calm relaxation. An article about trust needs warmth and stability. Read the article\'s argument and reflect its feeling, not just its topic. - The scene must feel relevant to BOTH the article\'s topic/industry AND its emotional theme. Ground the scene in the article\'s specific domain. - Focus on ONE primary subject or scene. Do not compose two subjects with contrasting states. - NEVER use words like "symbolizing", "representing", "evoking", or "conveying". Image generators render pixels, not concepts. Describe only what is literally visible. - Write 2-3 short, discrete sentences. No semicolons chaining ideas. - Do NOT include layout instructions like "leaving space for text" or "negative space on the right." Just describe the scene. - Do NOT include any style directives (e.g. "in watercolor style", "in anime style"). Style will be applied separately.'; $system_prompt .= "\n\nSettings context:"; $system_prompt .= "\n- Aspect ratio: " . $aspect_ratio . ' (' . $composition_hint . '). Compose the scene to suit this format.'; if ( !empty( $style_label ) ) { $system_prompt .= "\n- The image will be rendered " . $style_label . '. Describe a scene that works well in this style, but do NOT include style directives in your prompt.'; } if ( $allow_text ) { $system_prompt .= "\n- Text will be overlaid on this image, so include some open areas in the composition."; } else { $system_prompt .= "\n- This image must be completely free of any text or writing."; } if ( $use_brand_kit ) { $system_prompt .= $this->get_brand_kit()->get_prompt_context_fragment(); } $system_prompt .= "\n\nOutput ONLY the prompt, nothing else."; $user_message = ''; if ( !empty( $title ) ) { $user_message .= 'Article Title: ' . $title . "\n\n"; } if ( !empty( $content ) ) { $user_message .= 'Article Content: ' . $content; } if ( $provider === 'gemini' ) { return $this->call_gemini_text_api( $system_prompt, $user_message, $settings ); } if ( $provider === 'muse' ) { // Muse Spark always reasons, and its token cap covers reasoning plus the // visible reply. "none" is rejected with a 400, so ask for "low" effort, // use the non-deprecated cap with room for both, and leave temperature // at the model default as Meta recommends. return $this->call_openai_compatible_text_api( self::MUSE_API_BASE . '/chat/completions', ( isset( $settings['muse_api_key'] ) ? $settings['muse_api_key'] : '' ), self::MUSE_TEXT_MODEL, $system_prompt, $user_message, array( 'max_tokens' => null, 'temperature' => null, 'max_completion_tokens' => 1024, 'reasoning_effort' => 'low', ), 60 ); } // OpenAI and Grok share the same API format $api_url = ( $provider === 'grok' ? 'https://api.x.ai/v1/chat/completions' : 'https://api.openai.com/v1/chat/completions' ); $api_key = Providers::get_api_key( $settings, ( $provider === 'grok' ? 'grok' : 'openai' ) ); $model = Providers::text_model( ( $provider === 'grok' ? 'grok' : 'openai' ) ); // Grok 4.7 cannot turn reasoning off, so ask for the lowest effort; a short image prompt // does not need more. GPT-6 Luna is a reasoning model: it takes max_completion_tokens, // not max_tokens, and no temperature. // Both get the same 1024-token budget as Muse, so reasoning never uses up the reply. if ( $provider === 'grok' ) { $extra_body = array( 'max_tokens' => null, 'max_completion_tokens' => 1024, 'reasoning_effort' => 'low', ); $timeout = 30; } else { $extra_body = array( 'max_tokens' => null, 'temperature' => null, 'max_completion_tokens' => 1024, 'reasoning_effort' => 'low', ); $timeout = 60; } return $this->call_openai_compatible_text_api( $api_url, $api_key, $model, $system_prompt, $user_message, $extra_body, $timeout ); } /** * Call an OpenAI-compatible text completion API (OpenAI, Grok and Muse). * * @param string $api_url API endpoint URL. * @param string $api_key API key. * @param string $model Model name. * @param string $system_prompt System prompt. * @param string $user_message User message. * @param array $extra_body Optional provider-specific request fields. They replace * the defaults, and a null value removes that field. * @param int $timeout Request timeout in seconds. * @return string|\WP_Error */ private function call_openai_compatible_text_api( $api_url, $api_key, $model, $system_prompt, $user_message, $extra_body = array(), $timeout = 30 ) { if ( empty( $api_key ) ) { return new \WP_Error('no_api_key', __( 'API key is not configured.', 'ai-featured-image-generator' )); } $request_body = array_merge( array( 'model' => $model, 'messages' => array(array( 'role' => 'system', 'content' => $system_prompt, ), array( 'role' => 'user', 'content' => $user_message, )), 'max_tokens' => 300, 'temperature' => 0.7, ), $extra_body ); $request_body = array_filter( $request_body, function ( $value ) { return $value !== null; } ); $response = wp_remote_post( $api_url, array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( $request_body ), 'timeout' => $timeout, ) ); if ( is_wp_error( $response ) ) { return $response; } $code = wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); if ( $code !== 200 ) { return $this->handle_api_error( $code, 'Text API error', $body ); } $data = json_decode( $body, true ); $text = ( isset( $data['choices'][0]['message']['content'] ) && is_string( $data['choices'][0]['message']['content'] ) ? trim( $data['choices'][0]['message']['content'] ) : '' ); if ( $text === '' ) { // Reasoning models can spend the whole token budget thinking and stop // before writing any visible reply. if ( isset( $data['choices'][0]['finish_reason'] ) && $data['choices'][0]['finish_reason'] === 'length' ) { return new \WP_Error('response_truncated', __( 'The AI used up its reply length before writing a prompt. Please try again.', 'ai-featured-image-generator' )); } return new \WP_Error('empty_response', __( 'The AI returned an empty prompt. Please try again.', 'ai-featured-image-generator' )); } return $text; } /** * Call Gemini text generation API. * * @param string $system_prompt System prompt. * @param string $user_message User message. * @param array $settings Plugin settings. * @return string|\WP_Error */ private function call_gemini_text_api( $system_prompt, $user_message, $settings ) { $api_key = ( isset( $settings['gemini_api_key'] ) ? $settings['gemini_api_key'] : '' ); if ( empty( $api_key ) ) { return new \WP_Error('no_api_key', __( 'Gemini API key is not configured.', 'ai-featured-image-generator' )); } // Always use a Gemini Flash text model, regardless of which image model // the user selected. This mirrors OpenAI (gpt-6-luna) and Grok (grok-4.7) // which also hardcode their text models. Image models don't reliably // return text-only responses even with responseModalities: ["TEXT"]. // The second model is a fallback if the first returns 404. $text_models = array('gemini-3.6-flash', 'gemini-3.8-flash'); $payload = wp_json_encode( array( 'system_instruction' => array( 'parts' => array(array( 'text' => $system_prompt, )), ), 'contents' => array(array( 'parts' => array(array( 'text' => $user_message, )), )), 'generationConfig' => array( 'maxOutputTokens' => 1024, 'temperature' => 0.7, 'responseModalities' => array('TEXT'), 'thinkingConfig' => array( 'thinkingLevel' => 'minimal', ), ), ) ); $code = 0; $body = ''; $response = null; foreach ( $text_models as $text_model ) { $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $text_model . ':generateContent'; $response = wp_remote_post( $url, array( 'headers' => array( 'x-goog-api-key' => $api_key, 'Content-Type' => 'application/json', ), 'body' => $payload, 'timeout' => 30, 'httpversion' => '1.1', 'sslverify' => true, ) ); if ( is_wp_error( $response ) ) { continue; } $code = wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); if ( $code === 200 ) { break; } // 404 means model not found, try the next one if ( $code === 404 ) { continue; } // Any other error, stop trying and report it break; } if ( is_wp_error( $response ) ) { return $response; } if ( $code !== 200 ) { return $this->handle_api_error( $code, 'Gemini text API error', $body ); } $data = json_decode( $body, true ); $text = ( isset( $data['candidates'][0]['content']['parts'][0]['text'] ) ? trim( $data['candidates'][0]['content']['parts'][0]['text'] ) : '' ); if ( empty( $text ) ) { return new \WP_Error('empty_response', __( 'The AI returned an empty prompt. Please try again.', 'ai-featured-image-generator' )); } return $text; } /** * Handle API errors with human-readable messages. * * @param int $response_code HTTP response code. * @param string $error_message Original error message from API. * @param string $body Response body. * @return \WP_Error */ private function handle_api_error( $response_code, $error_message, $body = '' ) { $error_data = json_decode( $body, true ); // Try multiple paths for error messages (the providers use different structures) $api_error_message = $error_message; if ( isset( $error_data['error']['message'] ) && is_string( $error_data['error']['message'] ) ) { $api_error_message = $error_data['error']['message']; } elseif ( isset( $error_data['error'] ) && is_string( $error_data['error'] ) ) { $api_error_message = $error_data['error']; } elseif ( !empty( $error_data['errors'] ) && is_array( $error_data['errors'] ) ) { // Some providers return {name, errors: [string, ...]} $strings = array_filter( $error_data['errors'], 'is_string' ); if ( !empty( $strings ) ) { $api_error_message = implode( '; ', $strings ); } } elseif ( isset( $error_data['message'] ) && is_string( $error_data['message'] ) ) { $api_error_message = $error_data['message']; } // Log only the status code and message, never the raw provider response. if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) { error_log( 'AIFI: API error ' . (int) $response_code . ': ' . $api_error_message ); } // Common API error patterns and their human-readable equivalents $error_mappings = array( 'invalid_api_key' => __( 'Your API key is invalid or expired. Please check your API key in the plugin settings.', 'ai-featured-image-generator' ), 'insufficient_quota' => __( 'You have exceeded your API usage quota. Please check your account billing.', 'ai-featured-image-generator' ), 'billing_not_active' => __( 'Your account billing is not active. Please add a payment method to your account.', 'ai-featured-image-generator' ), 'content_policy' => __( 'Your prompt contains content that violates the AI provider\'s usage policies. Please modify your prompt and try again.', 'ai-featured-image-generator' ), 'safety_system' => __( 'Your prompt was rejected by the safety system. Please modify your prompt to avoid potentially harmful content.', 'ai-featured-image-generator' ), 'blocked' => __( 'Your request was blocked. This may be due to content policy violations. Please modify your prompt and try again.', 'ai-featured-image-generator' ), 'rate_limit' => __( 'You are making requests too quickly. Please wait a moment before trying again.', 'ai-featured-image-generator' ), 'resource_exhausted' => __( 'API quota exceeded. Please wait or upgrade your account plan.', 'ai-featured-image-generator' ), 'server_error' => __( 'The AI service is experiencing issues. Please try again in a few minutes.', 'ai-featured-image-generator' ), 'service_unavailable' => __( 'The image generation service is temporarily unavailable. Please try again later.', 'ai-featured-image-generator' ), ); // Check for specific error patterns $lower_error = strtolower( $api_error_message ); // Authentication and billing errors if ( strpos( $lower_error, 'invalid api key' ) !== false || strpos( $lower_error, 'incorrect api key' ) !== false ) { return new \WP_Error('api_auth_error', $error_mappings['invalid_api_key'], array( 'status' => $response_code, )); } if ( strpos( $lower_error, 'billing_not_active' ) !== false ) { return new \WP_Error('api_billing_error', $error_mappings['billing_not_active'], array( 'status' => $response_code, )); } if ( strpos( $lower_error, 'quota' ) !== false || strpos( $lower_error, 'billing' ) !== false ) { return new \WP_Error('api_quota_error', $error_mappings['insufficient_quota'], array( 'status' => $response_code, )); } // Content policy errors if ( strpos( $lower_error, 'content policy' ) !== false || strpos( $lower_error, 'usage policy' ) !== false ) { return new \WP_Error('api_content_error', $error_mappings['content_policy'], array( 'status' => $response_code, )); } if ( strpos( $lower_error, 'safety system' ) !== false || strpos( $lower_error, 'safety' ) !== false ) { return new \WP_Error('api_safety_error', $error_mappings['safety_system'], array( 'status' => $response_code, )); } // Rate limiting if ( strpos( $lower_error, 'rate limit' ) !== false || strpos( $lower_error, 'too many requests' ) !== false || strpos( $lower_error, 'resource_exhausted' ) !== false ) { return new \WP_Error('api_rate_limit', $error_mappings['rate_limit'], array( 'status' => $response_code, )); } // Gemini-specific errors if ( strpos( $lower_error, 'blocked' ) !== false ) { return new \WP_Error('api_blocked', $error_mappings['blocked'], array( 'status' => $response_code, )); } // Gemini reports a wrong key as "API key not valid", with reason API_KEY_INVALID in error.details. $gemini_key_invalid = strpos( $lower_error, 'api key not valid' ) !== false; if ( !$gemini_key_invalid && !empty( $error_data['error']['details'] ) && is_array( $error_data['error']['details'] ) ) { foreach ( $error_data['error']['details'] as $detail ) { if ( is_array( $detail ) && isset( $detail['reason'] ) && $detail['reason'] === 'API_KEY_INVALID' ) { $gemini_key_invalid = true; break; } } } if ( $gemini_key_invalid || strpos( $lower_error, 'api_key_invalid' ) !== false || strpos( $lower_error, 'invalid_argument' ) !== false ) { return new \WP_Error('api_auth_error', $error_mappings['invalid_api_key'], array( 'status' => $response_code, )); } // Server errors if ( $response_code === 503 ) { return new \WP_Error('api_unavailable', $error_mappings['service_unavailable'], array( 'status' => $response_code, )); } if ( $response_code >= 500 ) { return new \WP_Error('api_server_error', $error_mappings['server_error'], array( 'status' => $response_code, )); } // Generic error handling based on HTTP status codes switch ( $response_code ) { case 400: return new \WP_Error('api_bad_request', sprintf( /* translators: %s: underlying error message from the API */ __( 'Invalid request: %s', 'ai-featured-image-generator' ), $api_error_message ), array( 'status' => $response_code, )); case 401: return new \WP_Error('api_unauthorized', __( 'Authentication failed. Please check your API key.', 'ai-featured-image-generator' ), array( 'status' => $response_code, )); case 403: return new \WP_Error('api_forbidden', __( 'Access denied. Please check your API key permissions.', 'ai-featured-image-generator' ), array( 'status' => $response_code, )); case 404: return new \WP_Error('api_not_found', __( 'The requested service was not found. Please try again later.', 'ai-featured-image-generator' ), array( 'status' => $response_code, )); case 402: return new \WP_Error('api_payment_required', __( 'Insufficient credits. Please add credits to your AI provider account to use this feature.', 'ai-featured-image-generator' ), array( 'status' => $response_code, )); case 429: return new \WP_Error('api_rate_limit', __( 'Too many requests. Please wait a moment before trying again.', 'ai-featured-image-generator' ), array( 'status' => $response_code, )); default: // Fallback to original error message if no specific mapping found return new \WP_Error( 'api_error', /* translators: 1: HTTP status code, 2: error message from the API */ sprintf( __( 'API error (HTTP %1$d): %2$s', 'ai-featured-image-generator' ), $response_code, $api_error_message ), array( 'status' => $response_code, ) ); } } /** * Call AI image generation API. * * @param string $prompt Image prompt. * @param array $settings Plugin settings. * @param int $quality Optional quality override. * @return string|\WP_Error Image data on success, WP_Error on failure. */ private function call_ai_api( $prompt, $settings, $quality = null ) { require_once ABSPATH . 'wp-admin/includes/file.php'; // A file kind left by an earlier call must never reach this call's save. $this->output_kind = ''; $provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' ); // Route to provider-specific method if ( $provider === 'gemini' ) { // Premium check: Gemini is only available for premium users if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Google Gemini is a Pro feature. Please upgrade to use Gemini for image generation, or switch to OpenAI in the plugin settings.', 'ai-featured-image-generator' )); } } elseif ( $provider === 'muse' ) { // Premium check: Meta Muse is only available for premium users if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Meta Muse is a Pro feature. Please upgrade to use Muse for image generation, or switch to OpenAI in the plugin settings.', 'ai-featured-image-generator' )); } } elseif ( $provider === 'grok' ) { return $this->provider_result( $this->call_grok_api( $prompt, $settings, $quality ) ); } else { return $this->provider_result( $this->call_openai_api( $prompt, $settings, $quality ) ); } // Reached only by Gemini or Muse on a build without the Pro code. 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 ) )); } /** * Pass a provider result through, forgetting the file kind when the call failed. * * @param mixed $result Temp file path or WP_Error. * @return mixed The same result. */ private function provider_result( $result ) { if ( is_wp_error( $result ) ) { $this->output_kind = ''; } return $result; } /** * Call OpenAI image generation API. * * @param string $prompt Image prompt. * @param array $settings Plugin settings. * @param int $quality Optional quality override. * @return string|\WP_Error Image data on success, WP_Error on failure. */ private function call_openai_api( $prompt, $settings, $quality = null ) { $this->output_kind = ''; $api_url = 'https://api.openai.com/v1/images/generations'; $size = ( isset( $settings['default_size'] ) ? $settings['default_size'] : '1024x1024' ); $output_format = ( isset( $settings['output_format'] ) ? $settings['output_format'] : 'webp' ); $quality = ( $quality !== null ? intval( $quality ) : (( isset( $settings['image_quality'] ) ? intval( $settings['image_quality'] ) : 90 )) ); $model = ( isset( $settings['ai_model'] ) ? $settings['ai_model'] : 'gpt-image-2' ); // Removed models (deprecated by OpenAI: gpt-image-1, gpt-image-1-mini, gpt-image-1.5, chatgpt-image-latest). // Remap saved settings to gpt-image-2 so existing users keep working. if ( in_array( $model, Settings::OPENAI_DEPRECATED_MODELS, true ) ) { $model = 'gpt-image-2'; } // GPT Image 2.5 Flare and Sunburst were replaced by 2.6 at the same price. if ( isset( Settings::RETIRED_MODEL_REPLACEMENTS[$model] ) ) { $model = Settings::RETIRED_MODEL_REPLACEMENTS[$model]; } // GPT Image 2.6 models are Pro; Free always runs GPT Image 2, whatever was passed in. if ( Settings::is_gpt25_model( $model ) && !Providers::can_use_premium() ) { $model = 'gpt-image-2'; } // Get OpenAI API key (support legacy 'api_key' field) $api_key = ( isset( $settings['openai_api_key'] ) ? $settings['openai_api_key'] : (( isset( $settings['api_key'] ) ? $settings['api_key'] : '' )) ); // Generation quality tier (low / medium / high), supported by all GPT Image models. $generation_quality = ( isset( $settings['openai_quality'] ) ? $settings['openai_quality'] : 'high' ); // Extra High and Max are GPT Image 2.6 only; other models get High. if ( in_array( $generation_quality, Settings::OPENAI_GPT25_QUALITIES, true ) && !Settings::is_gpt25_model( $model ) ) { $generation_quality = 'high'; } // GPT Image 2 family params (GPT Image 2 and 2.6). $is_gpt2 = Settings::is_gpt2_family( $model ); $background = ( $is_gpt2 && isset( $settings['openai_background'] ) ? $settings['openai_background'] : 'auto' ); // GPT Image 2 rejects transparent backgrounds on most accounts (OpenAI lists it as a // preview). Pro switches this one request to GPT Image 2.6 Flare; Free sends it as is. if ( $background === 'transparent' && $model === 'gpt-image-2' && Providers::can_use_premium() ) { $model = 'gpt-image-2.6-flare'; $this->add_note( __( 'Switched to GPT Image 2.6 Flare for the transparent background.', 'ai-featured-image-generator' ) ); } // Transparent background needs PNG or WebP; JPEG switches to PNG for this request only. if ( $is_gpt2 && $background === 'transparent' && !in_array( $output_format, array('png', 'webp'), true ) ) { $output_format = 'png'; } // Build the API request body $body = array( 'model' => $model, 'prompt' => $prompt, 'n' => 1, 'size' => $size, 'output_format' => $output_format, 'quality' => $generation_quality, ); // Only include output_compression for lossy formats (webp, jpeg) // PNG is lossless and doesn't support compression parameter if ( $output_format !== 'png' ) { $body['output_compression'] = $quality; } // GPT Image 2 family: background (only send non-default value). if ( $is_gpt2 ) { if ( $background !== 'auto' ) { $body['background'] = $background; } } // GPT Image 2.6: planning detail, animated GIF and vector SVG. if ( Settings::is_gpt25_model( $model ) ) { $complexity = ( isset( $settings['openai_complexity'] ) ? $settings['openai_complexity'] : 'auto' ); if ( in_array( $complexity, array('low', 'medium', 'high'), true ) ) { $body['complexity'] = $complexity; } if ( !empty( $settings['aifi_vector'] ) ) { $body['output_format'] = 'svg'; $body['n'] = 1; $body['svg'] = array( 'model' => Providers::text_model( 'openai' ), 'reasoning' => array( 'effort' => 'low', ), ); unset($body['output_compression'], $body['background'], $body['size']); $this->output_kind = 'svg'; } elseif ( !empty( $settings['aifi_animated'] ) ) { $body['output_format'] = 'gif'; $body['size'] = self::gif_frame_size( $size, (int) $settings['aifi_animated']['frames'] ); $body['frame_count'] = (int) $settings['aifi_animated']['frames']; $body['frame_duration_ms'] = (int) $settings['aifi_animated']['frame_ms']; unset($body['output_compression']); if ( isset( $body['background'] ) && 'transparent' !== $body['background'] ) { unset($body['background']); } $this->output_kind = 'gif'; } } $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => json_encode( $body ), 'timeout' => 240, 'httpversion' => '1.1', 'sslverify' => true, 'blocking' => true, ); // Allow filtering API request arguments $args = apply_filters( 'aifi_api_request_args', $args ); $response = wp_remote_post( $api_url, $args ); if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); // Handle timeout specifically if ( strpos( $error_message, 'timed out' ) !== false ) { return new \WP_Error('api_timeout', __( 'The request timed out. The image generation is taking longer than expected. Please try again.', 'ai-featured-image-generator' )); } // Handle connection errors if ( stripos( $error_message, 'could not resolve host' ) !== false ) { return new \WP_Error('api_connection_error', __( 'Unable to connect to OpenAI servers. Please check your internet connection and try again.', 'ai-featured-image-generator' )); } // Handle SSL errors if ( strpos( $error_message, 'ssl' ) !== false || strpos( $error_message, 'certificate' ) !== false ) { return new \WP_Error('api_ssl_error', __( 'SSL connection error. Please try again or contact your hosting provider.', 'ai-featured-image-generator' )); } // Generic connection error return new \WP_Error('api_connection_error', sprintf( /* translators: %s: the connection error message */ __( 'Connection failed: %s', 'ai-featured-image-generator' ), $error_message )); } $response_code = wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); if ( $response_code !== 200 ) { if ( $background === 'transparent' && $model === 'gpt-image-2' && false !== stripos( (string) $body, 'Transparent background is not supported' ) ) { return new \WP_Error('transparent_needs_pro', __( 'Your OpenAI account cannot make transparent images with GPT Image 2. Choose a solid background, or upgrade to Pro to use GPT Image 2.6.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $error_message = __( 'Unknown API error occurred.', 'ai-featured-image-generator' ); return $this->handle_api_error( $response_code, $error_message, $body ); } // Parse the JSON response $response_data = json_decode( $body, true ); if ( json_last_error() !== JSON_ERROR_NONE ) { return new \WP_Error('api_parse_error', __( 'Invalid response from OpenAI API. Please try again.', 'ai-featured-image-generator' )); } if ( !isset( $response_data['data'][0]['b64_json'] ) ) { return new \WP_Error('api_data_error', __( 'No image data found in API response. The image generation may have failed.', 'ai-featured-image-generator' )); } // Decode the base64 image data $image_data = base64_decode( $response_data['data'][0]['b64_json'] ); if ( $image_data === false ) { return new \WP_Error('api_decode_error', __( 'Failed to process the generated image data. Please try again.', 'ai-featured-image-generator' )); } // Vector images are XML: only a cleaned copy is ever written to disk. if ( 'svg' === $this->output_kind ) { $image_data = Svg::sanitize( $image_data ); if ( is_wp_error( $image_data ) ) { $this->output_kind = ''; return $image_data; } } // Save the image data to a temporary file $temp_file = wp_tempnam( 'aifi-' ); if ( !$temp_file ) { return new \WP_Error('api_temp_file_error', __( 'Unable to create temporary file for the image. Please check your server permissions.', 'ai-featured-image-generator' )); } file_put_contents( $temp_file, $image_data ); return $temp_file; } /** * Call Google Gemini image generation API. * * @param string $prompt Image prompt. * @param array $settings Plugin settings. * @param int $quality Optional quality override (not used by Gemini). * @return string|\WP_Error Image data on success, WP_Error on failure. */ private function call_gemini_api( $prompt, $settings, $quality = null ) { // Double-check premium status (defense in depth) if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Google Gemini is a Pro feature. Please upgrade to use Gemini for image generation.', 'ai-featured-image-generator' )); } return new \WP_Error('premium_required', __( 'Google Gemini is a Pro feature. Please upgrade to use Gemini for image generation.', 'ai-featured-image-generator' )); } /** * The base64 data of the final image in a Gemini response. * * Looks at every part of the first candidate and takes the last inlineData * whose thought flag is not set (thinking models can send draft images first). * * @param mixed $response_data Decoded Gemini response. * @return string Base64 data, or '' when there is no image. */ private static function gemini_image_data( $response_data ) { $parts = ( isset( $response_data['candidates'][0]['content']['parts'] ) && is_array( $response_data['candidates'][0]['content']['parts'] ) ? $response_data['candidates'][0]['content']['parts'] : array() ); $found = ''; foreach ( $parts as $part ) { if ( !is_array( $part ) || !empty( $part['thought'] ) ) { continue; } if ( isset( $part['inlineData']['data'] ) && is_string( $part['inlineData']['data'] ) && '' !== $part['inlineData']['data'] ) { $found = $part['inlineData']['data']; } } return $found; } /** * Call Grok / xAI image generation API. * * @param string $prompt Image prompt. * @param array $settings Plugin settings. * @param int $quality Optional quality override (not used by Grok). * @return string|\WP_Error Temp file path on success, WP_Error on failure. */ private function call_grok_api( $prompt, $settings, $quality = null ) { $api_url = 'https://api.x.ai/v1/images/generations'; $api_key = ( isset( $settings['grok_api_key'] ) ? $settings['grok_api_key'] : '' ); $model = ( isset( $settings['ai_model'] ) ? $settings['ai_model'] : 'grok-imagine-image' ); // Retired Grok Imagine Image Pro moves to Grok Imagine Image 2.0. if ( isset( Settings::RETIRED_MODEL_REPLACEMENTS[$model] ) ) { $model = Settings::RETIRED_MODEL_REPLACEMENTS[$model]; } $can_use_premium = Providers::can_use_premium(); // Free users can only use standard model if ( !$can_use_premium && $model !== 'grok-imagine-image' ) { $model = 'grok-imagine-image'; } $aspect_ratio = ( isset( $settings['grok_aspect_ratio'] ) ? $settings['grok_aspect_ratio'] : '1:1' ); $resolution = ( isset( $settings['grok_resolution'] ) ? $settings['grok_resolution'] : '1k' ); $body = array( 'model' => $model, 'prompt' => $prompt, 'n' => 1, 'response_format' => 'b64_json', 'aspect_ratio' => $aspect_ratio, 'resolution' => $resolution, ); $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => json_encode( $body ), 'timeout' => 240, 'httpversion' => '1.1', 'sslverify' => true, 'blocking' => true, ); $args = apply_filters( 'aifi_api_request_args', $args ); $response = wp_remote_post( $api_url, $args ); if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); if ( strpos( $error_message, 'timed out' ) !== false ) { return new \WP_Error('api_timeout', __( 'The request timed out. Please try again.', 'ai-featured-image-generator' )); } /* translators: %s: the connection error message */ return new \WP_Error('api_connection_error', sprintf( __( 'Connection failed: %s', 'ai-featured-image-generator' ), $error_message )); } $response_code = wp_remote_retrieve_response_code( $response ); $response_body = wp_remote_retrieve_body( $response ); if ( $response_code !== 200 ) { return $this->handle_api_error( $response_code, __( 'Unknown API error occurred.', 'ai-featured-image-generator' ), $response_body ); } $response_data = json_decode( $response_body, true ); if ( json_last_error() !== JSON_ERROR_NONE || !isset( $response_data['data'][0]['b64_json'] ) ) { return new \WP_Error('api_data_error', __( 'No image data found in Grok API response. Please try again.', 'ai-featured-image-generator' )); } $image_data = base64_decode( $response_data['data'][0]['b64_json'] ); if ( $image_data === false ) { return new \WP_Error('api_decode_error', __( 'Failed to process the generated image data. Please try again.', 'ai-featured-image-generator' )); } $temp_file = wp_tempnam( 'aifi-' ); if ( !$temp_file ) { return new \WP_Error('api_temp_file_error', __( 'Unable to create temporary file. Please check server permissions.', 'ai-featured-image-generator' )); } file_put_contents( $temp_file, $image_data ); return $temp_file; } /** * Apply runtime-only provider/model overrides to a settings array. Nothing is * saved back to the option; the caller has already validated the values. * * @param array $settings Plugin settings. * @param array $overrides Supports 'ai_provider' and 'ai_model'. * @return array */ private function apply_overrides( $settings, $overrides ) { if ( !empty( $overrides['ai_provider'] ) && Providers::is_registered( $overrides['ai_provider'] ) ) { $settings['ai_provider'] = $overrides['ai_provider']; } if ( !empty( $overrides['ai_model'] ) ) { $settings['ai_model'] = $overrides['ai_model']; } // One shape for every provider, the same way the inline block does it. if ( !empty( $overrides['aspect_ratio'] ) ) { $ratio = (string) $overrides['aspect_ratio']; $settings['gemini_aspect_ratio'] = $ratio; $settings['default_size'] = $this->map_aspect_to_openai_size( $ratio, $settings['ai_model'] ?? 'gpt-image-2' ); $settings['grok_aspect_ratio'] = $ratio; $settings['muse_aspect_ratio'] = $ratio; } // GPT Image 2.6 extras: animated GIF and vector SVG (never both). unset($settings['aifi_animated'], $settings['aifi_vector']); if ( !empty( $overrides['vector'] ) ) { $settings['aifi_vector'] = true; } elseif ( !empty( $overrides['animated'] ) ) { $anim = ( is_array( $overrides['animated'] ) ? $overrides['animated'] : array() ); $frames = ( isset( $anim['frames'] ) ? (int) $anim['frames'] : (int) ($settings['openai_gif_frames'] ?? 9) ); $ms = ( isset( $anim['frame_ms'] ) ? (int) $anim['frame_ms'] : (int) ($settings['openai_gif_frame_ms'] ?? 200) ); $settings['aifi_animated'] = self::normalize_animation( $frames, $ms ); } return $settings; } /** * Clamp GIF settings to what OpenAI accepts. * * @param int $frames Frame count. * @param int $frame_ms Milliseconds per frame. * @return array array( 'frames' => int 2..16, 'frame_ms' => int 20..2000 rounded to 10 ). */ public static function normalize_animation( $frames, $frame_ms ) { $frames = max( 2, min( 16, (int) $frames ) ); $frame_ms = (int) (round( max( 20, min( 2000, (int) $frame_ms ) ) / 10 ) * 10); return array( 'frames' => $frames, 'frame_ms' => $frame_ms, ); } /** * Frame size for an animated GIF. OpenAI draws all frames on one sheet in a near-square * grid; the sheet's longest edge must be at most 3840 px and its area at most 3840x2160 * (both measured on 6 Nov 2026). Frames keep the requested shape and shrink until the * sheet fits, in steps of 16 px. * * @param string $size Requested frame size such as 1536x1024. * @param int $frames Frame count. * @return string WxH. */ public static function gif_frame_size( $size, $frames ) { if ( !preg_match( '/^(\\d+)x(\\d+)$/', (string) $size, $m ) || !(int) $m[1] || !(int) $m[2] ) { return (string) $size; } $w = (int) $m[1]; $h = (int) $m[2]; $aspect = $w / $h; $n = max( 1, (int) $frames ); $cols = (int) ceil( sqrt( $n ) ); $rows = (int) ceil( $n / $cols ); $best = 0; foreach ( array(array($cols, $rows), array($rows, $cols)) as $grid ) { list( $c, $r ) = $grid; $fw = min( $w, 3840 / $c, 3840 * $aspect / $r, sqrt( 3840 * 2160 * $aspect / ($c * $r) ) ); $best = max( $best, $fw ); } $fw = max( 16, (int) floor( $best / 16 ) * 16 ); $fh = max( 16, (int) floor( $fw / $aspect / 16 ) * 16 ); return $fw . 'x' . $fh; } /** * The OpenAI model a request will really use, after the retired and Free remaps. * * @param array $settings Settings for this request. * @return string */ private function effective_openai_model( $settings ) { $model = ( isset( $settings['ai_model'] ) ? $settings['ai_model'] : 'gpt-image-2' ); if ( in_array( $model, Settings::OPENAI_DEPRECATED_MODELS, true ) ) { $model = 'gpt-image-2'; } if ( isset( Settings::RETIRED_MODEL_REPLACEMENTS[$model] ) ) { $model = Settings::RETIRED_MODEL_REPLACEMENTS[$model]; } if ( Settings::is_gpt25_model( $model ) && !Providers::can_use_premium() ) { $model = 'gpt-image-2'; } return $model; } /** * Animated and vector images need GPT Image 2.6. Checked before any request. * * @param array $settings Settings for this request. * @return true|\WP_Error */ private function check_gpt26_extras( $settings ) { if ( empty( $settings['aifi_animated'] ) && empty( $settings['aifi_vector'] ) ) { return true; } $provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' ); if ( 'openai' !== $provider || !Settings::is_gpt25_model( $this->effective_openai_model( $settings ) ) ) { return new \WP_Error('needs_gpt_image_26', __( 'Animated and vector images need GPT Image 2.6 Flare or Sunburst.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } return true; } /** * Pixel size Meta expects for each aspect ratio. Muse reduces the size to a ratio, * so these only need to carry the right shape. * * Ratios outside the preset list get a size with a 1024 short edge, as long as * they are a valid W:H between 1:16 and 16:1. Anything else falls back to square. * * @param string $ratio Aspect ratio such as 16:9. * @return string WxH */ public static function muse_size_for_ratio( $ratio ) { $sizes = array( '1:1' => '1024x1024', '16:9' => '1792x1024', '9:16' => '1024x1792', '4:3' => '1365x1024', '3:4' => '1024x1365', '3:2' => '1536x1024', '2:3' => '1024x1536', '2:1' => '2048x1024', '1:2' => '1024x2048', ); if ( !is_string( $ratio ) ) { return $sizes['1:1']; } $ratio = trim( $ratio ); if ( isset( $sizes[$ratio] ) ) { return $sizes[$ratio]; } if ( !preg_match( '/^(\\d{1,5}):(\\d{1,5})$/', $ratio, $parts ) ) { return $sizes['1:1']; } $w = (int) $parts[1]; $h = (int) $parts[2]; if ( $w < 1 || $h < 1 || $w > 16 * $h || $h > 16 * $w ) { return $sizes['1:1']; } if ( $w >= $h ) { return (int) round( 1024 * $w / $h ) . 'x1024'; } return '1024x' . (int) round( 1024 * $h / $w ); } /** * Call the Meta Model API (Muse Image) for image generation. Pro only. * * @param string $prompt Image prompt. * @param array $settings Plugin settings. * @param string $quality Unused, Muse has no quality tiers. * @return string|\WP_Error Path to temp file on success, WP_Error on failure. */ private function call_muse_api( $prompt, $settings, $quality = null ) { if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Meta Muse is a Pro feature. Please upgrade to use Muse for image generation.', 'ai-featured-image-generator' )); } return new \WP_Error('premium_required', __( 'Meta Muse is a Pro feature.', 'ai-featured-image-generator' )); } /** * The OpenAI aspect ratio closest to an image's real shape. * * @param int $width Width in pixels. * @param int $height Height in pixels. * @return string Aspect ratio such as 3:2. */ private static function closest_openai_ratio( $width, $height ) { $ratios = array( '1:1' => 1.0, '3:2' => 1.5, '2:3' => 2 / 3, '16:9' => 16 / 9, '9:16' => 9 / 16, ); if ( $width < 1 || $height < 1 ) { return '1:1'; } $shape = $width / $height; $best = '1:1'; $gap = null; foreach ( $ratios as $name => $value ) { // Compare on a log scale so wide and tall shapes are judged the same way. $distance = abs( log( $shape / $value ) ); if ( null === $gap || $distance < $gap ) { $gap = $distance; $best = $name; } } return $best; } /** * Remove the background from an existing featured image with OpenAI GPT Image 2.6. * * The model redraws the picture on a transparent background, so small details can * differ from the original. The original image stays in the Media Library. * * @param int $post_id Post ID. * @return int|\WP_Error New attachment ID on success, WP_Error on failure. */ public function remove_background( $post_id ) { // Pro only. Checked here too, not only by the callers. if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', sprintf( /* translators: %s: feature name */ __( '%s is a Pro feature. Please upgrade to use it.', 'ai-featured-image-generator' ), __( 'Background removal', 'ai-featured-image-generator' ) )); } require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $settings = $this->settings->get_settings(); if ( !Providers::has_api_key( $settings, 'openai' ) ) { return new \WP_Error('no_api_key', __( 'An OpenAI API key is required for background removal.', 'ai-featured-image-generator' )); } // Get current featured image $thumbnail_id = get_post_thumbnail_id( $post_id ); if ( !$thumbnail_id ) { return new \WP_Error('no_featured_image', __( 'No featured image found.', 'ai-featured-image-generator' )); } $image_path = get_attached_file( $thumbnail_id ); if ( !$image_path || !file_exists( $image_path ) ) { return new \WP_Error('image_not_found', __( 'Featured image file not found.', 'ai-featured-image-generator' )); } // Only the 2.6 models return a real transparent background. $model = ( isset( $settings['ai_model'] ) ? (string) $settings['ai_model'] : '' ); if ( !Settings::is_gpt25_model( $model ) ) { $model = 'gpt-image-2.6-flare'; } $size = wp_getimagesize( $image_path ); $temp_file = $this->generate_from_reference( (int) $thumbnail_id, 'Remove the background from this image. Keep the main subject exactly as shown: same shape, colours, materials, text, details, framing and position. Return the isolated subject on a fully transparent background. No backdrop, no floor, no shadow. Do not add, remove or change anything else.', array( 'ai_provider' => 'openai', 'ai_model' => $model, 'aspect_ratio' => self::closest_openai_ratio( ( is_array( $size ) ? (int) $size[0] : 0 ), ( is_array( $size ) ? (int) $size[1] : 0 ) ), 'transparent' => true, ) ); if ( is_wp_error( $temp_file ) ) { // The shared helper words this error for product photos. if ( 'reference_unreadable' === $temp_file->get_error_code() ) { return new \WP_Error('image_not_found', __( 'The featured image could not be read. Use a PNG, JPEG or WebP image.', 'ai-featured-image-generator' )); } return $temp_file; } // Never save a picture that only looks transparent, or that kept its background. // A subject that touches the edges is fine, so only a picture with no clear edge pixels at all is refused. $scan = Image_Pixels::background_scan( $temp_file ); $no_alpha = is_array( $scan ) && empty( $scan['too_large'] ) && (float) $scan['alpha_share'] <= 0; if ( Image_Pixels::looks_like_checkerboard( $temp_file ) || $no_alpha ) { wp_delete_file( $temp_file ); return new \WP_Error('background_not_removed', __( 'The image came back without a real transparent background, so it was not saved. Please try again.', 'ai-featured-image-generator' )); } // Get post title for filename $post = get_post( $post_id ); $clean_title = ( $post ? explode( '·', $post->post_title )[0] : 'no-bg' ); $clean_title = trim( $clean_title ); $filename_base = sanitize_file_name( $clean_title . '-no-bg' ); $file_array = array( 'name' => $filename_base . (( 'image/webp' === self::file_mime( $temp_file ) ? '.webp' : '.png' )), 'tmp_name' => $temp_file, ); $attachment_id = media_handle_sideload( $file_array, $post_id ); if ( file_exists( $temp_file ) ) { wp_delete_file( $temp_file ); } if ( is_wp_error( $attachment_id ) ) { return $attachment_id; } $this->carry_logo_marker( $thumbnail_id, $attachment_id ); // Set as new featured image set_post_thumbnail( $post_id, $attachment_id ); return $attachment_id; } /** * Save image to media library. * * @param string $image_data Image data or temporary file path. * @param int $post_id Post ID. * @return int|\WP_Error Attachment ID on success, WP_Error on failure. */ private function save_image( $image_data, $post_id, $title, $settings = null ) { // Animated and vector files keep their own format: no WebP, no logo, no sub-sizes. // Read once and forget at once, so it never carries into the next save. $kind = $this->output_kind; $this->output_kind = ''; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; // Every caller passes a temporary file it just wrote. Nothing is ever fetched from an // address here, so a provider answer can never make the site download a URL. if ( !is_string( $image_data ) || !file_exists( $image_data ) ) { return new \WP_Error('image_missing', __( 'The new image could not be saved. Please try again.', 'ai-featured-image-generator' )); } $temp_file = $image_data; // Get the output format from settings to determine file extension. // Callers (e.g. inline generation) may pass an adjusted settings array so the // inline-specific format overrides are honored; otherwise use the saved settings. if ( $settings === null ) { $settings = $this->settings->get_settings(); } $provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' ); // Check premium status (WebP transcode for Gemini/Grok is a Pro feature). $can_use_premium = Providers::can_use_premium(); // Whether the saved bytes must be transcoded to WebP after generation. // OpenAI returns WebP natively, so only Gemini and Grok ever need a server-side conversion. $convert_to_webp = false; // Determine file extension based on provider if ( 'gif' === $kind || 'svg' === $kind ) { $extension = $kind; } elseif ( $provider === 'gemini' && $can_use_premium ) { // Gemini returns PNG natively; Pro users can transcode to WebP (default). $gemini_format = ( isset( $settings['gemini_output_format'] ) ? $settings['gemini_output_format'] : 'webp' ); if ( $gemini_format === 'webp' ) { $convert_to_webp = true; $extension = 'webp'; } else { $extension = 'png'; } } elseif ( $provider === 'gemini' ) { // Free users (defense in depth, Gemini is a Pro provider): native PNG. $extension = 'png'; } elseif ( $provider === 'grok' ) { // Grok returns JPEG natively; Pro users can transcode to WebP (default). if ( $can_use_premium ) { $grok_format = ( isset( $settings['grok_output_format'] ) ? $settings['grok_output_format'] : 'webp' ); if ( $grok_format === 'webp' ) { $convert_to_webp = true; $extension = 'webp'; } else { $extension = 'jpg'; } } else { // Free users keep Grok's native JPEG (WebP is a Pro teaser only). $extension = 'jpg'; } } elseif ( $provider === 'muse' ) { // Muse honors output_format via its API, so no server-side transcode is needed. $muse_format = ( isset( $settings['muse_output_format'] ) ? $settings['muse_output_format'] : 'webp' ); $extension = ( $muse_format === 'jpeg' ? 'jpg' : $muse_format ); } else { // OpenAI supports custom formats (default for all non-premium users) $output_format = ( isset( $settings['output_format'] ) ? $settings['output_format'] : 'webp' ); $extension = ( $output_format === 'jpeg' ? 'jpg' : $output_format ); } // Transcode to WebP for providers that do not return it natively (Pro only). // If the server cannot produce WebP, fall back to the provider's native format // so generation never fails because of an optional optimization. if ( $convert_to_webp ) { $webp_error = ''; $converted = $this->convert_to_webp( $temp_file, $webp_error ); if ( $converted ) { if ( $converted !== $temp_file && file_exists( $temp_file ) ) { wp_delete_file( $temp_file ); } $temp_file = $converted; $extension = 'webp'; } else { // Graceful fallback: keep the provider's native format and record a // non-fatal notice so the caller can tell the user (with the reason). $extension = ( $provider === 'grok' ? 'jpg' : 'png' ); $native_label = ( $provider === 'grok' ? 'JPEG' : 'PNG' ); $this->last_webp_notice = array( 'code' => 'webp_conversion_failed', 'message' => sprintf( /* translators: %s: the image format used instead, e.g. PNG or JPEG. */ __( 'WebP conversion could not be completed on this server, so the image was saved as %s instead.', 'ai-featured-image-generator' ), $native_label ), 'reason' => $webp_error, ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'AIFI: WebP conversion fallback for ' . $provider . ': ' . $webp_error ); } } } // Overlay the brand logo once the final format is settled, so the watermark // survives a WebP fallback. A failed overlay must never fail the generation. $logo_applied = false; if ( !empty( $settings['aifi_apply_brand_logo'] ) ) { if ( '' !== $kind ) { $this->add_note( __( 'The brand logo is not added to animated or vector images.', 'ai-featured-image-generator' ) ); } else { $logo_applied = $this->get_brand_kit()->apply_logo_overlay( $temp_file ); } } // Get post title and sanitize it for use as filename // Remove any "· PostType" suffix that might come from WordPress admin (e.g., "My Title · Movie") $clean_title = explode( '·', (string) $title )[0]; $clean_title = trim( $clean_title ); $filename = sanitize_file_name( $clean_title ); $file_array = array( 'name' => $filename . '.' . $extension, 'tmp_name' => $temp_file, ); // Move the temporary file into the uploads directory if ( '' !== $kind ) { $attachment_id = $this->sideload_special( $file_array, $post_id, $kind, $settings ); } else { $attachment_id = media_handle_sideload( $file_array, $post_id ); } // Clean up the temporary file if ( file_exists( $temp_file ) ) { wp_delete_file( $temp_file ); } if ( is_wp_error( $attachment_id ) ) { return $attachment_id; } // Lets the assistant's apply-brand-logo tool know this image already carries the logo. if ( $logo_applied ) { update_post_meta( $attachment_id, Abilities::META_LOGO_APPLIED, 1 ); } return $attachment_id; } /** * Save an animated GIF or a vector SVG made by the plugin. * * WordPress would make still sub-sizes of a GIF (losing the animation) and refuses * SVG uploads. For this one file only: no sub-sizes, no big-image scaling, and SVG * is allowed as the plugin cleaned it with Svg::sanitize() before writing it. * * @param array $file_array name and tmp_name. * @param int $post_id Parent post. * @param string $kind 'gif' or 'svg'. * @param array $settings Settings for this request. * @return int|\WP_Error Attachment ID. */ private function sideload_special( $file_array, $post_id, $kind, $settings ) { $no_sizes = '__return_empty_array'; $no_scaling = '__return_false'; $mimes = function ( $mimes ) { $mimes['svg'] = 'image/svg+xml'; return $mimes; }; $filetype = function ( $data, $file, $filename ) { if ( is_string( $filename ) && preg_match( '/\\.svg$/i', $filename ) ) { return array( 'ext' => 'svg', 'type' => 'image/svg+xml', 'proper_filename' => false, ); } return $data; }; $svg_xml = ( 'svg' === $kind && file_exists( $file_array['tmp_name'] ) ? (string) file_get_contents( $file_array['tmp_name'] ) : '' ); add_filter( 'intermediate_image_sizes_advanced', $no_sizes, 999 ); add_filter( 'big_image_size_threshold', $no_scaling, 999 ); if ( 'svg' === $kind ) { add_filter( 'upload_mimes', $mimes, 999 ); add_filter( 'wp_check_filetype_and_ext', $filetype, 999, 3 ); } // The filters must go even when the sideload throws, or every later upload would allow SVG. try { $attachment_id = media_handle_sideload( $file_array, $post_id ); } finally { remove_filter( 'intermediate_image_sizes_advanced', $no_sizes, 999 ); remove_filter( 'big_image_size_threshold', $no_scaling, 999 ); if ( 'svg' === $kind ) { remove_filter( 'upload_mimes', $mimes, 999 ); remove_filter( 'wp_check_filetype_and_ext', $filetype, 999 ); } } if ( is_wp_error( $attachment_id ) ) { return $attachment_id; } if ( 'svg' === $kind ) { // WordPress makes no metadata for SVG; record the size so themes and the media library show it. list( $w, $h ) = Svg::dimensions( $svg_xml ); wp_update_attachment_metadata( $attachment_id, array( 'width' => $w, 'height' => $h, 'file' => _wp_relative_upload_path( (string) get_attached_file( $attachment_id ) ), 'sizes' => array(), ) ); update_post_meta( $attachment_id, '_aifi_vector', 1 ); } else { $anim = ( isset( $settings['aifi_animated'] ) && is_array( $settings['aifi_animated'] ) ? $settings['aifi_animated'] : self::normalize_animation( 9, 200 ) ); update_post_meta( $attachment_id, '_aifi_animated', $anim ); } return $attachment_id; } /** * A background-removed copy of a logo-bearing image still shows the * logo, so it keeps the marker that stops apply-brand-logo stamping it again. * * @param int $source_id Image the copy was made from. * @param int $copy_id The new copy. */ private function carry_logo_marker( $source_id, $copy_id ) { if ( get_post_meta( $source_id, Abilities::META_LOGO_APPLIED, true ) || get_post_meta( $source_id, Abilities::META_BRANDED_FROM, true ) ) { update_post_meta( $copy_id, Abilities::META_LOGO_APPLIED, 1 ); } } /** * MIME type of an image file, without needing the fileinfo extension. * * Reads the image header with wp_get_image_mime(), then falls back to the file name. * * @param string $path File path. * @return string MIME type, 'image/png' when nothing is known. */ private static function file_mime( $path ) { $mime = ( function_exists( 'wp_get_image_mime' ) ? wp_get_image_mime( $path ) : false ); if ( !is_string( $mime ) || '' === $mime ) { $check = wp_check_filetype( basename( (string) $path ) ); $mime = ( !empty( $check['type'] ) ? $check['type'] : 'image/png' ); } return $mime; } /** * Convert a generated image file to WebP. * * Used for providers (Gemini, Grok) whose APIs do not return WebP natively. * Tries the WordPress image editor first (Imagick or GD, whichever the host * supports) and falls back to direct GD. Transparency is preserved when the * source is a PNG. Returns the path to a new WebP file, or false when the * server cannot produce WebP (the caller then keeps the original format). * * @param string $source_path Path to the source image (PNG/JPEG bytes). * @return string|false Path to the converted WebP file, or false on failure. */ public function convert_file_to_webp( $source_path, &$error = null ) { return $this->convert_to_webp( $source_path, $error ); } private function convert_to_webp( $source_path, &$error = null ) { $error = ''; if ( !is_string( $source_path ) || !file_exists( $source_path ) ) { $error = __( 'The generated image file could not be read for conversion.', 'ai-featured-image-generator' ); return false; } /** * Filter the WebP quality (1-100) used when transcoding Gemini/Grok output. * * 82 is a deliberate balance between visual quality and file size for * SEO-friendly, lightweight web images. * * @param int $quality Quality value (1-100). * @param string $source_path Path to the source image being converted. */ $quality = (int) apply_filters( 'aifi_webp_quality', 82, $source_path ); $quality = max( 1, min( 100, $quality ) ); $dest_path = $source_path . '.webp'; // Most specific failure reason encountered along the way (for the user). $editor_error = ''; // 1) Preferred: the WordPress image editor (auto-selects Imagick or GD). if ( function_exists( 'wp_get_image_editor' ) ) { $editor = wp_get_image_editor( $source_path ); if ( !is_wp_error( $editor ) ) { // When the output format differs from the source, core's // get_output_format() resets the quality to the format default, // ignoring set_quality(). Force our quality through the filter it // honors, scoped tightly to this single save() call. $force_quality = function () use($quality) { return $quality; }; add_filter( 'wp_editor_set_quality', $force_quality, 999 ); $editor->set_quality( $quality ); $saved = $editor->save( $dest_path, 'image/webp' ); remove_filter( 'wp_editor_set_quality', $force_quality, 999 ); if ( is_wp_error( $saved ) ) { $editor_error = $saved->get_error_message(); } elseif ( !empty( $saved['path'] ) && file_exists( $saved['path'] ) && filesize( $saved['path'] ) > 0 ) { // The editor silently falls back to JPEG/PNG when it cannot // encode WebP (e.g. Imagick built without the WebP delegate), // returning success for a non-WebP file. Only accept a result // that is genuinely WebP; otherwise discard it and try GD, // which can encode WebP even when Imagick cannot. $is_webp = isset( $saved['mime-type'] ) && $saved['mime-type'] === 'image/webp' || strtolower( pathinfo( $saved['path'], PATHINFO_EXTENSION ) ) === 'webp'; if ( $is_webp ) { return $saved['path']; } wp_delete_file( $saved['path'] ); $editor_error = __( 'The active image library (ImageMagick) does not support WebP output.', 'ai-featured-image-generator' ); } } else { $editor_error = $editor->get_error_message(); } } // 2) Fallback: direct GD (covers hosts whose editor lacks WebP support). if ( function_exists( 'imagewebp' ) && function_exists( 'imagecreatefromstring' ) ) { $bytes = @file_get_contents( $source_path ); if ( $bytes !== false ) { if ( function_exists( 'wp_raise_memory_limit' ) ) { wp_raise_memory_limit( 'image' ); } $image = @imagecreatefromstring( $bytes ); if ( $image !== false ) { if ( function_exists( 'imagepalettetotruecolor' ) ) { imagepalettetotruecolor( $image ); } imagealphablending( $image, false ); imagesavealpha( $image, true ); $ok = imagewebp( $image, $dest_path, $quality ); imagedestroy( $image ); if ( $ok && file_exists( $dest_path ) && filesize( $dest_path ) > 0 ) { return $dest_path; } } } } // WebP conversion failed. Remove any partial / zero-byte output a failed // attempt may have left behind, then bail out so the caller keeps the // provider's native format. if ( file_exists( $dest_path ) ) { wp_delete_file( $dest_path ); } // Build a clear, human-readable reason for the user. if ( !self::webp_conversion_supported() ) { $error = __( 'This server has no WebP-capable image library (GD compiled with WebP, or ImageMagick with the WebP delegate).', 'ai-featured-image-generator' ); } elseif ( $editor_error !== '' ) { // Image-library messages (e.g. ImageMagick exceptions) can embed // absolute server paths; strip them before showing the user. $error = $this->redact_paths( $editor_error ); } else { $error = __( 'The server image library failed to encode the image as WebP.', 'ai-featured-image-generator' ); } return false; } /** * Remove absolute filesystem paths from a library error message so it can be * safely shown to the user without disclosing server directory structure. * * @param string $message Raw error message. * @return string Sanitized message. */ private function redact_paths( $message ) { if ( !is_string( $message ) || $message === '' ) { return ''; } $roots = array(); if ( defined( 'ABSPATH' ) ) { $roots[] = ABSPATH; } $uploads = wp_get_upload_dir(); if ( !empty( $uploads['basedir'] ) ) { $roots[] = $uploads['basedir']; } if ( function_exists( 'get_temp_dir' ) ) { $roots[] = get_temp_dir(); } $message = str_replace( $roots, '', $message ); // Collapse any remaining absolute filesystem paths (2+ segments). $message = preg_replace( '#(?:/[^/\\s"\']+){2,}#', '[path]', $message ); return trim( $message ); } /** * Generate an inline image (not set as featured image). * * Used by the Gutenberg block to generate images that are inserted * directly into post content rather than as featured images. * * @param string $prompt Image prompt. * @param string $style Style preset. * @param string $aspect_ratio Aspect ratio (e.g., '16:9'). * @param int $post_id Optional post ID for attachment. * @param int $display_width Display width in pixels for size optimization. * @param string $custom_text Optional custom text to overlay on the image. * @param bool $use_brand_kit Whether to apply the brand kit to this generation. * @return array|\WP_Error Attachment data or error. */ public function generate_inline_image( $prompt, $style = '', $aspect_ratio = '', $post_id = 0, $display_width = 1200, $custom_text = '', $use_brand_kit = true, $overrides = array() ) { // Clear any notice from a previous generation on this instance. $this->last_webp_notice = null; $this->last_notes = array(); $settings = $this->apply_overrides( $this->settings->get_settings(), $overrides ); $this->output_kind = ''; $extras = $this->check_gpt26_extras( $settings ); if ( is_wp_error( $extras ) ) { return $extras; } // Build prompt with style $style = ( !empty( $style ) ? $style : $settings['default_style'] ?? 'realistic' ); $final_prompt = $prompt; // The old Stability presets (sp_ prefix) are gone; a saved one means no style. if ( strpos( $style, 'sp_' ) === 0 ) { $style = 'none'; } $style_prompt = $this->get_style_prompt( $style ); // Only add style prompt if style is not 'none' and prompt is not empty if ( $style !== 'none' && $style_prompt !== '' ) { $final_prompt .= ' ' . $style_prompt; } // Handle text on image - block custom_text is independent from global allow_text setting if ( !empty( $custom_text ) ) { // Custom text provided from block - always add it regardless of global setting $final_prompt .= ' please add the "' . $custom_text . '" text on the image '; } elseif ( empty( $settings['allow_text'] ) || $settings['allow_text'] === false ) { // No custom text and global setting disables text $final_prompt .= ' no text, no captions, no words, no letters, no writing'; } // Override aspect ratio if provided from block attribute if ( !empty( $aspect_ratio ) ) { $settings['gemini_aspect_ratio'] = $aspect_ratio; $settings['default_size'] = $this->map_aspect_to_openai_size( $aspect_ratio, $settings['ai_model'] ?? 'gpt-image-2' ); $settings['grok_aspect_ratio'] = $aspect_ratio; $settings['muse_aspect_ratio'] = $aspect_ratio; } else { // Use inline-specific defaults per provider $provider = $settings['ai_provider'] ?? 'openai'; if ( $provider === 'openai' && isset( $settings['inline_default_size'] ) ) { $settings['default_size'] = $settings['inline_default_size']; } elseif ( $provider === 'gemini' && isset( $settings['inline_gemini_aspect_ratio'] ) ) { $settings['gemini_aspect_ratio'] = $settings['inline_gemini_aspect_ratio']; } elseif ( $provider === 'grok' && isset( $settings['inline_grok_aspect_ratio'] ) ) { $settings['grok_aspect_ratio'] = $settings['inline_grok_aspect_ratio']; } elseif ( $provider === 'muse' && isset( $settings['inline_muse_aspect_ratio'] ) ) { $settings['muse_aspect_ratio'] = $settings['inline_muse_aspect_ratio']; } } // Optimize quality based on display width $optimized_quality = $this->get_optimized_quality( $display_width ); $settings['image_quality'] = $optimized_quality['quality']; // For Gemini, optimize image size based on display width if ( ($settings['ai_provider'] ?? 'openai') === 'gemini' ) { $settings['gemini_image_size'] = $optimized_quality['gemini_size']; } // Use inline-specific output format for OpenAI if ( ($settings['ai_provider'] ?? 'openai') === 'openai' && isset( $settings['inline_output_format'] ) ) { $settings['output_format'] = $settings['inline_output_format']; } // Use inline-specific output format for Gemini (WebP transcode is Pro-gated in save_image) if ( ($settings['ai_provider'] ?? 'openai') === 'gemini' && isset( $settings['inline_gemini_output_format'] ) ) { $settings['gemini_output_format'] = $settings['inline_gemini_output_format']; } // Use inline-specific output format for Grok (WebP transcode is Pro-gated in save_image) if ( ($settings['ai_provider'] ?? 'openai') === 'grok' && isset( $settings['inline_grok_output_format'] ) ) { $settings['grok_output_format'] = $settings['inline_grok_output_format']; } // Use inline-specific output format for Muse if ( ($settings['ai_provider'] ?? 'openai') === 'muse' && isset( $settings['inline_muse_output_format'] ) ) { $settings['muse_output_format'] = $settings['inline_muse_output_format']; } // Applied after the inline overrides. if ( $use_brand_kit ) { $final_prompt = $this->apply_brand_kit( $final_prompt, $settings ); } // Allow filtering the prompt $final_prompt = apply_filters( 'aifi_build_inline_prompt', $final_prompt, $style ); // Call AI API $image_data = $this->call_ai_api( $final_prompt, $settings, null ); if ( is_wp_error( $image_data ) ) { return $image_data; } // Save image (does NOT set as featured image). // Pass the inline-adjusted $settings so per-tab output formats are honored. $title = sanitize_title( substr( $prompt, 0, 50 ) ); $attachment_id = $this->save_image( $image_data, $post_id, $title, $settings ); if ( is_wp_error( $attachment_id ) ) { return $attachment_id; } // Get attachment data $attachment_url = wp_get_attachment_url( $attachment_id ); $attachment_meta = wp_get_attachment_metadata( $attachment_id ); // Auto alt text (for inline, title = prompt since there's no post title context) $alt_text = $this->apply_auto_alt_text( $attachment_id, array( 'title' => $prompt, 'prompt' => $prompt, 'style' => $style, ) ); // Fire action hook for inline image generation do_action( 'aifi_after_generate_inline', $attachment_id, $post_id ); return array( 'attachment_id' => $attachment_id, 'url' => $attachment_url, 'alt' => ( $alt_text ? $alt_text : $prompt ), 'width' => $attachment_meta['width'] ?? 0, 'height' => $attachment_meta['height'] ?? 0, ); } /** * The Brand Kit helper. * * @return Brand_Kit */ public function brand_kit() { return $this->get_brand_kit(); } /** * Width divided by height of the image a model really returns for an aspect ratio. * OpenAI maps 4:3 and 3:4 to its 3:2 and 2:3 sizes; other providers keep the ratio. * * @param string $provider Provider slug. * @param string $model Model slug. * @param string $aspect Aspect ratio such as 4:3. * @return float */ public function expected_ratio( $provider, $model, $aspect ) { if ( 'openai' === $provider ) { $size = $this->map_aspect_to_openai_size( (string) $aspect, (string) $model ); if ( preg_match( '/^(\\d+)x(\\d+)$/', (string) $size, $m ) && (int) $m[2] > 0 ) { return round( (int) $m[1] / (int) $m[2], 4 ); } } if ( preg_match( '/^(\\d+):(\\d+)$/', (string) $aspect, $m ) && (int) $m[2] > 0 ) { return round( (int) $m[1] / (int) $m[2], 4 ); } return 1.0; } /** * Make a new image from a reference photo (Product Images). Returns a temp file, not an * attachment, so the caller can check it and remove its background before saving. * * The Brand Kit never reaches this request: no palette, tone, description or reference. * * @param int $reference_id Attachment of the product photo. * @param string $prompt Prompt. * @param array $overrides ai_provider, ai_model, aspect_ratio, transparent (bool). * @return string|\WP_Error Temp file path. */ public function generate_from_reference( $reference_id, $prompt, $overrides = array() ) { require_once ABSPATH . 'wp-admin/includes/file.php'; // wp_tempnam() is not loaded on REST requests. $this->output_kind = ''; $settings = $this->apply_overrides( $this->settings->get_settings(), $overrides ); unset($settings['aifi_brand_reference'], $settings['aifi_animated'], $settings['aifi_vector']); // Only this request decides the background and format, never the site-wide defaults. $transparent = !empty( $overrides['transparent'] ); $settings['openai_background'] = ( $transparent ? 'transparent' : 'auto' ); if ( $transparent ) { // Transparency needs PNG or WebP: keep the site's WebP choice, anything else becomes PNG. foreach ( array('output_format', 'gemini_output_format') as $format_key ) { if ( !isset( $settings[$format_key] ) || 'webp' !== $settings[$format_key] ) { $settings[$format_key] = 'png'; } } } $payload = $this->get_brand_kit()->build_reference_payload( (int) $reference_id ); if ( !is_array( $payload ) ) { return new \WP_Error('reference_unreadable', __( 'The product photo could not be read.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $provider = ( isset( $settings['ai_provider'] ) ? $settings['ai_provider'] : 'openai' ); if ( 'openai' === $provider ) { return $this->provider_result( $this->call_openai_edit_api( $prompt, $settings, $payload ) ); } if ( 'gemini' === $provider ) { $settings['aifi_reference_image'] = $payload; return $this->provider_result( $this->call_gemini_api( $prompt, $settings ) ); } return new \WP_Error('reference_unsupported', __( 'Product Images works with OpenAI and Gemini models only.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } /** * OpenAI images/edits: a new image from a reference photo. * * @param string $prompt Prompt. * @param array $settings Settings for this request. * @param array $payload Reference from Brand_Kit::build_reference_payload(). * @return string|\WP_Error Temp file path. */ private function call_openai_edit_api( $prompt, $settings, $payload ) { $model = $this->effective_openai_model( $settings ); $api_key = ( isset( $settings['openai_api_key'] ) ? $settings['openai_api_key'] : (( isset( $settings['api_key'] ) ? $settings['api_key'] : '' )) ); $size = ( isset( $settings['default_size'] ) ? $settings['default_size'] : '1024x1024' ); $format = ( isset( $settings['output_format'] ) && in_array( $settings['output_format'], array('png', 'jpeg', 'webp'), true ) ? $settings['output_format'] : 'png' ); $quality = ( isset( $settings['openai_quality'] ) ? $settings['openai_quality'] : 'high' ); if ( in_array( $quality, Settings::OPENAI_GPT25_QUALITIES, true ) && !Settings::is_gpt25_model( $model ) ) { $quality = 'high'; } $transparent = isset( $settings['openai_background'] ) && 'transparent' === $settings['openai_background']; if ( $transparent && 'webp' !== $format ) { $format = 'png'; } $fields = array( 'model' => $model, 'prompt' => $prompt, 'n' => '1', 'size' => $size, 'quality' => $quality, 'output_format' => $format, ); if ( 'png' !== $format ) { $fields['output_compression'] = (string) (( isset( $settings['image_quality'] ) ? (int) $settings['image_quality'] : 90 )); } // GPT Image 2 rejects transparent; only the 2.6 models get the field. if ( $transparent && Settings::is_gpt25_model( $model ) ) { $fields['background'] = 'transparent'; } if ( Settings::is_gpt25_model( $model ) ) { $complexity = ( isset( $settings['openai_complexity'] ) ? $settings['openai_complexity'] : 'auto' ); if ( in_array( $complexity, array('low', 'medium', 'high'), true ) ) { $fields['complexity'] = $complexity; } } $boundary = wp_generate_password( 24, false ); $body = ''; foreach ( $fields as $name => $value ) { $body .= '--' . $boundary . "\r\n"; $body .= 'Content-Disposition: form-data; name="' . $name . '"' . "\r\n\r\n"; $body .= $value . "\r\n"; } $body .= '--' . $boundary . "\r\n"; $body .= 'Content-Disposition: form-data; name="image[]"; filename="' . $payload['filename'] . '"' . "\r\n"; $body .= 'Content-Type: ' . $payload['mime_type'] . "\r\n\r\n"; $body .= $payload['bytes'] . "\r\n"; $body .= '--' . $boundary . '--' . "\r\n"; $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, ), 'body' => $body, 'timeout' => 240, 'httpversion' => '1.1', 'sslverify' => true, 'blocking' => true, ); $args = apply_filters( 'aifi_api_request_args', $args ); $response = wp_remote_post( 'https://api.openai.com/v1/images/edits', $args ); if ( is_wp_error( $response ) ) { if ( false !== strpos( $response->get_error_message(), 'timed out' ) ) { return new \WP_Error('api_timeout', __( 'The request timed out. Please try again.', 'ai-featured-image-generator' )); } /* translators: %s: the connection error message */ return new \WP_Error('api_connection_error', sprintf( __( 'Connection failed: %s', 'ai-featured-image-generator' ), $response->get_error_message() )); } $code = wp_remote_retrieve_response_code( $response ); $raw = wp_remote_retrieve_body( $response ); if ( 200 !== $code ) { return $this->handle_api_error( $code, __( 'Unknown API error occurred.', 'ai-featured-image-generator' ), $raw ); } $data = json_decode( $raw, true ); if ( JSON_ERROR_NONE !== json_last_error() || empty( $data['data'][0]['b64_json'] ) ) { return new \WP_Error('api_data_error', __( 'No image data found in API response. The image generation may have failed.', 'ai-featured-image-generator' )); } $bytes = base64_decode( $data['data'][0]['b64_json'] ); if ( false === $bytes ) { return new \WP_Error('api_decode_error', __( 'Failed to process the generated image data. Please try again.', 'ai-featured-image-generator' )); } $temp = wp_tempnam( 'aifi-' ); if ( !$temp ) { return new \WP_Error('api_temp_file_error', __( 'Unable to create temporary file for the image. Please check your server permissions.', 'ai-featured-image-generator' )); } file_put_contents( $temp, $bytes ); return $temp; } /** * Save a generated temp file as an attachment (Product Images uses this). * * @param string $temp_file Temp file. * @param int $post_id Parent post. * @param string $title File name base. * @param array $settings Settings for this request (aifi_apply_brand_logo, output formats). * @return int|\WP_Error Attachment ID. */ public function save_generated_file( $temp_file, $post_id, $title, $settings ) { return $this->save_image( $temp_file, $post_id, $title, $settings ); } /** * The notes collected so far, for callers that build their own result. * * @param string $note Note to add. */ public function note( $note ) { $this->add_note( (string) $note ); } /** * Start a fresh list of notes and notices (Product Images, one product at a time). */ public function reset_notes() { $this->last_notes = array(); $this->last_webp_notice = null; } /** * Make a Brand Kit logo with GPT Image 2.6: a transparent PNG and, when asked, an SVG copy. * * Uses the saved OpenAI model when it is a 2.6 model, otherwise GPT Image 2.6 Flare, * whatever provider the site uses for other images. The logo overlay is never applied. * * @param string $prompt What the logo shows. * @param bool $svg Also save an SVG copy. * @return array|\WP_Error array( 'png_id' => int, 'svg_id' => int|null, 'notes' => string[] ). */ public function generate_logo( $prompt, $svg = false ) { require_once ABSPATH . 'wp-admin/includes/file.php'; // wp_tempnam() is not loaded on REST requests. $this->last_webp_notice = null; $this->last_notes = array(); $this->output_kind = ''; $settings = $this->settings->get_settings(); $saved = ( isset( $settings['ai_model'] ) ? $settings['ai_model'] : '' ); $model = ( 'openai' === ($settings['ai_provider'] ?? '') && Settings::is_gpt25_model( $saved ) ? $saved : 'gpt-image-2.6-flare' ); $settings['ai_provider'] = 'openai'; $settings['ai_model'] = $model; $settings['openai_background'] = 'transparent'; $settings['output_format'] = 'png'; $settings['default_size'] = '1024x1024'; $settings['aifi_apply_brand_logo'] = false; unset($settings['aifi_animated'], $settings['aifi_vector']); $final_prompt = trim( $prompt ) . ' Flat logo on a transparent background, no text other than the brand name.'; $label = __( 'Brand logo', 'ai-featured-image-generator' ); $temp = $this->provider_result( $this->call_openai_api( $final_prompt, $settings ) ); if ( is_wp_error( $temp ) ) { return $temp; } $png_id = $this->save_image( $temp, 0, 'brand-logo', $settings ); if ( is_wp_error( $png_id ) ) { return $png_id; } update_post_meta( $png_id, '_wp_attachment_image_alt', $label ); $svg_id = null; if ( $svg ) { $settings['aifi_vector'] = true; unset($settings['openai_background']); $temp = $this->provider_result( $this->call_openai_api( $final_prompt, $settings ) ); if ( is_wp_error( $temp ) ) { $this->add_note( sprintf( /* translators: %s: the error message */ __( 'The PNG logo was saved, but the SVG copy failed: %s', 'ai-featured-image-generator' ), $temp->get_error_message() ) ); } else { $saved_svg = $this->save_image( $temp, 0, 'brand-logo', $settings ); if ( is_wp_error( $saved_svg ) ) { $this->add_note( sprintf( /* translators: %s: the error message */ __( 'The PNG logo was saved, but the SVG copy failed: %s', 'ai-featured-image-generator' ), $saved_svg->get_error_message() ) ); } else { $svg_id = (int) $saved_svg; update_post_meta( $svg_id, '_wp_attachment_image_alt', $label ); update_post_meta( $svg_id, '_aifi_logo_svg_of', (int) $png_id ); } } } return array( 'png_id' => (int) $png_id, 'svg_id' => $svg_id, 'notes' => $this->last_notes, ); } /** * Map aspect ratio to OpenAI image size. * * OpenAI only supports 3 native sizes: * - 1024x1024 (1:1 square) * - 1536x1024 (3:2 landscape, used for 4:3, 16:9) * - 1024x1536 (2:3 portrait, used for 3:4, 9:16) * * @param string $aspect_ratio Aspect ratio string (e.g., '16:9'). * @return string OpenAI size string (e.g., '1536x1024'). */ private function map_aspect_to_openai_size( $aspect_ratio, $model = 'gpt-image-2' ) { // GPT Image 2 and 2.6 (and the legacy 'chatgpt-image-latest' alias) share the wide sizes. $is_v2 = Settings::is_gpt2_family( $model ); if ( $is_v2 ) { $mapping = array( '1:1' => '1024x1024', '3:2' => '1536x1024', '2:3' => '1024x1536', '16:9' => '1792x1024', '9:16' => '1024x1792', '3:1' => '1920x640', '1:3' => '640x1920', '4:3' => '1536x1024', '3:4' => '1024x1536', ); } else { $mapping = array( '1:1' => '1024x1024', '4:3' => '1536x1024', '3:2' => '1536x1024', '16:9' => '1536x1024', '3:4' => '1024x1536', '2:3' => '1024x1536', '9:16' => '1024x1536', ); } return $mapping[$aspect_ratio] ?? '1024x1024'; } /** * Get optimized quality and size settings based on display width. * * Optimizes image generation to match the display context: * - Small displays (< 600px): Higher compression, smaller Gemini size * - Medium displays (600-1000px): Balanced quality * - Large displays (> 1000px): Full quality, larger Gemini size * * @param int $display_width Display width in pixels. * @return array Array with 'quality' (1-100) and 'gemini_size' ('1K', '2K', '4K'). */ private function get_optimized_quality( $display_width ) { // Small display: mobile, sidebar, small columns if ( $display_width < 600 ) { return array( 'quality' => 75, 'gemini_size' => '1K', ); } // Medium display: typical content width if ( $display_width < 1000 ) { return array( 'quality' => 85, 'gemini_size' => '1K', ); } // Large display: wide/full layouts, high-res displays if ( $display_width < 1600 ) { return array( 'quality' => 90, 'gemini_size' => '2K', ); } // Extra large display: 4K/retina, full-width layouts return array( 'quality' => 95, 'gemini_size' => '4K', ); } /** * Apply auto alt text to an attachment based on plugin settings. * * @param int $attachment_id Attachment ID. * @param array $context Context array with 'title', 'prompt', and 'style' keys. * @param string $old_alt_text Optional existing alt text from previous featured image. * @return string|false The alt text that was set, or false if disabled. */ private function apply_auto_alt_text( $attachment_id, $context, $old_alt_text = '' ) { $settings = $this->settings->get_settings(); if ( empty( $settings['auto_alt_text'] ) ) { return false; } // If overwrite is disabled and we have old alt text, preserve it $overwrite = ( isset( $settings['alt_text_overwrite'] ) ? (bool) $settings['alt_text_overwrite'] : true ); if ( !$overwrite && !empty( $old_alt_text ) ) { $alt_text = sanitize_text_field( trim( $old_alt_text ) ); update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt_text ); return $alt_text; } $alt_text = $this->build_alt_text( $context ); if ( !empty( $alt_text ) ) { update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt_text ); } return $alt_text; } /** * Build alt text from the Alt Text settings (source and custom format). * * Shared by generated images and the Image Audit "Fill missing alt text" action, * so both follow the same rules. Does not check the Auto Alt Text toggle. * * @param array $context Context array with 'title', and optional 'prompt' and 'style' keys. * @return string Sanitized alt text, possibly empty. */ public function build_alt_text( $context ) { $settings = $this->settings->get_settings(); $source = ( isset( $settings['alt_text_source'] ) ? $settings['alt_text_source'] : 'post_title' ); $title = ( isset( $context['title'] ) ? $context['title'] : '' ); $prompt = ( isset( $context['prompt'] ) ? $context['prompt'] : $title ); $style = ( isset( $context['style'] ) ? $this->get_style_label( $context['style'] ) : '' ); switch ( $source ) { case 'prompt': $alt_text = $prompt; break; case 'custom': $format = ( isset( $settings['alt_text_custom_format'] ) ? $settings['alt_text_custom_format'] : '{title}' ); $alt_text = str_replace( array( '{title}', '{prompt}', '{style}', '{site_name}' ), array( $title, $prompt, $style, get_bloginfo( 'name' ) ), $format ); break; case 'post_title': default: $alt_text = $title; break; } return sanitize_text_field( trim( $alt_text ) ); } /** * Get a human-readable label for a style key. * * @param string $style Style key (e.g. 'realistic', 'custom_0'). * @return string Human-readable label (e.g. 'Realistic'). */ private function get_style_label( $style ) { if ( strpos( $style, 'custom_' ) === 0 ) { $custom_styles = $this->settings->get_custom_styles(); $idx = (int) substr( $style, 7 ); return ( isset( $custom_styles[$idx]['name'] ) ? $custom_styles[$idx]['name'] : $style ); } // Translated, because the label can reach alt text through the {style} tag. $labels = array( 'none' => __( 'None', 'ai-featured-image-generator' ), 'realistic' => __( 'Realistic', 'ai-featured-image-generator' ), 'artistic' => __( 'Artistic', 'ai-featured-image-generator' ), 'cartoon' => __( 'Cartoon', 'ai-featured-image-generator' ), 'sketch' => __( 'Sketch', 'ai-featured-image-generator' ), 'watercolor' => __( 'Watercolor', 'ai-featured-image-generator' ), '3d' => __( '3D Render', 'ai-featured-image-generator' ), 'pixel' => __( 'Pixel Art', 'ai-featured-image-generator' ), 'cyberpunk' => __( 'Cyberpunk', 'ai-featured-image-generator' ), 'fantasy' => __( 'Fantasy', 'ai-featured-image-generator' ), 'anime' => __( 'Anime', 'ai-featured-image-generator' ), 'minimalist' => __( 'Minimalist', 'ai-featured-image-generator' ), 'technicolor' => __( 'Technicolor', 'ai-featured-image-generator' ), ); $labels = array_merge( $labels, Settings::get_trending_styles() ); return ( isset( $labels[$style] ) ? $labels[$style] : $style ); } }