query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", $value_name, '1' ) ); if ( 1 !== (int) $added ) { return false; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "REPLACE INTO {$wpdb->options} ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", $timeout_name, (string) (time() + (int) $ttl) ) ); // The read above may have cached both names as missing for this request. $notoptions = wp_cache_get( 'notoptions', 'options' ); if ( is_array( $notoptions ) ) { unset($notoptions[$value_name], $notoptions[$timeout_name]); wp_cache_set( 'notoptions', $notoptions, 'options' ); } wp_cache_delete( $value_name, 'options' ); wp_cache_delete( $timeout_name, 'options' ); return true; } /** * Initialize REST API. */ public function __construct() { add_action( 'rest_api_init', array($this, 'register_routes') ); } /** * Register REST API routes. */ public function register_routes() { register_rest_route( 'aifi/v1', '/mcp/install-adapter', array( 'methods' => 'POST', 'callback' => array($this, 'mcp_install_adapter'), 'permission_callback' => function ( $request ) { if ( !current_user_can( 'install_plugins' ) && !current_user_can( 'activate_plugins' ) ) { return false; } // Only the settings screen may call this, not an application password. return $this->check_rest_nonce( $request ); }, ) ); register_rest_route( 'aifi/v1', '/mcp/create-key', array( 'methods' => 'POST', 'callback' => array($this, 'mcp_create_key'), 'permission_callback' => function ( $request ) { // Same rule core uses for its own Application Passwords endpoint. if ( !current_user_can( 'edit_posts' ) || !current_user_can( 'create_app_password', get_current_user_id() ) ) { return false; } // Only the settings screen may call this, so an AI client cannot mint more keys. return $this->check_rest_nonce( $request ); }, ) ); register_rest_route( 'aifi/v1', '/mcp/long-sessions', array( 'methods' => 'POST', 'callback' => array($this, 'mcp_long_sessions'), 'permission_callback' => function ( $request ) { if ( !current_user_can( Settings::capability() ) ) { return false; } return $this->check_rest_nonce( $request ); }, 'args' => array( 'enabled' => array( 'required' => true, 'type' => 'boolean', ), ), ) ); register_rest_route( 'aifi/v1', '/mcp/status', array( 'methods' => 'GET', 'callback' => array($this, 'mcp_status'), 'permission_callback' => function () { return current_user_can( 'edit_posts' ); }, ) ); register_rest_route( 'aifi/v1', '/validate-key', array( 'methods' => 'POST', 'callback' => array($this, 'validate_api_key'), 'permission_callback' => function () { // Same right as the settings screen (a network admin on multisite). return current_user_can( Settings::capability() ); }, 'args' => array( 'provider' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'api_key' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); register_rest_route( 'aifi/v1', '/remove-background', array( 'methods' => 'POST', 'callback' => array($this, 'remove_background'), 'permission_callback' => array($this, 'check_media_permission'), 'args' => array( 'post_id' => array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ), ), ) ); // Brand Kit: generate a logo with GPT Image 2.6 (Pro). register_rest_route( 'aifi/v1', '/brand-kit/generate-logo', array( 'methods' => 'POST', 'callback' => array($this, 'generate_logo'), 'permission_callback' => array($this, 'check_admin_permission'), 'args' => array( 'prompt' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', ), 'svg' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); register_rest_route( 'aifi/v1', '/generate-prompt', array( 'methods' => 'POST', 'callback' => array($this, 'generate_prompt'), 'permission_callback' => array($this, 'check_permission'), 'args' => array( 'post_id' => array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ), 'use_brand_kit' => array( 'required' => false, 'type' => 'boolean', 'default' => true, 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); register_rest_route( 'aifi/v1', '/save-prompt', array( 'methods' => 'POST', 'callback' => array($this, 'save_prompt'), 'permission_callback' => array($this, 'check_permission'), 'args' => array( 'post_id' => array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ), 'prompt' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', ), ), ) ); register_rest_route( 'aifi/v1', '/generate', array( 'methods' => 'POST', 'callback' => array($this, 'generate_image'), 'permission_callback' => array($this, 'check_media_permission'), 'args' => array( 'post_id' => array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ), 'title' => array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'prompt' => array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'custom_text' => array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'style' => array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'quality' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => function ( $value ) { $quality = intval( $value ); return max( 1, min( 100, $quality ) ); // Ensure quality is between 1 and 100 }, ), 'use_brand_kit' => array( 'required' => false, 'type' => 'boolean', 'default' => true, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'model' => array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'animated' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); // Listen to this post (Pro). Post routes check the post types chosen on the Audio tab, // which may include WooCommerce products, instead of the image post types. $post_id_arg = array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ); register_rest_route( 'aifi/v1', '/audio/generate', array( 'methods' => 'POST', 'callback' => array($this, 'audio_generate'), 'permission_callback' => array($this, 'check_audio_generate_permission'), 'args' => array( 'post_id' => $post_id_arg, 'job' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_key', ), ), ) ); register_rest_route( 'aifi/v1', '/audio/status', array( 'methods' => 'GET', 'callback' => array($this, 'audio_status'), 'permission_callback' => array($this, 'check_audio_permission'), 'args' => array( 'post_id' => $post_id_arg, ), ) ); register_rest_route( 'aifi/v1', '/audio/delete', array( 'methods' => 'POST', 'callback' => array($this, 'audio_delete'), 'permission_callback' => array($this, 'check_audio_permission'), 'args' => array( 'post_id' => $post_id_arg, ), ) ); register_rest_route( 'aifi/v1', '/audio/toggle', array( 'methods' => 'POST', 'callback' => array($this, 'audio_toggle'), 'permission_callback' => array($this, 'check_audio_permission'), 'args' => array( 'post_id' => $post_id_arg, 'hidden' => array( 'required' => true, 'type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); // Settings screen only: voice lists and samples. $audio_settings_args = array( 'provider' => array( 'required' => true, 'type' => 'string', 'enum' => Audio::PROVIDERS, ), 'api_key' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), ); register_rest_route( 'aifi/v1', '/audio/voices', array( 'methods' => 'POST', 'callback' => array($this, 'audio_voices'), 'permission_callback' => array($this, 'check_settings_permission'), 'args' => $audio_settings_args + array( 'refresh' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); register_rest_route( 'aifi/v1', '/audio/preview', array( 'methods' => 'POST', 'callback' => array($this, 'audio_preview'), 'permission_callback' => array($this, 'check_settings_permission'), 'args' => $audio_settings_args + array( 'voice' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'model' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } /** * Settings screen requests: administrators with a valid REST nonce. * * @param \WP_REST_Request $request Request object. * @return bool|\WP_Error */ public function check_settings_permission( $request ) { if ( !current_user_can( Settings::capability() ) ) { return new \WP_Error('rest_forbidden', __( 'Sorry, you are not allowed to change these settings.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } if ( !wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) { return new \WP_Error('rest_forbidden', __( 'Invalid nonce.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } return true; } /** * Check if user has permission to generate images. * * @param \WP_REST_Request $request Request object. * @return bool|\WP_Error */ /** * Settings-page routes: administrators only, from the plugin's own screens. * * @param \WP_REST_Request $request Request. * @return true|\WP_Error */ public function check_admin_permission( $request ) { if ( !current_user_can( Settings::capability() ) ) { return new \WP_Error('rest_forbidden', __( 'Sorry, you are not allowed to do that.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } if ( !wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) { return new \WP_Error('rest_forbidden', __( 'Invalid nonce.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } return true; } /** * POST /brand-kit/generate-logo: a transparent PNG logo (set as the Brand Kit logo) * and, when asked, an SVG copy in the Media Library. GPT Image 2.6, Pro. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function generate_logo( $request ) { if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Logo generation is a Pro feature. Please upgrade to use it.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } return new \WP_Error('premium_required', __( 'Logo generation is a Pro feature. Please upgrade to use it.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } /** * Routes that add an image to the Media Library also need upload_files, the same as the * block route, so a Contributor cannot create media or spend the site's credits. * * @param \WP_REST_Request $request Request object. * @return true|\WP_Error */ public function check_media_permission( $request ) { $allowed = $this->check_permission( $request ); if ( true !== $allowed ) { return $allowed; } if ( !current_user_can( 'upload_files' ) ) { return new \WP_Error('rest_forbidden', __( 'Your account cannot add images to the Media Library, so it cannot generate them.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } return true; } public function check_permission( $request ) { $post_id = absint( $request['post_id'] ); if ( !current_user_can( 'edit_post', $post_id ) ) { return new \WP_Error('rest_forbidden', __( 'Sorry, you are not allowed to generate images for this post.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } if ( !wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) { return new \WP_Error('rest_forbidden', __( 'Invalid nonce.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } // Check if the post type is enabled for image generation $post = get_post( $post_id ); if ( !$post ) { return new \WP_Error('rest_invalid_post', __( 'Invalid post.', 'ai-featured-image-generator' ), array( 'status' => 404, )); } $settings = new Settings(false); $enabled_post_types = $settings->get_enabled_post_types(); if ( !in_array( $post->post_type, $enabled_post_types, true ) ) { return new \WP_Error('rest_post_type_not_enabled', __( 'AI image generation is not enabled for this post type.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } return true; } /** * Audio post routes: the same checks as check_permission(), but the post type must be one * ticked on the Audio tab (Audio::post_type_allowed()), which may include products. * * @param \WP_REST_Request $request Request object. * @return bool|\WP_Error */ /** * Making a recording saves an audio file to the Media Library and spends the site's * credits, so it also needs upload_files (a Contributor cannot). * * @param \WP_REST_Request $request Request object. * @return true|\WP_Error */ public function check_audio_generate_permission( $request ) { $allowed = $this->check_audio_permission( $request ); if ( true !== $allowed ) { return $allowed; } if ( !current_user_can( 'upload_files' ) ) { return new \WP_Error('rest_forbidden', __( 'Your account cannot add files to the Media Library, so it cannot make recordings.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } return true; } public function check_audio_permission( $request ) { $post_id = absint( $request['post_id'] ); if ( !current_user_can( 'edit_post', $post_id ) ) { return new \WP_Error('rest_forbidden', __( 'Sorry, you are not allowed to edit this post.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } $nonce = $this->check_rest_nonce( $request ); if ( is_wp_error( $nonce ) ) { return $nonce; } $post = get_post( $post_id ); if ( !$post ) { return new \WP_Error('rest_invalid_post', __( 'Invalid post.', 'ai-featured-image-generator' ), array( 'status' => 404, )); } if ( !$this->audio()->post_type_allowed( $post ) ) { return new \WP_Error('audio_post_type', __( 'Audio is not turned on for this post type. Choose post types on the Audio tab.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } return true; } /** * The request carries a valid wp_rest nonce, so it comes from the plugin's own screens and * not from an application password. * * @param \WP_REST_Request $request Request object. * @return true|\WP_Error */ private function check_rest_nonce( $request ) { if ( !wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) { return new \WP_Error('rest_forbidden', __( 'Invalid nonce.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } return true; } /** * The saved API key for a provider (or ElevenLabs), for Test Connection with an empty field. * * @param string $provider Provider slug. * @return string Empty string when none is saved. */ private function saved_api_key( $provider ) { $settings = ( new Settings(false) )->get_settings(); if ( 'elevenlabs' === $provider ) { return ( isset( $settings['elevenlabs_api_key'] ) ? trim( (string) $settings['elevenlabs_api_key'] ) : '' ); } if ( !Providers::is_registered( $provider ) ) { return ''; } return trim( Providers::get_api_key( $settings, $provider ) ); } /** * Validate an API key by making a lightweight test request. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function validate_api_key( $request ) { $provider = $request['provider']; $api_key = trim( (string) $request['api_key'] ); // The settings form never prints a saved key, so an empty field means "test the saved one". if ( '' === $api_key ) { $api_key = $this->saved_api_key( $provider ); } if ( empty( $api_key ) ) { return new \WP_Error('empty_key', __( 'Please enter an API key.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } // ElevenLabs is only used by Listen to this post, which is Pro. if ( $provider === 'elevenlabs' && !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Listen to this post is a Pro feature.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } if ( Providers::is_registered( $provider ) && !Providers::is_available( $provider ) ) { return new \WP_Error('premium_required', sprintf( /* translators: %s: provider name */ __( '%s is a Pro feature.', 'ai-featured-image-generator' ), Providers::label( $provider ) ), array( 'status' => 403, )); } if ( $provider === 'openai' ) { $response = wp_remote_get( 'https://api.openai.com/v1/models', array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, ), 'timeout' => 15, ) ); } elseif ( $provider === 'gemini' ) { // The key goes in a header, not the address, so logging plugins and proxies never record it. $response = wp_remote_get( 'https://generativelanguage.googleapis.com/v1beta/models', array( 'timeout' => 15, 'headers' => array( 'x-goog-api-key' => $api_key, ), ) ); } elseif ( $provider === 'grok' ) { $response = wp_remote_get( 'https://api.x.ai/v1/models', array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, ), 'timeout' => 15, ) ); } elseif ( $provider === 'elevenlabs' ) { $response = wp_remote_get( 'https://api.elevenlabs.io/v1/user', array( 'headers' => array( 'xi-api-key' => $api_key, ), 'timeout' => 15, ) ); } elseif ( $provider === 'muse' ) { $response = wp_remote_get( Generator::MUSE_API_BASE . '/models', array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, ), 'timeout' => 15, ) ); } else { return new \WP_Error('invalid_provider', __( 'Invalid provider.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } if ( is_wp_error( $response ) ) { return new \WP_Error('connection_error', __( 'Could not connect to the API. Please check your internet connection.', 'ai-featured-image-generator' ), array( 'status' => 500, )); } $status_code = wp_remote_retrieve_response_code( $response ); if ( $status_code === 200 ) { $result = array( 'success' => true, 'message' => __( 'API key is valid!', 'ai-featured-image-generator' ), ); return rest_ensure_response( $result ); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); $error_message = __( 'Invalid API key.', 'ai-featured-image-generator' ); if ( isset( $body['error']['message'] ) ) { $error_message = $body['error']['message']; } elseif ( isset( $body['detail']['message'] ) && is_string( $body['detail']['message'] ) ) { // ElevenLabs puts its reason under detail. $error_message = $body['detail']['message']; } elseif ( isset( $body['message'] ) ) { $error_message = $body['message']; } return new \WP_Error('invalid_key', $error_message, array( 'status' => $status_code, )); } /** * Generate image via REST API. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function generate_image( $request ) { $post_id = $request['post_id']; // One generation per post at a time (shared with /list-generate and auto-generate). // The lock covers the whole request and is released at the end, like generate_logo(). $lock_key = 'aifi_lock_' . $post_id; if ( !self::take_lock( $lock_key, self::LOCK_TTL ) ) { return new \WP_Error('rest_forbidden', __( 'Please wait a moment before generating another image.', 'ai-featured-image-generator' ), array( 'status' => 429, )); } try { return $this->generate_image_locked( $request ); } finally { set_transient( $lock_key, true, self::COOLDOWN ); } } /** * The /generate work, run while the per-post lock is held. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ private function generate_image_locked( $request ) { $post_id = $request['post_id']; $title = $request['title']; $prompt = $request['prompt']; $custom_text = $request['custom_text']; $style = $request['style']; $quality = $request['quality']; // Older clients omit the field entirely; brand kit stays on by default. $use_brand_kit = ( isset( $request['use_brand_kit'] ) ? (bool) $request['use_brand_kit'] : true ); // Get settings $settings = new Settings(false); $settings_data = $settings->get_settings(); // Check if appropriate API key is configured based on provider $provider = ( isset( $settings_data['ai_provider'] ) ? $settings_data['ai_provider'] : 'openai' ); // Premium check: Gemini is only available for premium users if ( $provider === 'gemini' ) { 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' ), array( 'status' => 403, )); } } // Optional per-request model: GPT Image 2.6 only, OpenAI only, Pro only. $overrides = array(); $model_override = ( isset( $request['model'] ) ? (string) $request['model'] : '' ); if ( $model_override !== '' ) { if ( $provider !== 'openai' || !Settings::is_gpt25_model( $model_override ) ) { return new \WP_Error('invalid_model', __( 'That model is not available for the current AI provider.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'GPT Image 2.6 is a Pro feature. Please upgrade to use it.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } $overrides['ai_model'] = $model_override; } // Animated GIF: GPT Image 2.6 only, which is Pro. if ( !empty( $request['animated'] ) ) { if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Animated images are a Pro feature. Please upgrade to use them.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } $overrides['animated'] = true; } $provider_label = Providers::label( $provider ); if ( !Providers::has_api_key( $settings_data, $provider ) ) { return new \WP_Error('rest_forbidden', sprintf( /* translators: %s: provider name */ __( 'API key not configured for %s. Please configure it in the plugin settings.', 'ai-featured-image-generator' ), $provider_label ), array( 'status' => 400, )); } // Generate image $generator = new Generator($settings); $result = $generator->generate_image( $post_id, $prompt, $style, $title, $custom_text, $quality, $use_brand_kit, $overrides ); if ( is_wp_error( $result ) ) { return $result; } $response = array( 'success' => true, 'attachment_id' => $result, 'url' => wp_get_attachment_url( $result ), 'model' => $overrides['ai_model'] ?? $settings_data['ai_model'] ?? '', ); // Surface a non-fatal WebP-conversion fallback notice, if any. $webp_notice = $generator->get_last_webp_notice(); if ( $webp_notice ) { $response['webp_notice'] = $webp_notice['message']; $response['webp_notice_reason'] = $webp_notice['reason']; } // Plain-language notes, such as a model switch. $notes = $generator->get_last_notes(); if ( !empty( $notes ) ) { $response['notes'] = $notes; } return rest_ensure_response( $response ); } /** * Remove background from featured image via REST API. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function remove_background( $request ) { $post_id = $request['post_id']; // Premium check: background removal is Pro only if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Background removal is a Pro feature. Please upgrade to use this feature.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } // Check for transient lock $lock_key = 'aifi_lock_rmbg_' . $post_id; if ( !self::take_lock( $lock_key, self::LOCK_TTL ) ) { return new \WP_Error('rest_forbidden', __( 'Please wait a moment before processing another image.', 'ai-featured-image-generator' ), array( 'status' => 429, )); } try { $settings = new Settings(false); $generator = new Generator($settings); $result = $generator->remove_background( $post_id ); if ( is_wp_error( $result ) ) { return $result; } return rest_ensure_response( array( 'success' => true, 'attachment_id' => $result, 'url' => wp_get_attachment_url( $result ), ) ); } finally { set_transient( $lock_key, true, self::COOLDOWN ); } } /** * Generate an image prompt from a post's title and body content. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function generate_prompt( $request ) { $post_id = $request['post_id']; $use_brand_kit = !isset( $request['use_brand_kit'] ) || (bool) $request['use_brand_kit']; $settings = new Settings(false); $generator = new Generator($settings); $result = $generator->generate_prompt_from_content( $post_id, $use_brand_kit ); if ( is_wp_error( $result ) ) { return $result; } // Persist the generated prompt to post meta update_post_meta( $post_id, '_aifi_custom_prompt', wp_slash( $result ) ); return rest_ensure_response( array( 'success' => true, 'prompt' => $result, ) ); } /** * Save a custom prompt to post meta. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function save_prompt( $request ) { $post_id = $request['post_id']; $prompt = $request['prompt']; update_post_meta( $post_id, '_aifi_custom_prompt', wp_slash( $prompt ) ); return rest_ensure_response( array( 'success' => true, ) ); } /** * Audio handlers share one instance per request. * * @return Audio */ private function audio() { return new Audio(new Settings(false)); } /** * Make the next part of a post's recording (Pro). * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function audio_generate( $request ) { if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Listen to this post is a Pro feature. Please upgrade to turn posts into audio.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } $result = $this->audio()->step( (int) $request['post_id'], (string) $request['job'] ); if ( is_wp_error( $result ) ) { return $result; } return rest_ensure_response( array( 'success' => true, ) + $result ); } /** * What the post editor shows: the recording, whether it is out of date, and the estimate. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function audio_status( $request ) { if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Listen to this post is a Pro feature. Please upgrade to turn posts into audio.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } $audio = $this->audio(); $post = get_post( (int) $request['post_id'] ); return rest_ensure_response( array( 'success' => true, 'status' => $audio->status( $post ), 'estimate' => $audio->estimate( $post ), 'allowed' => $audio->post_type_allowed( $post ), ) ); } /** * Remove a post's recording (Pro). * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function audio_delete( $request ) { if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Listen to this post is a Pro feature. Please upgrade to turn posts into audio.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } $audio = $this->audio(); $audio->delete_audio( (int) $request['post_id'] ); return rest_ensure_response( array( 'success' => true, 'status' => $audio->status( (int) $request['post_id'] ), ) ); } /** * Hide or show the player on one post (Pro). * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function audio_toggle( $request ) { if ( !Providers::can_use_premium() ) { return new \WP_Error('premium_required', __( 'Listen to this post is a Pro feature. Please upgrade to turn posts into audio.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } $this->audio()->set_hidden( (int) $request['post_id'], (bool) $request['hidden'] ); return rest_ensure_response( array( 'success' => true, 'hidden' => (bool) $request['hidden'], ) ); } /** * Voices for the Audio tab (Pro). * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function audio_voices( $request ) { $voices = $this->audio()->voices( (string) $request['provider'], (string) $request['api_key'], (bool) $request['refresh'] ); if ( is_wp_error( $voices ) ) { return $voices; } return rest_ensure_response( array( 'success' => true, 'voices' => $voices, ) ); } /** * A short sample of a voice for the Audio tab (Pro). Nothing is saved. * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function audio_preview( $request ) { $sample = $this->audio()->preview( (string) $request['provider'], (string) $request['voice'], (string) $request['model'], (string) $request['api_key'] ); if ( is_wp_error( $sample ) ) { return $sample; } return rest_ensure_response( array( 'success' => true, ) + $sample ); } /** * Turn 30-day assistant connections on or off. * * @param \WP_REST_Request $request REST request object. * @return array */ public function mcp_long_sessions( $request ) { $enabled = (bool) $request->get_param( 'enabled' ); update_option( Abilities::LONG_SESSIONS_OPTION, ( $enabled ? '1' : '0' ), false ); return array( 'enabled' => $enabled, 'message' => __( 'Saved.', 'ai-featured-image-generator' ), ); } /** * Whether an assistant has reached the site yet, for the "Connected" tick. * * @return array */ public function mcp_status() { $at = ( class_exists( '\\AIFI\\Abilities' ) ? Abilities::connected_at() : 0 ); return array( 'connected' => $at > 0, 'connected_at' => ( $at ? date_i18n( get_option( 'date_format' ), $at ) : '' ), ); } /** * Install (or just activate) the official MCP Adapter plugin. * * @return \WP_REST_Response|\WP_Error */ public function mcp_install_adapter() { require_once ABSPATH . 'wp-admin/includes/plugin.php'; $plugin_file = 'mcp-adapter/mcp-adapter.php'; if ( !file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ) ) { if ( !current_user_can( 'install_plugins' ) ) { return new \WP_Error('rest_forbidden', __( 'You are not allowed to install plugins on this site.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/misc.php'; $api = plugins_api( 'plugin_information', array( 'slug' => 'mcp-adapter', 'fields' => array( 'sections' => false, ), ) ); if ( is_wp_error( $api ) ) { return new \WP_Error('install_failed', __( 'Could not reach WordPress.org to download the MCP Adapter. Check the connection and try again.', 'ai-featured-image-generator' ), array( 'status' => 500, )); } $upgrader = new \Plugin_Upgrader(new \WP_Ajax_Upgrader_Skin()); $result = $upgrader->install( $api->download_link ); if ( is_wp_error( $result ) || !$result ) { $message = ( is_wp_error( $result ) ? $result->get_error_message() : __( 'The install did not finish.', 'ai-featured-image-generator' ) ); return new \WP_Error('install_failed', $message, array( 'status' => 500, )); } } if ( !current_user_can( 'activate_plugins' ) ) { return new \WP_Error('rest_forbidden', __( 'You are not allowed to activate plugins on this site.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } $activated = activate_plugin( $plugin_file ); if ( is_wp_error( $activated ) ) { return new \WP_Error('activate_failed', $activated->get_error_message(), array( 'status' => 500, )); } return rest_ensure_response( array( 'success' => true, 'message' => __( 'MCP Adapter is installed and active.', 'ai-featured-image-generator' ), ) ); } /** * Create an Application Password for the current user, dedicated to AI assistants. * The password is returned once and never stored by this plugin. * * @return \WP_REST_Response|\WP_Error */ public function mcp_create_key() { $user = wp_get_current_user(); if ( !current_user_can( 'create_app_password', $user->ID ) ) { return new \WP_Error('rest_forbidden', __( 'You are not allowed to create keys for this account.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } if ( !function_exists( 'wp_is_application_passwords_available_for_user' ) || !wp_is_application_passwords_available_for_user( $user ) ) { return new \WP_Error('keys_unavailable', __( 'Keys need a secure (https) site address. Switch the site to HTTPS, then try again.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } // Names must be unique per user, so number the extra keys. $base = 'AI Images (MCP)'; $name = $base; $taken = wp_list_pluck( \WP_Application_Passwords::get_user_application_passwords( $user->ID ), 'name' ); $n = 2; while ( in_array( $name, $taken, true ) ) { $name = $base . ' ' . $n++; } $created = \WP_Application_Passwords::create_new_application_password( $user->ID, array( 'name' => $name, ) ); if ( is_wp_error( $created ) ) { return new \WP_Error('key_failed', $created->get_error_message(), array( 'status' => 500, )); } list( $password ) = $created; $password = \WP_Application_Passwords::chunk_password( $password ); return rest_ensure_response( array( 'success' => true, 'name' => $name, 'username' => $user->user_login, 'password' => $password, 'basic' => base64_encode( $user->user_login . ':' . $password ), 'message' => __( 'Key created.', 'ai-featured-image-generator' ), ) ); } }