settings = $settings; $this->generator = $generator; $this->product_images = $product_images; $this->product_unify = $product_unify; if ( !function_exists( 'wp_register_ability' ) ) { return; } add_action( 'wp_abilities_api_categories_init', array($this, 'register_category') ); add_action( 'wp_abilities_api_init', array($this, 'register_abilities') ); add_action( 'mcp_adapter_init', array($this, 'register_mcp_server') ); add_filter( 'mcp_adapter_prompt_name', array($this, 'prompt_name'), 10, 2 ); add_filter( 'mcp_adapter_session_inactivity_timeout', array($this, 'session_timeout') ); } /** * Whether the owner opted in to 30-day assistant connections. * * @return bool */ public static function long_sessions() { return get_option( self::LONG_SESSIONS_OPTION, '0' ) === '1'; } /** * Keep assistant connections for 30 days without use when the owner opted in. * Every request is still checked against the key, so a longer connection grants nothing new. * * @param int $seconds Timeout from the MCP Adapter or an earlier filter. * @return int */ public function session_timeout( $seconds ) { return ( self::long_sessions() ? max( (int) $seconds, self::LONG_SESSION_SECONDS ) : $seconds ); } /* --------------------------------------------------------------------- * Environment helpers * ------------------------------------------------------------------ */ /** * Whether WordPress core has the Abilities API (6.9+). * * @return bool */ public static function is_supported() { return function_exists( 'wp_register_ability' ); } /** * Whether the MCP Adapter plugin is active. * * @return bool */ public static function is_adapter_active() { if ( !class_exists( '\\WP\\MCP\\Core\\McpAdapter' ) ) { return false; } // The class alone is not enough: WooCommerce bundles the adapter library but // only starts it when its own MCP feature is switched on. Until then the // adapter never fires mcp_adapter_init and no server exists. $plugin = 'mcp-adapter/mcp-adapter.php'; if ( in_array( $plugin, (array) get_option( 'active_plugins', array() ), true ) ) { return true; } if ( is_multisite() && isset( get_site_option( 'active_sitewide_plugins', array() )[$plugin] ) ) { return true; } if ( class_exists( '\\Automattic\\WooCommerce\\Utilities\\FeaturesUtil' ) && \Automattic\WooCommerce\Utilities\FeaturesUtil::feature_is_enabled( 'mcp_integration' ) ) { return true; } return did_action( 'mcp_adapter_init' ) > 0; } /** * Whether the MCP Adapter plugin is installed (active or not). * * @return bool */ public static function is_adapter_installed() { return file_exists( WP_PLUGIN_DIR . '/mcp-adapter/mcp-adapter.php' ); } /** * URL assistants connect to. * * @return string */ public static function get_server_url() { return rest_url( 'mcp/' . self::SERVER_ROUTE ); } /** * @return bool */ private function is_pro() { return Providers::can_use_premium(); } /** * @return string */ private function upgrade_url() { return ( function_exists( 'afig_fs' ) ? afig_fs()->get_upgrade_url() : 'https://wordpress.org/plugins/ai-featured-image-generator/' ); } /** * Ability names attached to this site's MCP server. * * @return string[] */ public function get_tool_names() { $names = array_merge( self::FREE_ABILITIES, self::PRO_ABILITIES ); return array_map( function ( $name ) { return self::CATEGORY . '/' . $name; }, $names ); } /* --------------------------------------------------------------------- * Free limit * ------------------------------------------------------------------ */ /** * Attachment meta on every image an assistant made on a Free site. The count of * these is a floor for the usage counter, so clearing the option gives nothing back. */ const META_FREE_IMAGE = '_aifi_mcp_free_image'; /** * The stored counter, never below 0. On multisite one counter covers the whole * network; an older per-site value still counts. * * @return int */ private static function stored_usage() { $value = (int) get_option( self::USAGE_OPTION, 0 ); if ( is_multisite() ) { $value = max( $value, (int) get_site_option( self::USAGE_OPTION, 0 ) ); } return max( 0, $value ); } /** * Images on this site tagged as made by an assistant on Free. * * @return int */ private static function tagged_usage() { global $wpdb; return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = %s", self::META_FREE_IMAGE ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } /** * Images generated through assistants so far (Free sites only). * * @return int */ public static function get_usage() { return max( self::stored_usage(), self::tagged_usage() ); } /** * Remaining assistant images, or null for unlimited. * * @return int|null */ public static function get_remaining() { if ( Providers::can_use_premium() ) { return null; } return max( 0, self::FREE_MCP_IMAGE_LIMIT - self::get_usage() ); } /** * Change the counter in one SQL statement, so requests that arrive together * cannot all pass the limit. With $delta 1 it only adds when under the limit. * * @param int $delta 1 to take a slot, -1 to give it back. * @return bool Whether the row changed. */ private static function bump_counter( $delta ) { global $wpdb; $multi = is_multisite(); if ( $multi ) { add_site_option( self::USAGE_OPTION, self::stored_usage() ); $table = $wpdb->sitemeta; $key = 'meta_key'; $col = 'meta_value'; $where = $wpdb->prepare( 'site_id = %d AND ', get_current_network_id() ); } else { add_option( self::USAGE_OPTION, 0 ); $table = $wpdb->options; $key = 'option_name'; $col = 'option_value'; $where = ''; } $value = "GREATEST(CAST({$col} AS SIGNED), 0)"; if ( $delta > 0 ) { $sql = $wpdb->prepare( "UPDATE {$table} SET {$col} = {$value} + 1 WHERE {$where}{$key} = %s AND {$value} < %d", self::USAGE_OPTION, self::FREE_MCP_IMAGE_LIMIT ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared } else { $sql = $wpdb->prepare( "UPDATE {$table} SET {$col} = GREATEST({$value} - 1, 0) WHERE {$where}{$key} = %s", self::USAGE_OPTION ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared } $changed = (bool) $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared if ( $multi ) { wp_cache_delete( get_current_network_id() . ':' . self::USAGE_OPTION, 'site-options' ); } else { wp_cache_delete( self::USAGE_OPTION, 'options' ); wp_cache_delete( 'alloptions', 'options' ); } return $changed; } /** * Take one of the Free images before generating. Pro sites are not counted. * * @return true|\WP_Error */ private function reserve_slot() { if ( $this->is_pro() ) { return true; } if ( self::tagged_usage() < self::FREE_MCP_IMAGE_LIMIT && self::bump_counter( 1 ) ) { return true; } return new \WP_Error('mcp_limit_reached', self::limit_message(), array( 'status' => 403, 'upgrade_url' => $this->upgrade_url(), )); } /** * Give the slot back when the image could not be made. */ private function release_slot() { if ( !$this->is_pro() ) { self::bump_counter( -1 ); } } /** * Tag a finished Free image so the count survives a reset of the option. * * @param int $attachment_id New image. */ private function tag_free_image( $attachment_id ) { if ( !$this->is_pro() && $attachment_id ) { update_post_meta( (int) $attachment_id, self::META_FREE_IMAGE, 1 ); } } /** * Plain-language message an assistant can repeat when the Free limit is used up. * * @return string */ public static function limit_message() { return sprintf( /* translators: 1: number of free images, 2: upgrade URL */ __( 'You have used all %1$d free AI-assistant images on this site. Upgrade to Pro for unlimited generation: %2$s', 'ai-featured-image-generator' ), self::FREE_MCP_IMAGE_LIMIT, ( function_exists( 'afig_fs' ) ? afig_fs()->get_upgrade_url() : '' ) ); } /** * @return true|\WP_Error */ private function check_free_limit() { if ( $this->is_pro() ) { return true; } if ( self::get_usage() >= self::FREE_MCP_IMAGE_LIMIT ) { return new \WP_Error('mcp_limit_reached', self::limit_message(), array( 'status' => 403, 'upgrade_url' => $this->upgrade_url(), )); } return true; } /** * @param string $feature Human name of the feature, e.g. "Background removal". * @return true|\WP_Error */ private function require_pro( $feature ) { if ( $this->is_pro() ) { return true; } return $this->premium_error( $feature ); } /** * The upgrade message, always as an error. Used where Pro code is missing from this build. * * @param string $feature Human name of the feature. * @return \WP_Error */ private function premium_error( $feature ) { return new \WP_Error('premium_required', sprintf( /* translators: 1: feature name, 2: upgrade URL */ __( '%1$s is a Pro feature of AI Featured Image Generator, so it did not run. Tell the user, and give them this upgrade link: %2$s', 'ai-featured-image-generator' ), $feature, $this->upgrade_url() ), array( 'status' => 403, 'upgrade_url' => $this->upgrade_url(), )); } /* --------------------------------------------------------------------- * Registration * ------------------------------------------------------------------ */ public function register_category() { wp_register_ability_category( self::CATEGORY, array( 'label' => __( 'AI Featured Image', 'ai-featured-image-generator' ), 'description' => __( 'Generate and manage AI images for posts.', 'ai-featured-image-generator' ), ) ); } public function register_abilities() { $this->register_go_prompt(); $provider_schema = array( 'type' => 'string', 'enum' => Providers::slugs(), 'description' => __( 'Override the provider for this image only. Call list-providers to see which ones have an API key.', 'ai-featured-image-generator' ), ); $model_schema = array( 'type' => 'string', 'description' => __( 'Override the model for this image only. Must belong to the chosen provider.', 'ai-featured-image-generator' ), ); $style_schema = array( 'type' => 'string', 'description' => __( 'Style slug such as realistic, artistic, cartoon, minimalist, watercolor, 3d, anime. Leave empty for the site default.', 'ai-featured-image-generator' ), ); $category_schema = array( 'type' => 'string', 'description' => __( 'Only posts in this category, by name or slug.', 'ai-featured-image-generator' ), ); $tag_schema = array( 'type' => 'string', 'description' => __( 'Only posts with this tag, by name or slug.', 'ai-featured-image-generator' ), ); $author_schema = array( 'type' => 'string', 'description' => __( 'Only posts by this author: display name, username or email.', 'ai-featured-image-generator' ), ); $image_output = array( 'type' => 'object', 'properties' => array( 'attachment_id' => array( 'type' => 'integer', ), 'url' => array( 'type' => 'string', ), 'alt' => array( 'type' => 'string', ), 'width' => array( 'type' => 'integer', ), 'height' => array( 'type' => 'integer', ), 'provider' => array( 'type' => 'string', ), 'model' => array( 'type' => 'string', ), 'remaining' => array( 'type' => array('integer', 'null'), ), 'show_image' => array( 'type' => 'string', ), 'animated' => array( 'type' => 'boolean', ), 'frames' => array( 'type' => 'integer', ), 'vector' => array( 'type' => 'boolean', ), 'notes' => array( 'type' => 'array', 'items' => array( 'type' => 'string', ), ), ), ); $frames_schema = array( 'type' => 'integer', 'minimum' => 2, 'maximum' => 16, 'description' => __( 'Frames in an animated image. Defaults to the site setting (usually 9).', 'ai-featured-image-generator' ), ); $frame_ms_schema = array( 'type' => 'integer', 'minimum' => 20, 'maximum' => 2000, 'description' => __( 'Milliseconds per frame in an animated image. Defaults to the site setting (usually 200).', 'ai-featured-image-generator' ), ); $this->register( 'generate-featured-image', array( 'label' => __( 'Generate featured image', 'ai-featured-image-generator' ), 'description' => __( 'Generate an AI image for a post from its title (plus an optional prompt) and set it as the featured image. Returns the new attachment. Each call costs one image, so when asked to regenerate several posts, list them and get a yes before starting. Set animated for an animated GIF (GPT Image 2.6, Pro). Animated costs up to about one still image per frame.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('post_id'), 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'ID of the post or page.', 'ai-featured-image-generator' ), ), 'prompt' => array( 'type' => 'string', 'description' => __( 'Extra description added to the post title.', 'ai-featured-image-generator' ), ), 'aspect_ratio' => array( 'type' => 'string', 'pattern' => '^[0-9]{1,2}:[0-9]{1,2}$', 'description' => __( 'Shape of the image, such as 16:9. Each provider supports different shapes: call list-providers to see them. Defaults to the site setting.', 'ai-featured-image-generator' ), ), 'style' => $style_schema, 'provider' => $provider_schema, 'model' => $model_schema, 'use_brand_kit' => array( 'type' => 'boolean', 'default' => true, ), 'set_as_featured' => array( 'type' => 'boolean', 'default' => true, 'description' => __( 'Set false to only save the image to the Media Library.', 'ai-featured-image-generator' ), ), 'animated' => array( 'type' => 'boolean', 'default' => false, 'description' => __( 'Make an animated GIF. Needs GPT Image 2.6 Flare or Sunburst (Pro).', 'ai-featured-image-generator' ), ), 'frames' => $frames_schema, 'frame_ms' => $frame_ms_schema, ), ), 'output_schema' => $image_output, 'permission_callback' => array($this, 'can_generate_for_post'), 'execute_callback' => array($this, 'execute_generate_featured_image'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => false, ) ), ) ); $this->register( 'generate-image', array( 'label' => __( 'Generate image', 'ai-featured-image-generator' ), 'description' => __( 'Generate any AI image from a prompt and save it to the Media Library. Returns the attachment and its URL. format animated makes a GIF and vector makes an SVG drawing (both GPT Image 2.6, Pro). Animated costs up to about one still image per frame.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('prompt'), 'additionalProperties' => false, 'properties' => array( 'prompt' => array( 'type' => 'string', 'minLength' => 3, ), 'style' => $style_schema, 'aspect_ratio' => array( 'type' => 'string', 'pattern' => '^[0-9]{1,2}:[0-9]{1,2}$', 'description' => __( 'Shape of the image, such as 16:9. Each provider supports different shapes: call list-providers to see them. Defaults to the site setting.', 'ai-featured-image-generator' ), ), 'provider' => $provider_schema, 'model' => $model_schema, 'use_brand_kit' => array( 'type' => 'boolean', 'default' => true, ), 'format' => array( 'type' => 'string', 'enum' => array('still', 'animated', 'vector'), 'default' => 'still', 'description' => __( 'still (default), animated (GIF) or vector (SVG). Animated and vector need GPT Image 2.6 Flare or Sunburst (Pro).', 'ai-featured-image-generator' ), ), 'frames' => $frames_schema, 'frame_ms' => $frame_ms_schema, ), ), 'output_schema' => $image_output, 'permission_callback' => array($this, 'can_generate'), 'execute_callback' => array($this, 'execute_generate_image'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => false, 'idempotent' => false, ) ), ) ); $this->register( 'list-providers', array( 'label' => __( 'List providers', 'ai-featured-image-generator' ), 'description' => __( 'List the AI providers and models this site can use, which have an API key, which one is active, and the aspect ratios each one supports.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'default' => new \stdClass(), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'active_provider' => array( 'type' => 'string', ), 'active_model' => array( 'type' => 'string', ), 'providers' => array( 'type' => 'array', ), ), ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_list_providers'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'find-posts', array( 'label' => __( 'Find posts', 'ai-featured-image-generator' ), 'description' => __( 'Search posts and pages by title or words, to get the ID for the other tools. Says whether each one already has a featured image.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('search'), 'additionalProperties' => false, 'properties' => array( 'search' => array( 'type' => 'string', 'description' => __( 'Words from the title, or the whole title.', 'ai-featured-image-generator' ), ), 'post_type' => array( 'type' => 'string', 'default' => 'any', 'description' => __( 'post, page, or any.', 'ai-featured-image-generator' ), ), 'category' => $category_schema, 'tag' => $tag_schema, 'author' => $author_schema, 'limit' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 20, 'default' => 10, ), ), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'posts' => array( 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'id' => array( 'type' => 'integer', ), 'title' => array( 'type' => 'string', ), 'type' => array( 'type' => 'string', ), 'status' => array( 'type' => 'string', ), 'date' => array( 'type' => 'string', ), 'has_featured_image' => array( 'type' => 'boolean', ), 'edit_url' => array( 'type' => 'string', ), ), ), ), ), ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_find_posts'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'get-usage', array( 'label' => __( 'Get usage', 'ai-featured-image-generator' ), 'description' => __( 'How many AI-assistant images this site has used and how many remain on the Free plan. Also the quick, free way to test the connection to this site.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'default' => new \stdClass(), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'is_pro' => array( 'type' => 'boolean', ), 'limit' => array( 'type' => array('integer', 'null'), ), 'used' => array( 'type' => 'integer', ), 'remaining' => array( 'type' => array('integer', 'null'), ), ), ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_get_usage'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'list-posts-missing-image', array( 'label' => __( 'List posts missing a featured image', 'ai-featured-image-generator' ), 'description' => __( 'Find posts or pages that have no featured image yet.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'default' => new \stdClass(), 'properties' => array( 'post_type' => array( 'type' => 'string', 'default' => 'post', ), 'status' => array( 'type' => 'string', 'enum' => array( 'any', 'publish', 'draft', 'pending', 'future', 'private' ), 'default' => 'any', ), 'category' => $category_schema, 'tag' => $tag_schema, 'author' => $author_schema, 'limit' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 50, 'default' => 20, ), 'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'posts' => array( 'type' => 'array', ), 'total' => array( 'type' => 'integer', ), 'total_pages' => array( 'type' => 'integer', ), 'page' => array( 'type' => 'integer', ), ), ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_list_posts_missing_image'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'get-post', array( 'label' => __( 'Get post', 'ai-featured-image-generator' ), 'description' => __( 'Read a post title, short excerpt and featured image status, useful for writing a better image prompt.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('post_id'), 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_edit_post'), 'execute_callback' => array($this, 'execute_get_post'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'set-featured-image', array( 'label' => __( 'Set featured image', 'ai-featured-image-generator' ), 'description' => __( 'Use an existing Media Library image as the featured image of a post. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('post_id', 'attachment_id'), 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), 'attachment_id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_edit_post'), 'execute_callback' => array($this, 'execute_set_featured_image'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => true, ) ), ) ); $this->register( 'insert-image-into-post', array( 'label' => __( 'Insert image into post', 'ai-featured-image-generator' ), 'description' => __( 'Add an image block to a post, at the top, at the bottom, or after a given paragraph. It only adds an image block. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('post_id', 'attachment_id'), 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), 'attachment_id' => array( 'type' => 'integer', 'minimum' => 1, ), 'placement' => array( 'type' => 'string', 'enum' => array('top', 'bottom', 'after_paragraph'), 'default' => 'top', ), 'paragraph_index' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1, 'description' => __( 'Used with after_paragraph. 1 is the first paragraph. Paragraphs inside quotes, groups or columns are not counted.', 'ai-featured-image-generator' ), ), 'alt' => array( 'type' => 'string', ), 'caption' => array( 'type' => 'string', ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_edit_post'), 'execute_callback' => array($this, 'execute_insert_image_into_post'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => false, 'idempotent' => false, ) ), ) ); $this->register( 'remove-background', array( 'label' => __( 'Remove background', 'ai-featured-image-generator' ), 'description' => __( 'Remove the background from the featured image of a post with OpenAI GPT Image 2.6 and replace it. The picture is redrawn on a transparent background, so small details can change. Costs one image. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('post_id'), 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ), 'output_schema' => $image_output, 'permission_callback' => array($this, 'can_change_post_media'), 'execute_callback' => array($this, 'execute_remove_background'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => false, ) ), ) ); $this->register( 'generate-audio', array( 'label' => __( 'Generate post audio', 'ai-featured-image-generator' ), 'description' => __( 'Turn a post into a narrated recording with the voice chosen on the Audio tab, and show a "Listen to this post" player above its content. Costs depend on the provider and the post length. If the post already has an up-to-date recording it is returned as is, unless regenerate is true. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('post_id'), 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), 'regenerate' => array( 'type' => 'boolean', 'default' => false, 'description' => __( 'Make a new recording even when the current one still matches the post.', 'ai-featured-image-generator' ), ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_change_post_media'), 'execute_callback' => array($this, 'execute_generate_audio'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => false, ) ), ) ); $this->register( 'generate-product-image', array( 'label' => __( 'Generate product image', 'ai-featured-image-generator' ), 'description' => __( 'Make store images for a WooCommerce product from its real photo (type of shot: studio, showroom, lifestyle or 3D; mood; white, grey, beige, custom or transparent background for studio and 3D shots). The product itself is kept exactly as it is. Shows the result for approval by default: the product only changes when apply is main or gallery. Each image costs one generation. For more than 10 products, do not preview one by one: use apply main or gallery when the user asked to change the products, otherwise tell the user to use Bulk images on the Product Images tab (Match photos to your style remakes only the photos that differ). Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('product_id'), 'additionalProperties' => false, 'properties' => array( 'product_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'ID of the WooCommerce product.', 'ai-featured-image-generator' ), ), 'attachment_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'Photo to start from. Defaults to the main image, then the first gallery image.', 'ai-featured-image-generator' ), ), 'mode' => array( 'type' => 'string', 'enum' => Product_Images::MODES, 'description' => __( 'Type of shot. For lifestyle, the setting is chosen to suit the product unless extra_prompt names one.', 'ai-featured-image-generator' ), ), 'background' => array( 'type' => 'string', 'enum' => Product_Images::BACKGROUNDS, 'description' => __( 'Used for studio and 3D shots only.', 'ai-featured-image-generator' ), ), 'background_hex' => array( 'type' => 'string', 'pattern' => '^#[0-9a-fA-F]{6}$', 'description' => __( 'Colour for a custom background, such as #f4f4f4.', 'ai-featured-image-generator' ), ), 'style' => array( 'type' => 'string', 'enum' => Product_Images::STYLES, 'description' => __( 'Mood: clean_studio is Clean, natural_light is Soft daylight.', 'ai-featured-image-generator' ), ), 'extra_prompt' => array( 'type' => 'string', 'maxLength' => 300, 'description' => __( 'Optional extra words for this request, such as "on a beach towel at sunset".', 'ai-featured-image-generator' ), ), 'count' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => Product_Images::SET_MAX, 'default' => 1, 'description' => __( 'Images to make. More than one makes a product set: a studio main image plus gallery images in the shot types from the settings.', 'ai-featured-image-generator' ), ), 'apply' => array( 'type' => 'string', 'enum' => array('preview', 'main', 'gallery'), 'default' => 'preview', 'description' => __( 'preview (default) changes nothing; main makes the first image the main image and adds the rest to the gallery; gallery adds them all to the gallery.', 'ai-featured-image-generator' ), ), ), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'images' => array( 'type' => 'array', ), 'product_id' => array( 'type' => 'integer', ), 'main_id' => array( 'type' => 'integer', ), 'gallery_ids' => array( 'type' => 'array', 'items' => array( 'type' => 'integer', ), ), 'applied' => array( 'type' => 'string', ), 'notes' => array( 'type' => 'array', 'items' => array( 'type' => 'string', ), ), ), ), 'permission_callback' => array($this, 'can_edit_product'), 'execute_callback' => array($this, 'execute_generate_product_image'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => false, ) ), ) ); $this->register( 'audit-product-images', array( 'label' => __( 'Audit product images', 'ai-featured-image-generator' ), 'description' => __( 'Check WooCommerce product images against the Product Images style: which backgrounds, shapes, sizes or formats differ. Reads only, makes nothing, costs nothing. Pages of up to 20 products. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'filter' => array( 'type' => 'string', 'enum' => array('all', 'category', 'no_main'), 'default' => 'all', 'description' => __( 'all, category (with category), or no_main: products that have photos but no main image.', 'ai-featured-image-generator' ), ), 'category' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'Product category ID, for filter category.', 'ai-featured-image-generator' ), ), 'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1, ), 'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 20, 'default' => 20, ), ), 'default' => new \stdClass(), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'summary' => array( 'type' => 'object', ), 'rows' => array( 'type' => 'array', ), 'total' => array( 'type' => 'integer', ), 'pages' => array( 'type' => 'integer', ), ), ), 'permission_callback' => array($this, 'can_manage_shop'), 'execute_callback' => array($this, 'execute_audit_product_images'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'find-media', array( 'label' => __( 'Find media', 'ai-featured-image-generator' ), 'description' => __( 'Search images in the Media Library by name, to get an attachment ID for the logo, reference or featured image tools.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('search'), 'additionalProperties' => false, 'properties' => array( 'search' => array( 'type' => 'string', 'description' => __( 'Part of the image title or file name.', 'ai-featured-image-generator' ), ), 'limit' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 20, 'default' => 10, ), ), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'images' => array( 'type' => 'array', ), ), ), 'permission_callback' => array($this, 'can_generate'), 'execute_callback' => array($this, 'execute_find_media'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'list-posts', array( 'label' => __( 'List posts', 'ai-featured-image-generator' ), 'description' => __( 'List posts or pages with filters: category, tag, date range, featured image yes or no, and images made before the Brand Kit last changed. Use it to work through a whole category.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'default' => new \stdClass(), 'properties' => array( 'search' => array( 'type' => 'string', ), 'post_type' => array( 'type' => 'string', 'default' => 'post', 'description' => __( 'post, page, or any.', 'ai-featured-image-generator' ), ), 'status' => array( 'type' => 'string', 'enum' => array( 'any', 'publish', 'draft', 'pending', 'future', 'private' ), 'default' => 'any', ), 'category' => $category_schema, 'tag' => $tag_schema, 'author' => $author_schema, 'after' => array( 'type' => 'string', 'pattern' => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$', 'description' => __( 'Only posts published on or after this date, YYYY-MM-DD.', 'ai-featured-image-generator' ), ), 'before' => array( 'type' => 'string', 'pattern' => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$', 'description' => __( 'Only posts published on or before this date, YYYY-MM-DD.', 'ai-featured-image-generator' ), ), 'has_featured_image' => array( 'type' => 'string', 'enum' => array('any', 'yes', 'no'), 'default' => 'any', ), 'image_older_than_brand_kit' => array( 'type' => 'boolean', 'default' => false, 'description' => __( 'Only posts whose featured image was made before the Brand Kit last changed, so they may need a refresh.', 'ai-featured-image-generator' ), ), 'limit' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 50, 'default' => 20, ), 'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'posts' => array( 'type' => 'array', ), 'total' => array( 'type' => 'integer', ), 'total_pages' => array( 'type' => 'integer', ), 'page' => array( 'type' => 'integer', ), ), ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_list_posts'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $kit_output = array( 'type' => 'object', ); $this->register( 'get-brand-kit', array( 'label' => __( 'Get Brand Kit', 'ai-featured-image-generator' ), 'description' => __( 'Show the Brand Kit: whether it is on, colours, tone, description, things to avoid, the reference image, and the logo with its placement. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'default' => new \stdClass(), ), 'output_schema' => $kit_output, 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_get_brand_kit'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'update-brand-kit', array( 'label' => __( 'Update Brand Kit', 'ai-featured-image-generator' ), 'description' => __( 'Change the Brand Kit: turn it on or off, set up to 3 colours, the tone, the description, things to avoid, or the reference image. Only the fields given change. Reports every change so it can be undone. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'enabled' => array( 'type' => 'boolean', 'description' => __( 'Apply the Brand Kit to new images by default.', 'ai-featured-image-generator' ), ), 'colors' => array( 'type' => 'array', 'maxItems' => 3, 'items' => array( 'type' => 'string', 'pattern' => '^#([A-Fa-f0-9]{3}){1,2}$', ), 'description' => __( 'Up to 3 hex colours such as #1a2b3c. An empty list clears them.', 'ai-featured-image-generator' ), ), 'tone' => array( 'type' => 'string', 'description' => __( 'A few words, such as warm and friendly.', 'ai-featured-image-generator' ), ), 'description' => array( 'type' => 'string', 'description' => __( 'One or two sentences about the brand and its look.', 'ai-featured-image-generator' ), ), 'avoid' => array( 'type' => 'string', 'description' => __( 'Comma-separated things to keep out of images.', 'ai-featured-image-generator' ), ), 'reference_id' => array( 'type' => 'integer', 'minimum' => 0, 'description' => __( 'Media Library image whose style new images should follow. 0 removes it. Use find-media to get the ID.', 'ai-featured-image-generator' ), ), ), ), 'output_schema' => $kit_output, 'permission_callback' => array($this, 'can_manage_brand'), 'execute_callback' => array($this, 'execute_update_brand_kit'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => true, ) ), ) ); $this->register( 'set-brand-logo', array( 'label' => __( 'Set brand logo', 'ai-featured-image-generator' ), 'description' => __( 'Choose the Brand Kit logo from the Media Library and place it: corner or centre, size, opacity, margin and nudge. Only the fields given change. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'logo_id' => array( 'type' => 'integer', 'minimum' => 0, 'description' => __( 'Media Library image to use as the logo, ideally a PNG with a transparent background. 0 removes the logo. Use find-media to get the ID.', 'ai-featured-image-generator' ), ), 'position' => array( 'type' => 'string', 'enum' => array( 'top-left', 'top-right', 'bottom-left', 'bottom-right', 'center' ), ), 'size' => array( 'type' => 'integer', 'minimum' => 5, 'maximum' => 40, 'description' => __( 'Logo width as a percentage of the shorter image side. 15 is the default.', 'ai-featured-image-generator' ), ), 'opacity' => array( 'type' => 'integer', 'minimum' => 10, 'maximum' => 100, ), 'margin' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 100, 'description' => __( 'Distance from the edges, for corner positions. 20 is the default.', 'ai-featured-image-generator' ), ), 'offset_x' => array( 'type' => 'integer', 'minimum' => -100, 'maximum' => 100, 'description' => __( 'Nudge right (positive) or left (negative).', 'ai-featured-image-generator' ), ), 'offset_y' => array( 'type' => 'integer', 'minimum' => -100, 'maximum' => 100, 'description' => __( 'Nudge down (positive) or up (negative).', 'ai-featured-image-generator' ), ), ), ), 'output_schema' => $kit_output, 'permission_callback' => array($this, 'can_manage_brand'), 'execute_callback' => array($this, 'execute_set_brand_logo'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => true, ) ), ) ); $this->register( 'preview-brand-kit', array( 'label' => __( 'Preview Brand Kit', 'ai-featured-image-generator' ), 'description' => __( 'Make one test image with the current Brand Kit, including the logo, and save it to the Media Library so the result can be checked before using it on posts. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'default' => new \stdClass(), 'properties' => array( 'prompt' => array( 'type' => 'string', 'description' => __( 'What the test image should show. Defaults to a simple scene in the brand style.', 'ai-featured-image-generator' ), ), 'aspect_ratio' => array( 'type' => 'string', 'pattern' => '^[0-9]{1,2}:[0-9]{1,2}$', 'default' => '1:1', ), ), ), 'output_schema' => $image_output, 'permission_callback' => array($this, 'can_generate'), 'execute_callback' => array($this, 'execute_preview_brand_kit'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => false, 'idempotent' => false, ) ), ) ); $this->register( 'apply-brand-logo', array( 'label' => __( 'Apply brand logo', 'ai-featured-image-generator' ), 'description' => __( 'Stamp the Brand Kit logo onto the featured image a post already has. No AI call, no cost. The original image stays in the Media Library and remove-brand-logo puts it back. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('post_id'), 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_change_post_media'), 'execute_callback' => array($this, 'execute_apply_brand_logo'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => false, ) ), ) ); $this->register( 'remove-brand-logo', array( 'label' => __( 'Remove brand logo', 'ai-featured-image-generator' ), 'description' => __( 'Undo apply-brand-logo on a post: put back the featured image it had before the logo was added. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('post_id'), 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_edit_post'), 'execute_callback' => array($this, 'execute_remove_brand_logo'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => true, ) ), ) ); $this->register( 'suggest-brand-kit', array( 'label' => __( 'Suggest Brand Kit', 'ai-featured-image-generator' ), 'description' => __( 'Collect what the site says about itself: name, tagline, theme colours, site logo and icon, recent posts, and the current Brand Kit. Use it to propose colours, a tone and a description, then save them with update-brand-kit after the user agrees. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'default' => new \stdClass(), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_manage_brand'), 'execute_callback' => array($this, 'execute_suggest_brand_kit'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'audit-images', array( 'label' => __( 'Audit images', 'ai-featured-image-generator' ), 'description' => __( 'Scan featured images and the images inside posts, or the whole Media Library, with filters: missing alt text, format (jpg, png, webp, gif, avif), shape (1:1, 16:9 and so on), pixel size and file size. Returns counts by format and shape plus the matching images and their posts. Use it for questions like "count my 1:1 images" or "which pages have JPG images without alt text".', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'default' => new \stdClass(), 'properties' => array( 'scope' => array( 'type' => 'string', 'enum' => array('posts', 'library'), 'default' => 'posts', 'description' => __( 'posts: images used by posts (featured and in the content). library: every image in the Media Library.', 'ai-featured-image-generator' ), ), 'post_type' => array( 'type' => 'string', 'default' => 'any', 'description' => __( 'post, page, any, or another enabled type. Posts scope only.', 'ai-featured-image-generator' ), ), 'status' => array( 'type' => 'string', 'enum' => array( 'any', 'publish', 'draft', 'pending', 'future', 'private' ), 'default' => 'any', ), 'category' => $category_schema, 'tag' => $tag_schema, 'author' => array( 'type' => 'string', 'description' => __( 'Posts scope: only posts by this author. Library scope: only images uploaded by this user. Display name, username or email.', 'ai-featured-image-generator' ), ), 'location' => array( 'type' => 'string', 'enum' => array('any', 'featured', 'content'), 'default' => 'any', 'description' => __( 'Only featured images, only images inside the content, or both.', 'ai-featured-image-generator' ), ), 'missing_alt' => array( 'type' => 'boolean', 'description' => __( 'true: only images with no alt text. false: only images that have alt text. Leave out for both.', 'ai-featured-image-generator' ), ), 'format' => array( 'type' => 'string', 'enum' => array( 'jpg', 'png', 'webp', 'gif', 'avif', 'svg' ), 'description' => __( 'Only images in this format.', 'ai-featured-image-generator' ), ), 'aspect_ratio' => array( 'type' => 'string', 'pattern' => '^[0-9]{1,2}:[0-9]{1,2}$', 'description' => __( 'Only images of this shape, within 2 percent, such as 1:1 or 16:9.', 'ai-featured-image-generator' ), ), 'min_width' => array( 'type' => 'integer', 'minimum' => 1, ), 'max_width' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'Only images this wide or narrower, in pixels. Useful for finding small images.', 'ai-featured-image-generator' ), ), 'min_kb' => array( 'type' => 'integer', 'minimum' => 1, ), 'max_kb' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'Only files this size or smaller, in kilobytes.', 'ai-featured-image-generator' ), ), 'uploaded_after' => array( 'type' => 'string', 'pattern' => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$', 'description' => __( 'Only images added to the Media Library on or after this date, YYYY-MM-DD.', 'ai-featured-image-generator' ), ), 'uploaded_before' => array( 'type' => 'string', 'pattern' => '^[0-9]{4}-[0-9]{2}-[0-9]{2}$', 'description' => __( 'Only images added on or before this date, YYYY-MM-DD.', 'ai-featured-image-generator' ), ), 'quality' => array( 'type' => 'string', 'enum' => array('blurry', 'low_quality', 'cut_off'), 'description' => __( 'Measure each image and keep only: blurry (soft focus), low_quality (blurry, soft, or narrower than 800 px), or cut_off (detail runs into an edge, so something may be cropped). Measuring takes time, so each call checks up to 100 images; use page for the next 100.', 'ai-featured-image-generator' ), ), 'limit' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 50, 'description' => __( 'How many matching images to list. The counts always cover everything scanned.', 'ai-featured-image-generator' ), ), 'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_audit_images'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'inspect-image', array( 'label' => __( 'Inspect image', 'ai-featured-image-generator' ), 'description' => __( 'Measure one image: pixel size, shape, format, file size, alt text, where it is used, a sharpness score (blurry, soft or sharp) and edge checks that hint at cut-off content or empty borders. Use view-image afterwards to look at it.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'attachment_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'The image. Or give post_id to inspect that post\'s featured image.', 'ai-featured-image-generator' ), ), 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_inspect_image'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ) ), ) ); $this->register( 'view-image', array( 'label' => __( 'View image', 'ai-featured-image-generator' ), 'description' => __( 'Show an image to the user and to yourself. Use it right after making or changing an image so the user sees the result, whenever the user asks to see an image, and to judge quality, framing and cut-off edges. Returns a preview picture.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'attachment_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'The image. Or give post_id to view that post\'s featured image.', 'ai-featured-image-generator' ), ), 'post_id' => array( 'type' => 'integer', 'minimum' => 1, ), 'max_size' => array( 'type' => 'integer', 'minimum' => 256, 'maximum' => 1600, 'default' => 1024, 'description' => __( 'Longest side of the preview in pixels.', 'ai-featured-image-generator' ), ), ), ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_view_image'), 'meta' => $this->meta( array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ), array( 'show_in_rest' => false, ) ), ) ); $this->register( 'update-image', array( 'label' => __( 'Update image', 'ai-featured-image-generator' ), 'description' => __( 'Change an image in the Media Library: title, alt text, caption, description, or file name. A new file name makes a renamed copy and points every post that used the image at the copy, so no link breaks; the old file stays until deleted. Only the fields given change. Changing the file name is Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('attachment_id'), 'additionalProperties' => false, 'properties' => array( 'attachment_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'The image. Use find-media or audit-images to get the ID.', 'ai-featured-image-generator' ), ), 'title' => array( 'type' => 'string', ), 'alt' => array( 'type' => 'string', 'description' => __( 'Alt text. An empty string clears it.', 'ai-featured-image-generator' ), ), 'caption' => array( 'type' => 'string', ), 'description' => array( 'type' => 'string', ), 'filename' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 120, 'description' => __( 'New file name without the extension, such as summer-recipes-hero. The format stays the same.', 'ai-featured-image-generator' ), ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_edit_attachment'), 'execute_callback' => array($this, 'execute_update_image'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => false, ) ), ) ); $this->register( 'convert-image', array( 'label' => __( 'Convert image to WebP', 'ai-featured-image-generator' ), 'description' => __( 'Make a WebP copy of a JPG or PNG image and point every post that used it at the copy, so pages load faster and no link breaks. The original stays until deleted. No AI call, no cost. Use audit-images with format jpg or png to find candidates. Pro.', 'ai-featured-image-generator' ), 'input_schema' => array( 'type' => 'object', 'required' => array('attachment_id'), 'additionalProperties' => false, 'properties' => array( 'attachment_id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ), 'output_schema' => array( 'type' => 'object', ), 'permission_callback' => array($this, 'can_edit_attachment'), 'execute_callback' => array($this, 'execute_convert_image'), 'meta' => $this->meta( array( 'readonly' => false, 'destructive' => true, 'idempotent' => false, ) ), ) ); } /** * @param string $name Ability name without prefix. * @param array $args Ability arguments. */ private function register( $name, $args ) { $args['category'] = self::CATEGORY; // Every tool names the site, so an assistant connected to several sites // (or to other image tools) knows which one a request is about. if ( isset( $args['description'] ) ) { $args['description'] = sprintf( /* translators: 1: site name, 2: tool description */ __( 'On %1$s: %2$s', 'ai-featured-image-generator' ), self::site_label(), $args['description'] ); } if ( isset( $args['execute_callback'] ) ) { $callback = $args['execute_callback']; $args['execute_callback'] = function ( $input = array() ) use($callback) { self::note_connection(); return call_user_func( $callback, $input ); }; } wp_register_ability( self::CATEGORY . '/' . $name, $args ); } /** * Whether the current request came in through the MCP server route. * * @return bool */ public static function is_mcp_request() { // The adapter serves every server under the "mcp" REST namespace. The plugin's own // routes (aifi/v1/mcp/status and so on) live elsewhere and must not count. $route = ( isset( $GLOBALS['wp']->query_vars['rest_route'] ) ? (string) $GLOBALS['wp']->query_vars['rest_route'] : '' ); if ( $route === '' && isset( $_SERVER['REQUEST_URI'] ) ) { $path = (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized $route = preg_replace( '#^.*?/' . preg_quote( rest_get_url_prefix(), '#' ) . '#', '', $path ); } return (bool) preg_match( '#^/mcp/#', $route ); } /** * Remember that an assistant reached the site. Any tool call counts, so the * check in the settings tab can be a free one such as get-usage. */ public static function note_connection() { if ( !self::is_mcp_request() ) { return; } update_option( self::CONNECTED_OPTION, time() ); } /** * @return int Unix time of the last assistant call, 0 if none yet. */ public static function connected_at() { return (int) get_option( self::CONNECTED_OPTION, 0 ); } /** * Site name shown to assistants, falling back to the host. * * @return string */ public static function site_label() { $name = trim( wp_strip_all_tags( get_bloginfo( 'name' ) ) ); if ( $name === '' ) { $name = (string) wp_parse_url( home_url(), PHP_URL_HOST ); } return $name; } /** * Short, safe name for this site, used in assistant configs: "aifig-". * Lets several sites sit side by side in one config file. * * @return string */ public static function connection_name() { $slug = sanitize_title( get_bloginfo( 'name' ) ); if ( $slug === '' ) { $slug = sanitize_title( (string) wp_parse_url( home_url(), PHP_URL_HOST ) ); } // Avoid "aifig-aifig-blog" when the site name already starts with it. $slug = preg_replace( '/^aifig-?/', '', $slug ); $slug = substr( trim( $slug, '-' ), 0, 30 ); return 'aifig' . (( $slug !== '' ? '-' . rtrim( $slug, '-' ) : '' )); } /** * The "go" command: a free-text request wrapped in enough context that the * assistant uses this site's tools and nothing else. Shown as /:go in * Claude Code and Cursor, and in the + menu in Claude Desktop. */ private function register_go_prompt() { wp_register_ability( self::CATEGORY . '/go', array( 'label' => __( 'Go', 'ai-featured-image-generator' ), 'description' => sprintf( /* translators: %s: site name */ __( 'Ask for any image work on %s in plain words.', 'ai-featured-image-generator' ), self::site_label() ), 'category' => self::CATEGORY, 'input_schema' => array( 'type' => 'object', 'properties' => array( 'request' => array( 'type' => 'string', 'description' => __( 'What you want, in plain words. For example: a featured image for my latest post.', 'ai-featured-image-generator' ), ), ), 'required' => array('request'), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'text' => array( 'type' => 'string', ), ), ), 'permission_callback' => array($this, 'can_read'), 'execute_callback' => array($this, 'execute_go'), 'meta' => array( 'public' => true, 'mcp' => array( 'public' => true, 'type' => 'prompt', ), ), ) ); } /** * @param array $input Prompt arguments. * @return array */ public function execute_go( $input ) { $request = ( isset( $input['request'] ) ? trim( (string) $input['request'] ) : '' ); $text = sprintf( /* translators: 1: site name, 2: site URL, 3: the user's request */ __( 'Work on the WordPress site "%1$s" (%2$s) using only its aifi tools. Request: %3$s.', 'ai-featured-image-generator' ), self::site_label(), home_url(), ( $request !== '' ? $request : __( 'make a featured image for my latest post', 'ai-featured-image-generator' ) ) ); $text .= ' ' . __( 'If a post is named, use find-posts to get its ID first. Keep the Brand Kit on unless told otherwise. When done, say what changed and give the image link.', 'ai-featured-image-generator' ); return array( 'text' => $text, ); } /** * Show the command as "go" instead of "aifi-go". * * @param string $name Sanitized prompt name. * @param \WP_Ability $ability Ability. * @return string */ public function prompt_name( $name, $ability ) { return ( $ability instanceof \WP_Ability && $ability->get_name() === self::CATEGORY . '/go' ? 'go' : $name ); } /** * Shared meta: visible to the Abilities REST API and exposed through MCP. * * @param array $annotations readonly / destructive / idempotent flags. * @param array $extra More meta keys, such as show_in_rest. * @return array */ private function meta( $annotations, $extra = array() ) { return array_merge( array( 'public' => true, 'mcp' => array( 'public' => true, 'type' => 'tool', ), 'annotations' => $annotations, ), $extra ); } /** * Attach our tools to a dedicated server on the MCP Adapter. * * @param \WP\MCP\Core\McpAdapter $adapter Adapter instance. */ public function register_mcp_server( $adapter ) { if ( !self::is_adapter_active() || !class_exists( '\\WP\\MCP\\Transport\\HttpTransport' ) ) { return; } $error_handler = ( class_exists( '\\WP\\MCP\\Infrastructure\\ErrorHandling\\ErrorLogMcpErrorHandler' ) ? '\\WP\\MCP\\Infrastructure\\ErrorHandling\\ErrorLogMcpErrorHandler' : null ); $observability = ( class_exists( '\\WP\\MCP\\Infrastructure\\Observability\\NullMcpObservabilityHandler' ) ? '\\WP\\MCP\\Infrastructure\\Observability\\NullMcpObservabilityHandler' : null ); try { $adapter->create_server( self::SERVER_ID, 'mcp', self::SERVER_ROUTE, sprintf( /* translators: %s: site name */ __( 'AI Images for %s', 'ai-featured-image-generator' ), self::site_label() ), sprintf( /* translators: 1: site name, 2: site URL */ __( 'Generate AI featured images and inline images on the WordPress site %1$s (%2$s). After you make or change an image, show it to the user with view-image.', 'ai-featured-image-generator' ), self::site_label(), home_url() ), AIFI_VERSION, array('\\WP\\MCP\\Transport\\HttpTransport'), $error_handler, $observability, $this->get_tool_names(), array(), array(self::CATEGORY . '/go'), function () { return is_user_logged_in() && current_user_can( 'edit_posts' ); } ); } catch ( \Throwable $e ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( 'AIFI: could not register MCP server: ' . $e->getMessage() ); } } } /* --------------------------------------------------------------------- * Permission callbacks * * These only answer "may this user call the tool at all". WordPress core * replaces any error returned here with a generic "no permission" message, * so every message an assistant should repeat (Free limit, Pro upgrade, * missing or trashed post, post type not enabled) is returned from the * execute callbacks instead. * ------------------------------------------------------------------ */ public function can_read() { return current_user_can( 'edit_posts' ); } public function can_generate() { return current_user_can( 'upload_files' ); } public function can_generate_for_post( $input ) { return $this->can_change_post_media( $input ); } /** * Tools that add an image or audio file to the Media Library or spend the site's * credits for a post: edit rights on the post and the right to upload files, the same * as the editor routes (a Contributor cannot). * * @param array $input Ability input. * @return bool */ public function can_change_post_media( $input ) { return current_user_can( 'upload_files' ) && $this->can_edit_post( $input ); } /** * The user may edit the attachment. Like can_edit_post: a missing ID is * reported by the execute callback with a clear message. * * @param array $input Ability input. * @return bool */ public function can_edit_attachment( $input ) { $id = ( isset( $input['attachment_id'] ) ? absint( $input['attachment_id'] ) : 0 ); if ( !$id || !get_post( $id ) ) { return current_user_can( 'edit_posts' ); } return current_user_can( 'edit_post', $id ); } /** * Changing the Brand Kit changes every future image, so it takes the same * right as the settings page. */ public function can_manage_brand() { // On multisite the settings, and so the kit, are shared by the whole network. return current_user_can( ( is_multisite() ? 'manage_network_options' : 'manage_options' ) ); } /** * The user may edit the post. When the post does not exist the execute * callback reports it, so here we only require a user who edits posts. * * @param array $input Ability input. * @return bool */ /** * Product tools: edit rights on that product. An ID that belongs to another post * type never passes, so edit rights on a post cannot reach a product tool. * * @param array $input Ability input. * @return bool */ public function can_edit_product( $input ) { $id = ( isset( $input['product_id'] ) ? absint( $input['product_id'] ) : 0 ); $post = ( $id ? get_post( $id ) : null ); if ( !$post ) { return current_user_can( 'edit_products' ) || current_user_can( 'edit_posts' ); } if ( 'product' !== $post->post_type ) { return false; } return current_user_can( 'edit_post', $id ); } /** * Shop-wide product tools: Shop Managers and administrators. * * @return bool */ public function can_manage_shop() { return current_user_can( 'manage_woocommerce' ) || current_user_can( 'manage_options' ); } public function can_edit_post( $input ) { $post_id = ( isset( $input['post_id'] ) ? absint( $input['post_id'] ) : 0 ); if ( !$post_id || !get_post( $post_id ) ) { return current_user_can( 'edit_posts' ); } return current_user_can( 'edit_post', $post_id ); } /** * Load the post a per-post tool works on, with the same rules as the editor * REST endpoint: it exists, is a real saved post (not in the Trash), and its * post type is enabled for image generation. Edit rights are checked by the * permission callback. Read-only tools skip the enabled post type rule: finding * is allowed on every post type the admin shows, as in list_posts(). * * @param array $input Ability input. * @param bool $read_only True for tools that only look. * @return \WP_Post|\WP_Error */ private function get_target_post( $input, $read_only = false ) { $post_id = ( isset( $input['post_id'] ) ? absint( $input['post_id'] ) : 0 ); $post = ( $post_id ? get_post( $post_id ) : null ); if ( !$post ) { return new \WP_Error('invalid_post', __( 'No post with that ID exists.', 'ai-featured-image-generator' ), array( 'status' => 404, )); } if ( !current_user_can( 'edit_post', $post->ID ) ) { return new \WP_Error('rest_forbidden', __( 'You are not allowed to edit this post.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } if ( 'trash' === $post->post_status ) { return new \WP_Error('post_in_trash', __( 'This post is in the Trash. Restore it first, then try again.', 'ai-featured-image-generator' ), array( 'status' => 409, )); } if ( 'auto-draft' === $post->post_status ) { return new \WP_Error('post_not_saved', __( 'This post has not been saved yet. Save it as a draft first, then try again.', 'ai-featured-image-generator' ), array( 'status' => 409, )); } if ( $read_only ) { // Same rule as list_posts(): only types the admin shows, never attachments or // internal records such as privacy requests. $object = get_post_type_object( $post->post_type ); if ( !$object || !$object->show_ui || 'attachment' === $post->post_type ) { return new \WP_Error('invalid_post_type', __( 'That ID is not a post or page this tool can read.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } } if ( !$read_only && !in_array( $post->post_type, $this->settings->get_content_post_types(), true ) ) { return new \WP_Error('post_type_not_enabled', sprintf( /* translators: %s: post type */ __( 'AI images are not enabled for the "%s" post type. Enable it in AI Images > General.', 'ai-featured-image-generator' ), $post->post_type ), array( 'status' => 403, )); } return $post; } /** * Refusal for the featured image tools on a product. Product Images records the * originals before it changes a product, so Restore can go back; these tools do not. * * @param \WP_Post $post Target post. * @return \WP_Error|null Null when the post is not a product. */ private function product_refusal( $post ) { if ( 'product' !== $post->post_type ) { return null; } return new \WP_Error('product_use_product_tool', sprintf( /* translators: %d: product ID */ __( 'This tool does not change product images, because Restore could not undo it. Use generate-product-image for product %d.', 'ai-featured-image-generator' ), $post->ID ), array( 'status' => 400, )); } /** * Upgrade message for the Pro tools, used both on Pro builds without a license * and on the Free build where the tool code is not included. * * @return \WP_Error */ private function pro_tool_error() { return $this->premium_error( __( 'This tool', 'ai-featured-image-generator' ) ); } /* --------------------------------------------------------------------- * Execute callbacks * ------------------------------------------------------------------ */ /** * Turn provider/model inputs into validated runtime overrides. * * @param array $input Ability input. * @return array|\WP_Error Overrides array (possibly empty). */ private function resolve_overrides( $input ) { $overrides = array(); $settings = $this->settings->get_settings(); $provider = ( isset( $input['provider'] ) && $input['provider'] !== '' ? $input['provider'] : $settings['ai_provider'] ?? 'openai' ); if ( !Providers::is_registered( $provider ) ) { return new \WP_Error('invalid_provider', __( 'Unknown provider.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } if ( !Providers::is_available( $provider ) ) { return $this->require_pro( Providers::label( $provider ) ); } if ( !Providers::has_api_key( $settings, $provider ) ) { return new \WP_Error('no_api_key', sprintf( /* translators: %s: provider name */ __( 'No API key is set for %s. Add one in AI Images > General.', 'ai-featured-image-generator' ), Providers::label( $provider ) ), array( 'status' => 400, )); } if ( !empty( $input['provider'] ) ) { $overrides['ai_provider'] = $provider; // A provider switch needs a matching model unless one was given. if ( empty( $input['model'] ) && $provider !== ($settings['ai_provider'] ?? 'openai') ) { $overrides['ai_model'] = Providers::default_model( $provider ); } } if ( !empty( $input['model'] ) ) { // A real model of this provider that only Pro may use gets the upgrade message. $all_models = Providers::image_models( $provider ); if ( !$this->is_pro() && isset( $all_models[$input['model']] ) && !Providers::is_model_available( $provider, $input['model'] ) ) { return new \WP_Error('premium_required', sprintf( /* translators: 1: model name, 2: model names the Free plan can use, 3: upgrade URL */ __( '%1$s is a Pro model of AI Featured Image Generator, so it did not run. On Free you can use %2$s instead. Tell the user, and give them this upgrade link: %3$s', 'ai-featured-image-generator' ), $all_models[$input['model']], implode( ', ', Providers::image_models( $provider, true ) ), $this->upgrade_url() ), array( 'status' => 403, 'upgrade_url' => $this->upgrade_url(), )); } if ( !Providers::is_model_available( $provider, $input['model'] ) ) { return new \WP_Error('invalid_model', sprintf( /* translators: 1: model, 2: provider */ __( 'The model "%1$s" is not available for %2$s on this site. Call list-providers for the options.', 'ai-featured-image-generator' ), $input['model'], Providers::label( $provider ) ), array( 'status' => 400, )); } $overrides['ai_model'] = $input['model']; } return $overrides; } /** * Aspect ratios a provider can produce. OpenAI and Gemini follow the generator * and settings lists, which are wider than the block picker; the rest use the * same table the block uses. * * @param string $provider Provider slug. * @param string $model Image model, used for OpenAI. * @return string[] Empty when the provider has no ratio list. */ /** * The requested aspect ratio, checked against the provider that will run. * * @param array $input Tool input. * @param array $overrides Resolved provider/model overrides. * @return string|\WP_Error '' when none was asked for. */ private function resolve_aspect_ratio( $input, $overrides ) { $aspect_ratio = ( isset( $input['aspect_ratio'] ) ? trim( (string) $input['aspect_ratio'] ) : '' ); if ( $aspect_ratio === '' ) { return ''; } $settings = $this->settings->get_settings(); $provider = $overrides['ai_provider'] ?? $settings['ai_provider'] ?? 'openai'; $model = $overrides['ai_model'] ?? (( $provider === ($settings['ai_provider'] ?? 'openai') ? $settings['ai_model'] ?? '' : Providers::default_model( $provider ) )); $allowed = self::aspect_ratios_for( $provider, $model ); if ( $allowed && !in_array( $aspect_ratio, $allowed, true ) ) { return new \WP_Error('invalid_aspect_ratio', sprintf( /* translators: 1: provider name, 2: requested aspect ratio, 3: comma-separated list of allowed ratios */ __( '%1$s does not offer %2$s images on this site. Use one of these: %3$s.', 'ai-featured-image-generator' ), Providers::label( $provider ), $aspect_ratio, implode( ', ', $allowed ) ), array( 'status' => 400, 'allowed' => $allowed, )); } return $aspect_ratio; } private static function aspect_ratios_for( $provider, $model = '' ) { if ( Providers::OPENAI === $provider ) { if ( '' === (string) $model ) { $model = Providers::default_model( Providers::OPENAI ); } return ( Settings::is_gpt2_family( $model ) ? array( '1:1', '3:2', '2:3', '16:9', '9:16', '4:3', '3:4', '3:1', '1:3' ) : array( '1:1', '4:3', '3:2', '16:9', '3:4', '2:3', '9:16' ) ); } if ( Providers::GEMINI === $provider ) { return array( '1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9' ); } $table = Blocks::get_provider_aspect_ratios(); if ( empty( $table[$provider] ) ) { return array(); } return array_map( 'strval', array_keys( $table[$provider] ) ); } /** * @param int $attachment_id Attachment. * @param array $overrides Overrides used. * @param bool $brand_wanted Whether the call asked for the Brand Kit. * @return array */ /** * Tell the assistant to show the result. A tool reply carries either data or a picture, * not both, so the picture comes from a view-image call right after. * * @param int $attachment_id Image to show. * @return string */ /** * Overrides for an animated or vector image, after the Pro check. * * @param string $format still, animated or vector. * @param array $input Tool input (frames, frame_ms). * @return array|\WP_Error */ private function extras_overrides( $format, $input ) { if ( 'animated' !== $format && 'vector' !== $format ) { return array(); } if ( !$this->is_pro() ) { return $this->premium_error( ( 'animated' === $format ? __( 'Animated images', 'ai-featured-image-generator' ) : __( 'Vector images', 'ai-featured-image-generator' ) ) ); } if ( 'vector' === $format ) { return array( 'vector' => true, ); } $anim = array(); if ( isset( $input['frames'] ) ) { $anim['frames'] = (int) $input['frames']; } if ( isset( $input['frame_ms'] ) ) { $anim['frame_ms'] = (int) $input['frame_ms']; } return array( 'animated' => ( $anim ? $anim : true ), ); } private function show_hint( $attachment_id ) { return sprintf( /* translators: %d: attachment ID */ __( 'Show this image to the user now: call view-image with attachment_id %d.', 'ai-featured-image-generator' ), (int) $attachment_id ); } private function image_result( $attachment_id, $overrides = array(), $brand_wanted = true ) { $settings = $this->settings->get_settings(); $meta = wp_get_attachment_metadata( $attachment_id ); $branded = $brand_wanted && $this->is_pro() && $this->brand_kit()->is_active(); $out = array( 'attachment_id' => (int) $attachment_id, 'url' => (string) wp_get_attachment_url( $attachment_id ), 'alt' => (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ), 'width' => ( isset( $meta['width'] ) ? (int) $meta['width'] : 0 ), 'height' => ( isset( $meta['height'] ) ? (int) $meta['height'] : 0 ), 'provider' => (string) ($overrides['ai_provider'] ?? $settings['ai_provider'] ?? 'openai'), 'model' => (string) ($overrides['ai_model'] ?? $settings['ai_model'] ?? ''), 'remaining' => self::get_remaining(), 'brand_kit_applied' => $branded, 'show_image' => $this->show_hint( $attachment_id ), ); $anim = get_post_meta( $attachment_id, '_aifi_animated', true ); if ( is_array( $anim ) && !empty( $anim['frames'] ) ) { $out['animated'] = true; $out['frames'] = (int) $anim['frames']; } if ( get_post_meta( $attachment_id, '_aifi_vector', true ) ) { $out['vector'] = true; $out['show_image'] = __( 'This is a vector (SVG) image, which has no preview here. Give the user the URL to open it.', 'ai-featured-image-generator' ); } $notes = $this->generator->get_last_notes(); if ( !empty( $out['animated'] ) ) { $notes[] = sprintf( /* translators: %d: number of frames */ __( 'Up to about %dx the cost of a still image.', 'ai-featured-image-generator' ), $out['frames'] ); } if ( $notes ) { $out['notes'] = array_values( $notes ); } // Without this an assistant tends to call any new image "on brand". if ( !$this->is_pro() ) { $out['note'] = sprintf( /* translators: %s: upgrade URL */ __( 'The Brand Kit was not used, because it is a Pro feature. Do not describe this image as on brand. If the user asked for their brand style, tell them the Brand Kit is Pro and give this link: %s', 'ai-featured-image-generator' ), $this->upgrade_url() ); } return $out; } public function execute_generate_featured_image( $input ) { $post = $this->get_target_post( $input ); if ( is_wp_error( $post ) ) { return $post; } // A product's main image is made from its real photo, never from the title alone. if ( 'product' === $post->post_type ) { return new \WP_Error('product_use_product_tool', sprintf( /* translators: %d: product ID */ __( 'Products use their real photo. Use generate-product-image for product %d.', 'ai-featured-image-generator' ), $post->ID ), array( 'status' => 400, )); } $limit = $this->check_free_limit(); if ( true !== $limit ) { return $limit; } $overrides = $this->resolve_overrides( $input ); if ( is_wp_error( $overrides ) ) { return $overrides; } $aspect_ratio = $this->resolve_aspect_ratio( $input, $overrides ); if ( is_wp_error( $aspect_ratio ) ) { return $aspect_ratio; } if ( $aspect_ratio !== '' ) { $overrides['aspect_ratio'] = $aspect_ratio; } $set_featured = !isset( $input['set_as_featured'] ) || (bool) $input['set_as_featured']; if ( !$set_featured ) { $overrides['skip_featured'] = true; } $extras = $this->extras_overrides( ( !empty( $input['animated'] ) ? 'animated' : 'still' ), $input ); if ( is_wp_error( $extras ) ) { return $extras; } $overrides = array_merge( $overrides, $extras ); // One generation per post at a time, shared with the editor box, the Posts list and // auto-generate on publish, so two paid images are never made for the same post. $lock_key = 'aifi_lock_' . $post->ID; if ( !REST::take_lock( $lock_key, REST::LOCK_TTL ) ) { return new \WP_Error('post_busy', __( 'An image is already being made for this post. Try again in a minute.', 'ai-featured-image-generator' ), array( 'status' => 429, )); } $slot = $this->reserve_slot(); if ( true !== $slot ) { delete_transient( $lock_key ); return $slot; } $use_brand_kit = !isset( $input['use_brand_kit'] ) || (bool) $input['use_brand_kit']; try { $result = $this->generator->generate_image( $post->ID, ( isset( $input['prompt'] ) ? (string) $input['prompt'] : '' ), ( isset( $input['style'] ) ? (string) $input['style'] : '' ), (string) get_post_field( 'post_title', $post->ID ), '', null, $use_brand_kit, $overrides ); } finally { // Released straight away: an assistant may ask again right after, on purpose. delete_transient( $lock_key ); } if ( is_wp_error( $result ) ) { $this->release_slot(); return $result; } $this->tag_free_image( $result ); $out = $this->image_result( $result, $overrides, $use_brand_kit ); $out['set_as_featured'] = $set_featured; $out['edit_url'] = (string) get_edit_post_link( $post->ID, 'raw' ); return $out; } public function execute_generate_image( $input ) { $limit = $this->check_free_limit(); if ( true !== $limit ) { return $limit; } $overrides = $this->resolve_overrides( $input ); if ( is_wp_error( $overrides ) ) { return $overrides; } $aspect_ratio = $this->resolve_aspect_ratio( $input, $overrides ); if ( is_wp_error( $aspect_ratio ) ) { return $aspect_ratio; } $extras = $this->extras_overrides( ( isset( $input['format'] ) ? (string) $input['format'] : 'still' ), $input ); if ( is_wp_error( $extras ) ) { return $extras; } $overrides = array_merge( $overrides, $extras ); // One image per user at a time, the same lock as the AI Image Generator block. $lock_key = 'aifi_block_lock_' . get_current_user_id(); if ( !REST::take_lock( $lock_key, REST::LOCK_TTL ) ) { return new \WP_Error('user_busy', __( 'An image is already being made for you. Try again in a minute.', 'ai-featured-image-generator' ), array( 'status' => 429, )); } $slot = $this->reserve_slot(); if ( true !== $slot ) { delete_transient( $lock_key ); return $slot; } $use_brand_kit = !isset( $input['use_brand_kit'] ) || (bool) $input['use_brand_kit']; try { $result = $this->generator->generate_inline_image( (string) $input['prompt'], ( isset( $input['style'] ) ? (string) $input['style'] : '' ), $aspect_ratio, 0, 1200, '', $use_brand_kit, $overrides ); } finally { delete_transient( $lock_key ); } if ( is_wp_error( $result ) ) { $this->release_slot(); return $result; } $this->tag_free_image( $result['attachment_id'] ); return $this->image_result( $result['attachment_id'], $overrides, $use_brand_kit ); } public function execute_list_providers() { $settings = $this->settings->get_settings(); $active = $settings['ai_provider'] ?? 'openai'; $pro = $this->is_pro(); $list = array(); foreach ( Providers::all() as $slug => $definition ) { $available = Providers::is_available( $slug ); $list[] = array( 'slug' => $slug, 'label' => Providers::label( $slug ), 'pro_only' => (bool) $definition['premium'], 'available' => $available, 'has_key' => $available && Providers::has_api_key( $settings, $slug ), 'active' => $slug === $active, 'models' => array_keys( Providers::image_models( $slug, !$pro ) ), 'aspect_ratios' => self::aspect_ratios_for( $slug, ( $slug === $active ? $settings['ai_model'] ?? '' : Providers::default_model( $slug ) ) ), ); } return array( 'active_provider' => $active, 'active_model' => (string) ($settings['ai_model'] ?? ''), 'providers' => $list, ); } public function execute_find_posts( $input ) { $input = (array) $input; $search = ( isset( $input['search'] ) ? sanitize_text_field( $input['search'] ) : '' ); $type = ( isset( $input['post_type'] ) ? sanitize_key( $input['post_type'] ) : 'any' ); $limit = ( isset( $input['limit'] ) ? max( 1, min( 20, (int) $input['limit'] ) ) : 10 ); if ( $search === '' ) { return new \WP_Error('empty_search', __( 'Give a word or two from the title.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } if ( $type !== 'any' && !post_type_exists( $type ) ) { return new \WP_Error('invalid_post_type', __( 'Unknown post type.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } // Only content the caller may edit, including their own drafts and private posts. // WP_Query's 'perm' => 'editable' only works for a single post type (with several it // hides everything written by others), so fetch extra and check each post instead. $types = ( $type === 'any' ? array_values( array_diff( get_post_types( array( 'show_ui' => true, ) ), array('attachment') ) ) : array($type) ); $args = array( 'post_type' => $types, 'post_status' => array( 'publish', 'future', 'draft', 'pending', 'private' ), 's' => $search, 'posts_per_page' => $limit * 3, 'orderby' => 'relevance', ); $terms = $this->add_term_filters( $input, $args ); if ( is_wp_error( $terms ) ) { return $terms; } $author = $this->resolve_author( $input ); if ( is_wp_error( $author ) ) { return $author; } if ( $author ) { $args['author'] = $author; } $posts = array(); // Posts the caller cannot edit are dropped, so keep reading further pages (at most 10) // until enough editable posts are found or the matches run out. for ($page = 1; $page <= 10 && count( $posts ) < $limit; $page++) { $args['paged'] = $page; $query = new \WP_Query($args); foreach ( $query->posts as $post ) { if ( 'attachment' === $post->post_type || !current_user_can( 'edit_post', $post->ID ) ) { continue; } $posts[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'type' => $post->post_type, 'status' => $post->post_status, 'date' => get_the_date( 'Y-m-d', $post ), 'has_featured_image' => has_post_thumbnail( $post ), 'edit_url' => (string) get_edit_post_link( $post->ID, 'raw' ), ); if ( count( $posts ) >= $limit ) { break; } } if ( $page >= (int) $query->max_num_pages ) { break; } } return array( 'posts' => $posts, ); } public function execute_get_usage() { $pro = $this->is_pro(); return array( 'is_pro' => $pro, 'limit' => ( $pro ? null : self::FREE_MCP_IMAGE_LIMIT ), 'used' => ( $pro ? 0 : self::get_usage() ), 'remaining' => self::get_remaining(), ); } public function execute_list_posts_missing_image( $input ) { $input = (array) $input; $input['has_featured_image'] = 'no'; // Over MCP the schema already rejects these; this guards direct PHP callers. unset( $input['image_older_than_brand_kit'], $input['search'], $input['after'], $input['before'] ); return $this->list_posts( $input ); } public function execute_list_posts( $input ) { return $this->list_posts( (array) $input ); } /** * Posts the caller may edit, filtered. Shared by list-posts and list-posts-missing-image. * * @param array $input Tool input. * @return array|\WP_Error */ private function list_posts( $input ) { $enabled = $this->settings->get_content_post_types(); $post_type = ( isset( $input['post_type'] ) ? sanitize_key( $input['post_type'] ) : 'post' ); // 'any' skips enabled types whose plugin has since been switched off. $types = ( 'any' === $post_type ? array_values( array_filter( $enabled, 'post_type_exists' ) ) : array($post_type) ); if ( !$types ) { return new \WP_Error('no_post_types', __( 'None of the post types enabled for AI images exist any more. Check AI Images > General.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } // Finding works on any post type the admin shows; making images still needs an enabled one. foreach ( $types as $type ) { $object = get_post_type_object( $type ); if ( !$object || !$object->show_ui || 'attachment' === $type ) { return new \WP_Error('invalid_post_type', __( 'Unknown post type.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } } $limit = ( isset( $input['limit'] ) ? max( 1, min( 50, (int) $input['limit'] ) ) : 20 ); $page = ( isset( $input['page'] ) ? max( 1, (int) $input['page'] ) : 1 ); $empty = array( 'posts' => array(), 'total' => 0, 'total_pages' => 0, 'page' => $page, ); // Only statuses this user can edit, so totals match what they can act on. With // several post types the strictest one wins. Post types without map_meta_cap // lack the published/private caps, so fall back. $editable = array( 'draft', 'pending', 'publish', 'future', 'private' ); $can_others = true; foreach ( $types as $type ) { $caps = get_post_type_object( $type )->cap; if ( !current_user_can( $caps->edit_posts ) ) { return $empty; } $others = current_user_can( $caps->edit_others_posts ); $can_others = $can_others && $others; $mine = array('draft', 'pending'); if ( current_user_can( ( isset( $caps->edit_published_posts ) ? $caps->edit_published_posts : $caps->edit_posts ) ) ) { $mine[] = 'publish'; $mine[] = 'future'; } if ( !$others || current_user_can( ( isset( $caps->edit_private_posts ) ? $caps->edit_private_posts : $caps->edit_others_posts ) ) ) { $mine[] = 'private'; } $editable = array_values( array_intersect( $editable, $mine ) ); } $status = ( isset( $input['status'] ) ? (string) $input['status'] : 'any' ); $statuses = ( 'any' === $status ? $editable : array_values( array_intersect( array($status), $editable ) ) ); if ( !$statuses ) { return $empty; } $args = array( 'post_type' => $types, 'post_status' => $statuses, 'posts_per_page' => $limit, 'paged' => $page, 'orderby' => 'date', 'order' => 'DESC', ); if ( !$can_others ) { $args['author'] = get_current_user_id(); } $author = $this->resolve_author( $input ); if ( is_wp_error( $author ) ) { return $author; } if ( $author ) { if ( !$can_others && $author !== get_current_user_id() ) { return $empty; // May only see their own posts. } $args['author'] = $author; } if ( !empty( $input['search'] ) ) { $args['s'] = sanitize_text_field( $input['search'] ); } $terms = $this->add_term_filters( $input, $args ); if ( is_wp_error( $terms ) ) { return $terms; } foreach ( array('after', 'before') as $date_key ) { if ( empty( $input[$date_key] ) ) { continue; } $date = \DateTime::createFromFormat( '!Y-m-d', (string) $input[$date_key] ); if ( !$date || $date->format( 'Y-m-d' ) !== $input[$date_key] ) { return new \WP_Error('invalid_date', sprintf( /* translators: 1: "after" or "before", 2: the value given */ __( '%1$s must be a real date written as YYYY-MM-DD, not "%2$s".', 'ai-featured-image-generator' ), $date_key, (string) $input[$date_key] ), array( 'status' => 400, )); } } if ( !empty( $input['after'] ) && !empty( $input['before'] ) && $input['after'] > $input['before'] ) { return new \WP_Error('invalid_date_range', __( 'The "after" date is later than the "before" date, so no post can match.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $date_query = array(); if ( !empty( $input['after'] ) ) { $date_query['after'] = sanitize_text_field( $input['after'] ); } if ( !empty( $input['before'] ) ) { $date_query['before'] = sanitize_text_field( $input['before'] ) . ' 23:59:59'; } if ( $date_query ) { $date_query['inclusive'] = true; $args['date_query'] = array($date_query); } if ( !empty( $input['ids_only'] ) ) { // The audit wants every matching post up to a cap, not a page of rows. $cap = (int) $input['ids_only']; $scan = new \WP_Query(array_merge( $args, array( 'posts_per_page' => $cap, 'paged' => 1, 'fields' => 'ids', ) )); $ids = array(); foreach ( $scan->posts as $post_id ) { if ( current_user_can( 'edit_post', $post_id ) ) { $ids[] = (int) $post_id; } } return array( 'ids' => $ids, 'truncated' => (int) $scan->found_posts > $cap, ); } $has_image = ( isset( $input['has_featured_image'] ) ? (string) $input['has_featured_image'] : 'any' ); $older = !empty( $input['image_older_than_brand_kit'] ); if ( $older ) { $has_image = 'yes'; } if ( 'no' === $has_image ) { // Same query the Bulk tab uses for "posts without a featured image". $args['meta_query'] = array(array( 'key' => '_thumbnail_id', 'compare' => 'NOT EXISTS', )); } elseif ( 'yes' === $has_image ) { $args['meta_query'] = array(array( 'key' => '_thumbnail_id', 'compare' => 'EXISTS', )); } $row = function ( $post ) { $thumb = (int) get_post_thumbnail_id( $post ); return array( 'id' => $post->ID, 'title' => $post->post_title, 'type' => $post->post_type, 'status' => $post->post_status, 'date' => get_the_date( 'Y-m-d', $post ), 'has_featured_image' => $thumb > 0, 'featured_image_id' => $thumb, 'edit_url' => (string) get_edit_post_link( $post->ID, 'raw' ), ); }; if ( $older ) { // The comparison is against each featured image's own date, which a post // query cannot do, so look through the matches in PHP and page the result. $changed = Settings::get_brand_kit_updated(); if ( !$changed ) { return $empty + array( 'note' => __( 'The Brand Kit has not been changed yet, so no image counts as older than it.', 'ai-featured-image-generator' ), ); } $cap = 500; $scan = new \WP_Query(array_merge( $args, array( 'posts_per_page' => $cap, 'paged' => 1, ) )); $found = array(); foreach ( $scan->posts as $post ) { $thumb = (int) get_post_thumbnail_id( $post ); if ( !$thumb || !current_user_can( 'edit_post', $post->ID ) ) { continue; } $made = get_post_field( 'post_date_gmt', $thumb ); if ( $made && strtotime( $made . ' UTC' ) < $changed ) { $found[] = $row( $post ); } } $total = count( $found ); $out = array( 'posts' => array_slice( $found, ($page - 1) * $limit, $limit ), 'total' => $total, 'total_pages' => (int) ceil( $total / max( 1, $limit ) ), 'page' => $page, 'brand_kit_changed' => gmdate( 'Y-m-d', $changed ), ); if ( (int) $scan->found_posts > $cap ) { $out['note'] = sprintf( /* translators: %d: number of posts checked */ __( 'Only the newest %d posts were checked.', 'ai-featured-image-generator' ), $cap ); } return $out; } $query = new \WP_Query($args); $posts = array(); foreach ( $query->posts as $post ) { if ( !current_user_can( 'edit_post', $post->ID ) ) { continue; } $posts[] = $row( $post ); } $total = (int) $query->found_posts; if ( empty( $query->posts ) && $page > 1 ) { // WP_Query reports 0 found past the last page; count from page 1 instead. $count = new \WP_Query(array_merge( $args, array( 'posts_per_page' => 1, 'paged' => 1, 'fields' => 'ids', ) )); $total = (int) $count->found_posts; } return array( 'posts' => $posts, 'total' => $total, 'total_pages' => (int) ceil( $total / max( 1, $limit ) ), 'page' => $page, ); } /** * Turn category / tag inputs into a tax_query. Names and slugs both work. * * @param array $input Tool input. * @param array $args WP_Query args, modified in place. * @return true|\WP_Error */ private function add_term_filters( $input, &$args ) { $map = array( 'category' => 'category', 'tag' => 'post_tag', ); foreach ( $map as $key => $taxonomy ) { $value = ( isset( $input[$key] ) ? trim( (string) $input[$key] ) : '' ); if ( $value === '' ) { continue; } $term = get_term_by( 'slug', sanitize_title( $value ), $taxonomy ); if ( !$term ) { $term = get_term_by( 'name', $value, $taxonomy ); } if ( !$term ) { $names = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => false, 'fields' => 'names', 'number' => 30, ) ); $names = ( is_array( $names ) && $names ? implode( ', ', $names ) : __( 'none', 'ai-featured-image-generator' ) ); $message = ( 'category' === $key ? sprintf( __( 'There is no category called "%1$s". Existing categories: %2$s', 'ai-featured-image-generator' ), $value, $names ) : sprintf( __( 'There is no tag called "%1$s". Existing tags: %2$s', 'ai-featured-image-generator' ), $value, $names ) ); return new \WP_Error('unknown_' . $key, $message, array( 'status' => 400, )); } $args['tax_query'][] = array( 'taxonomy' => $taxonomy, 'field' => 'term_id', 'terms' => (int) $term->term_id, ); } return true; } public function execute_get_post( $input ) { $post = $this->get_target_post( $input, true ); if ( is_wp_error( $post ) ) { return $post; } $thumb_id = get_post_thumbnail_id( $post->ID ); return array( 'id' => $post->ID, 'title' => $post->post_title, 'excerpt' => wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ), 60 ), 'post_type' => $post->post_type, 'status' => $post->post_status, 'paragraph_count' => $this->count_paragraphs( $post->post_content ), 'has_featured_image' => (bool) $thumb_id, 'featured_image_url' => ( $thumb_id ? (string) wp_get_attachment_url( $thumb_id ) : '' ), 'permalink' => (string) get_permalink( $post ), 'edit_url' => (string) get_edit_post_link( $post->ID, 'raw' ), ); } public function execute_set_featured_image( $input ) { return $this->pro_tool_error(); } public function execute_insert_image_into_post( $input ) { return $this->pro_tool_error(); } public function execute_remove_background( $input ) { return $this->pro_tool_error(); } public function execute_generate_audio( $input ) { return $this->pro_tool_error(); } public function execute_generate_product_image( $input ) { return $this->pro_tool_error(); } public function execute_audit_product_images( $input ) { return $this->pro_tool_error(); } public function execute_find_media( $input ) { $input = (array) $input; $search = ( isset( $input['search'] ) ? sanitize_text_field( $input['search'] ) : '' ); $limit = ( isset( $input['limit'] ) ? max( 1, min( 20, (int) $input['limit'] ) ) : 10 ); if ( $search === '' ) { return new \WP_Error('empty_search', __( 'Give part of the image name.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } // Core removes this filter itself after the next query, so it only affects this one. add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' ); $query = new \WP_Query(array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 's' => $search, 'posts_per_page' => $limit, 'orderby' => 'relevance', )); $kit = $this->settings->get_brand_kit(); $images = array(); foreach ( $query->posts as $post ) { $meta = wp_get_attachment_metadata( $post->ID ); $images[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'filename' => wp_basename( (string) get_attached_file( $post->ID ) ), 'url' => (string) wp_get_attachment_url( $post->ID ), 'width' => ( isset( $meta['width'] ) ? (int) $meta['width'] : 0 ), 'height' => ( isset( $meta['height'] ) ? (int) $meta['height'] : 0 ), 'mime' => $post->post_mime_type, 'date' => get_the_date( 'Y-m-d', $post ), 'is_brand_logo' => !empty( $kit['logo_id'] ) && (int) $kit['logo_id'] === $post->ID, ); } return array( 'images' => $images, ); } /* --------------------------------------------------------------------- * Brand Kit tools (Pro) * ------------------------------------------------------------------ */ /** * A fresh Brand Kit reader. Fresh because the class caches the kit for the * request, and the update tools change it mid-request. * * @return Brand_Kit */ private function brand_kit() { return new Brand_Kit($this->settings); } /** * @param int $attachment_id Attachment ID, may be 0. * @return array|null id, title, url */ private function attachment_summary( $attachment_id ) { $attachment_id = (int) $attachment_id; if ( !$attachment_id || !wp_attachment_is_image( $attachment_id ) ) { return null; } return array( 'id' => $attachment_id, 'title' => (string) get_the_title( $attachment_id ), 'url' => (string) wp_get_attachment_url( $attachment_id ), ); } /** * The Brand Kit as assistants see it. * * @return array */ private function brand_kit_summary() { $kit = $this->settings->get_brand_kit(); $changed = Settings::get_brand_kit_updated(); $logo = $this->attachment_summary( ( isset( $kit['logo_id'] ) ? $kit['logo_id'] : 0 ) ); if ( $logo ) { $logo += array( 'position' => $kit['logo_position'], 'size' => (int) $kit['logo_size'], 'opacity' => (int) $kit['logo_opacity'], 'margin' => (int) $kit['logo_margin'], 'offset_x' => (int) $kit['logo_offset_x'], 'offset_y' => (int) $kit['logo_offset_y'], ); } return array( 'enabled' => !empty( $kit['enabled'] ), 'active' => $this->brand_kit()->is_active(), 'colors' => ( isset( $kit['colors'] ) ? array_values( array_filter( (array) $kit['colors'] ) ) : array() ), 'tone' => ( isset( $kit['tone'] ) ? (string) $kit['tone'] : '' ), 'description' => ( isset( $kit['description'] ) ? (string) $kit['description'] : '' ), 'avoid' => ( isset( $kit['avoid'] ) ? (string) $kit['avoid'] : '' ), 'reference' => $this->attachment_summary( ( isset( $kit['reference_id'] ) ? $kit['reference_id'] : 0 ) ), 'logo' => $logo, 'last_changed' => ( $changed ? gmdate( 'Y-m-d', $changed ) : null ), 'settings_url' => admin_url( 'admin.php?page=ai-featured-image-generator&tab=brand' ), ); } public function execute_get_brand_kit() { return $this->pro_tool_error(); } /** * Shared by update-brand-kit and set-brand-logo. * * @param array $input Tool input. * @param array $map input key => settings key. * @return array|\WP_Error */ private function save_brand_fields( $input, $map ) { return $this->pro_tool_error(); } public function execute_update_brand_kit( $input ) { return $this->save_brand_fields( (array) $input, array( 'enabled' => 'brand_kit_enabled', 'colors' => 'brand_kit_colors', 'tone' => 'brand_kit_tone', 'description' => 'brand_kit_description', 'avoid' => 'brand_kit_avoid', 'reference_id' => 'brand_kit_reference_id', ) ); } public function execute_set_brand_logo( $input ) { return $this->save_brand_fields( (array) $input, array( 'logo_id' => 'brand_kit_logo_id', 'position' => 'brand_kit_logo_position', 'size' => 'brand_kit_logo_size', 'opacity' => 'brand_kit_logo_opacity', 'margin' => 'brand_kit_logo_margin', 'offset_x' => 'brand_kit_logo_offset_x', 'offset_y' => 'brand_kit_logo_offset_y', ) ); } public function execute_preview_brand_kit( $input ) { $input = (array) $input; return $this->pro_tool_error(); } public function execute_apply_brand_logo( $input ) { return $this->pro_tool_error(); } public function execute_remove_brand_logo( $input ) { return $this->pro_tool_error(); } public function execute_suggest_brand_kit() { return $this->pro_tool_error(); } /* --------------------------------------------------------------------- * Image audit tools * ------------------------------------------------------------------ */ /** * Common shapes, so 1024x683 reads as 3:2 and not 1024:683. * * @param int $width Pixels. * @param int $height Pixels. * @return string "W:H" for a known shape (within 2 percent), else "1.37:1" style. */ public static function ratio_label( $width, $height ) { if ( $width < 1 || $height < 1 ) { return ''; } $value = $width / $height; $common = array( '1:1', '4:3', '3:4', '3:2', '2:3', '16:9', '9:16', '5:4', '4:5', '21:9', '9:21', '2:1', '1:2', '3:1', '1:3', '16:10', '10:16' ); $best = ''; $delta = 0.02; foreach ( $common as $label ) { list( $w, $h ) = array_map( 'intval', explode( ':', $label ) ); $diff = abs( $value - $w / $h ) / ($w / $h); if ( $diff <= $delta ) { $best = $label; $delta = $diff; } } if ( $best !== '' ) { return $best; } return ( $value >= 1 ? round( $value, 2 ) . ':1' : '1:' . round( 1 / $value, 2 ) ); } /** * Format slug from a mime type or file name: jpg, png, webp, gif, avif, svg. * * @param string $mime Mime type, may be empty. * @param string $name File name or URL, used when the mime is unknown. * @return string */ private static function format_slug( $mime, $name = '' ) { $map = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'image/gif' => 'gif', 'image/avif' => 'avif', 'image/svg+xml' => 'svg', ); if ( isset( $map[$mime] ) ) { return $map[$mime]; } $ext = strtolower( (string) pathinfo( (string) wp_parse_url( $name, PHP_URL_PATH ), PATHINFO_EXTENSION ) ); return ( $ext === 'jpeg' ? 'jpg' : $ext ); } /** * Facts about one Media Library image, from stored metadata (no pixel work). * * @param int $attachment_id Attachment. * @return array|null Null when it is not an image. */ private function image_facts( $attachment_id ) { $attachment_id = (int) $attachment_id; if ( !$attachment_id || !wp_attachment_is_image( $attachment_id ) ) { return null; } $meta = wp_get_attachment_metadata( $attachment_id ); $width = ( isset( $meta['width'] ) ? (int) $meta['width'] : 0 ); $height = ( isset( $meta['height'] ) ? (int) $meta['height'] : 0 ); $path = (string) get_attached_file( $attachment_id ); if ( (!$width || !$height) && $path && file_exists( $path ) ) { $size = @getimagesize( $path ); if ( $size ) { $width = (int) $size[0]; $height = (int) $size[1]; } } $bytes = ( isset( $meta['filesize'] ) ? (int) $meta['filesize'] : 0 ); if ( !$bytes && $path && file_exists( $path ) ) { $bytes = (int) filesize( $path ); } return array( 'attachment_id' => $attachment_id, 'title' => (string) get_the_title( $attachment_id ), 'url' => (string) wp_get_attachment_url( $attachment_id ), 'width' => $width, 'height' => $height, 'ratio' => self::ratio_label( $width, $height ), 'format' => self::format_slug( (string) get_post_mime_type( $attachment_id ), $path ), 'kb' => (int) round( $bytes / 1024 ), 'alt' => (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ), 'uploaded' => (string) get_the_date( 'Y-m-d', $attachment_id ), ); } /** * Sharpness and edge measurements for an attachment, measured on its "large" size. * The result is kept on the attachment until its files or the rules change. * * @param int $attachment_id Attachment. * @param bool $measure False returns only a kept result and never measures. * @return array|false|null The measurements; false when the image cannot be measured * (it is not tried again until it changes); null when it is * not a measurable file, or has no kept result and $measure is false. */ public function measure_attachment( $attachment_id, $measure = true ) { $path = (string) get_attached_file( $attachment_id ); if ( $path === '' || !file_exists( $path ) || 'image/svg+xml' === get_post_mime_type( $attachment_id ) ) { return null; } $large = image_get_intermediate_size( $attachment_id, 'large' ); $uploads = wp_upload_dir(); $detail = ( $large && !empty( $large['path'] ) && empty( $uploads['error'] ) ? $uploads['basedir'] . '/' . $large['path'] : '' ); $signature = md5( implode( '|', array( $path, filesize( $path ), filemtime( $path ), $detail, ( $detail !== '' && file_exists( $detail ) ? filemtime( $detail ) : 0 ) ) ) ); $kept = get_post_meta( $attachment_id, self::META_MEASURE, true ); if ( is_array( $kept ) && isset( $kept['v'], $kept['sig'], $kept['m'] ) && self::MEASURE_VERSION === (int) $kept['v'] && $signature === $kept['sig'] && (is_array( $kept['m'] ) || false === $kept['m']) ) { return $kept['m']; } if ( !$measure ) { return null; } $result = $this->measure_image( $path, $detail ); update_post_meta( $attachment_id, self::META_MEASURE, array( 'v' => self::MEASURE_VERSION, 'sig' => $signature, 'm' => ( $result ? $result : false ), ) ); return ( $result ? $result : false ); } /** * @param string $value A date the schema already shaped as YYYY-MM-DD. * @return bool Whether it is a real calendar date. */ private static function is_real_date( $value ) { $date = \DateTime::createFromFormat( '!Y-m-d', (string) $value ); return $date && $date->format( 'Y-m-d' ) === (string) $value; } /** * Images inside a post's content: block images, classic tags, and images * from other sites (reported with attachment_id 0). * * @param string $content Post content. * @return array[] attachment_id, url, alt, alt_in_content (bool) */ private function content_images( $content ) { $images = array(); if ( $content === '' || !preg_match_all( '/]*>/i', $content, $tags ) ) { return $images; } foreach ( $tags[0] as $tag ) { $id = ( preg_match( '/\\bwp-image-(\\d+)\\b/', $tag, $m ) ? (int) $m[1] : 0 ); $src = ( preg_match( '/(? $id, 'url' => $src, 'alt' => ( $alt === null ? '' : $alt ), 'alt_in_content' => $alt !== null, ); } return $images; } /** * Collect the images an audit looks at and the ones that match its filters. * * Shared by the audit-images tool and the Image Audit tab. Does the cheap * checks only (alt text, format, shape, pixel and file size, dates); the * pixel checks for blur and cut-off edges stay in execute_audit_images(). * * @param array $input Same filters as the audit-images tool. * @return array|\WP_Error scope, scanned, found, by_format, by_ratio, note. */ public function audit_scan( $input ) { $input = (array) $input; $scope = ( isset( $input['scope'] ) ? (string) $input['scope'] : 'posts' ); $want_ratio = ( isset( $input['aspect_ratio'] ) ? (string) $input['aspect_ratio'] : '' ); $want_value = 0; if ( $want_ratio !== '' ) { list( $rw, $rh ) = array_map( 'intval', explode( ':', $want_ratio ) ); if ( $rw < 1 || $rh < 1 ) { return new \WP_Error('invalid_aspect_ratio', __( 'Give the shape as two numbers, such as 1:1 or 16:9.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $want_value = $rw / $rh; } foreach ( array('uploaded_after', 'uploaded_before') as $date_key ) { if ( !empty( $input[$date_key] ) && !self::is_real_date( $input[$date_key] ) ) { return new \WP_Error('invalid_date', sprintf( /* translators: 1: the input name, 2: the value given */ __( '%1$s must be a real date written as YYYY-MM-DD, not "%2$s".', 'ai-featured-image-generator' ), $date_key, (string) $input[$date_key] ), array( 'status' => 400, )); } } $matches = function ( $img ) use($input, $want_ratio, $want_value) { if ( isset( $input['missing_alt'] ) && ($img['alt'] === '') !== (bool) $input['missing_alt'] ) { return false; } if ( !empty( $input['uploaded_after'] ) && (empty( $img['uploaded'] ) || $img['uploaded'] < $input['uploaded_after']) ) { return false; } if ( !empty( $input['uploaded_before'] ) && (empty( $img['uploaded'] ) || $img['uploaded'] > $input['uploaded_before']) ) { return false; } if ( !empty( $input['format'] ) && $img['format'] !== $input['format'] ) { return false; } if ( $want_ratio !== '' ) { if ( !$img['width'] || !$img['height'] ) { return false; } if ( abs( $img['width'] / $img['height'] - $want_value ) / $want_value > 0.02 ) { return false; } } foreach ( array( 'min_width' => array('width', '>='), 'max_width' => array('width', '<='), 'min_kb' => array('kb', '>='), 'max_kb' => array('kb', '<='), ) as $key => $rule ) { if ( empty( $input[$key] ) ) { continue; } $have = (int) $img[$rule[0]]; if ( !$have ) { // A known file under 0.5 KB rounds to 0 KB and still counts as 0 KB. $known_small = false; if ( 'kb' === $rule[0] && !empty( $img['attachment_id'] ) ) { $meta = wp_get_attachment_metadata( $img['attachment_id'] ); $path = (string) get_attached_file( $img['attachment_id'] ); $known_small = !empty( $meta['filesize'] ) || $path && file_exists( $path ) && filesize( $path ) > 0; } if ( !$known_small ) { return false; // Unknown size never matches a size filter. } } if ( ( '>=' === $rule[1] ? $have < (int) $input[$key] : $have > (int) $input[$key] ) ) { return false; } } return true; }; $scanned = 0; $found = array(); $by_format = array(); $by_ratio = array(); $tally = function ( $img ) use(&$by_format, &$by_ratio) { $f = ( $img['format'] !== '' ? $img['format'] : 'unknown' ); $r = ( $img['ratio'] !== '' ? $img['ratio'] : 'unknown' ); $by_format[$f] = (( isset( $by_format[$f] ) ? $by_format[$f] : 0 )) + 1; $by_ratio[$r] = (( isset( $by_ratio[$r] ) ? $by_ratio[$r] : 0 )) + 1; }; $note = ''; if ( 'library' === $scope ) { $cap = 2000; $args = array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'posts_per_page' => $cap, 'orderby' => 'date', 'order' => 'DESC', 'fields' => 'ids', ); $author = $this->resolve_author( $input ); if ( is_wp_error( $author ) ) { return $author; } if ( $author ) { $args['author'] = $author; } $query = new \WP_Query($args); $ids = array_map( 'intval', $query->posts ); if ( $ids ) { _prime_post_caches( $ids, false, true ); update_meta_cache( 'post', $ids ); } // Without upload rights, only images the caller may edit, or whose post they may read. $whole_library = current_user_can( 'upload_files' ); foreach ( $ids as $id ) { if ( !$whole_library && !$this->can_view_attachment( $id ) ) { continue; } $img = $this->image_facts( $id ); if ( !$img ) { continue; } $scanned++; $tally( $img ); if ( $matches( $img ) ) { $img['uploaded_to'] = (int) get_post_field( 'post_parent', $id ); $found[] = $img; } } if ( (int) $query->found_posts > $cap ) { $note = sprintf( /* translators: %d: number of images checked */ __( 'Only the newest %d images were checked.', 'ai-featured-image-generator' ), $cap ); } } else { $list = $this->list_posts( array( 'post_type' => ( isset( $input['post_type'] ) ? $input['post_type'] : 'any' ), 'status' => ( isset( $input['status'] ) ? $input['status'] : 'any' ), 'category' => ( isset( $input['category'] ) ? $input['category'] : '' ), 'tag' => ( isset( $input['tag'] ) ? $input['tag'] : '' ), 'author' => ( isset( $input['author'] ) ? $input['author'] : '' ), 'limit' => 50, 'page' => 1, 'ids_only' => self::AUDIT_POST_CAP, ) ); if ( is_wp_error( $list ) ) { return $list; } $location = ( isset( $input['location'] ) ? (string) $input['location'] : 'any' ); if ( $list['ids'] ) { // One query each for the posts with their meta, then for their featured images, // instead of several per post. _prime_post_caches( $list['ids'], false, true ); update_meta_cache( 'post', $list['ids'] ); $thumbs = array(); foreach ( $list['ids'] as $post_id ) { $thumbs[] = (int) get_post_meta( $post_id, '_thumbnail_id', true ); } $thumbs = array_values( array_filter( array_unique( $thumbs ) ) ); if ( $thumbs ) { _prime_post_caches( $thumbs, false, true ); update_meta_cache( 'post', $thumbs ); } } foreach ( $list['ids'] as $post_id ) { $post = get_post( $post_id ); if ( !$post ) { continue; } $scanned++; $post_images = array(); if ( 'content' !== $location ) { $thumb = (int) get_post_thumbnail_id( $post ); $img = ( $thumb ? $this->image_facts( $thumb ) : null ); if ( $img ) { $img['location'] = 'featured'; $post_images[] = $img; } } // WooCommerce product galleries, when the caller asks (the Image Audit tab does). if ( !empty( $input['gallery'] ) && 'any' === $location && 'product' === $post->post_type ) { $main = (int) get_post_thumbnail_id( $post ); foreach ( array_unique( array_filter( array_map( 'absint', explode( ',', (string) get_post_meta( $post->ID, '_product_image_gallery', true ) ) ) ) ) as $gallery_id ) { $img = ( $gallery_id !== $main ? $this->image_facts( $gallery_id ) : null ); if ( $img ) { $img['location'] = 'gallery'; $post_images[] = $img; } } } if ( 'featured' !== $location ) { foreach ( $this->content_images( (string) $post->post_content ) as $ref ) { // A wp-image-N class can name any Media Library item, so facts come only // from images the caller may see; anything else is treated as an outside image. $img = ( $ref['attachment_id'] && $this->can_view_attachment( $ref['attachment_id'] ) ? $this->image_facts( $ref['attachment_id'] ) : null ); if ( !$img ) { $img = array( 'attachment_id' => 0, 'title' => '', 'url' => $ref['url'], 'width' => 0, 'height' => 0, 'ratio' => '', 'format' => self::format_slug( '', $ref['url'] ), 'kb' => 0, 'alt' => '', 'external' => true, ); } // The alt readers see is the one in the content, when the tag has one. if ( $ref['alt_in_content'] ) { $img['alt'] = $ref['alt']; } $img['location'] = 'content'; $post_images[] = $img; } } foreach ( $post_images as $img ) { $tally( $img ); if ( $matches( $img ) ) { $img['post_id'] = $post->ID; $img['post_title'] = $post->post_title; $img['post_type'] = $post->post_type; $img['edit_url'] = (string) get_edit_post_link( $post->ID, 'raw' ); $found[] = $img; } } } if ( !empty( $list['truncated'] ) ) { $note = sprintf( /* translators: %d: number of posts checked */ __( 'Only the newest %d posts were checked.', 'ai-featured-image-generator' ), self::AUDIT_POST_CAP ); } } arsort( $by_format ); arsort( $by_ratio ); return array( 'scope' => $scope, 'scanned' => $scanned, 'found' => $found, 'by_format' => $by_format, 'by_ratio' => $by_ratio, 'note' => $note, ); } public function execute_audit_images( $input, $scan = null ) { $input = (array) $input; $limit = ( isset( $input['limit'] ) ? max( 1, min( 100, (int) $input['limit'] ) ) : 50 ); $page = ( isset( $input['page'] ) ? max( 1, (int) $input['page'] ) : 1 ); // The Image Audit tab passes the scan it already has, so a list never scans twice. // An assistant paging through results gets the scan made for page 1: page 1 always // scans fresh, later pages reuse it for a few minutes. if ( !is_array( $scan ) ) { $filters = $input; unset($filters['page'], $filters['limit']); ksort( $filters ); $cache_key = self::AUDIT_CACHE_PREFIX . md5( get_current_user_id() . '|' . wp_json_encode( $filters ) ); $cached = ( $page > 1 ? get_transient( $cache_key ) : false ); if ( is_array( $cached ) && isset( $cached['found'], $cached['by_format'] ) ) { $scan = $cached; } else { $scan = $this->audit_scan( $input ); if ( is_array( $scan ) ) { set_transient( $cache_key, $scan, self::AUDIT_CACHE_TTL ); } } } if ( is_wp_error( $scan ) ) { return $scan; } $scope = $scan['scope']; $scanned = $scan['scanned']; $found = $scan['found']; $by_format = $scan['by_format']; $by_ratio = $scan['by_ratio']; $note = $scan['note']; $quality = ( isset( $input['quality'] ) ? (string) $input['quality'] : '' ); // Quality needs pixel work, so it runs on a window of candidates per call. $quality_note = ''; if ( $quality !== '' ) { $window = 100; $candidates = array_values( array_filter( $found, function ( $img ) { return !empty( $img['attachment_id'] ) && 'svg' !== $img['format']; } ) ); $slice = array_slice( $candidates, ($page - 1) * $window, $window ); $kept = array(); $checked = 0; $cache = array(); foreach ( $slice as $img ) { $aid = (int) $img['attachment_id']; if ( !isset( $cache[$aid] ) ) { $cache[$aid] = $this->measure_attachment( $aid ); } $m = $cache[$aid]; $checked++; if ( !$m ) { continue; } $small = $img['width'] > 0 && $img['width'] < 800; if ( 'blurry' === $quality ) { $hit = 'blurry' === $m['sharpness_label']; } elseif ( 'low_quality' === $quality ) { $hit = 'sharp' !== $m['sharpness_label'] || $small; } else { $hit = !empty( $m['busy_edges'] ); } if ( $hit ) { $img['sharpness'] = $m['sharpness']; $img['sharpness_label'] = $m['sharpness_label']; $img['busy_edges'] = $m['busy_edges']; $img['flat_edges'] = $m['flat_edges']; $kept[] = $img; } } $pages = (int) ceil( count( $candidates ) / $window ); $out = array( 'scope' => $scope, 'scanned' => $scanned, 'images_checked' => array_sum( $by_format ), 'quality' => $quality, 'measured' => $checked, 'matched' => count( $kept ), 'posts_matched' => ( 'posts' === $scope ? count( array_unique( wp_list_pluck( $kept, 'post_id' ) ) ) : null ), 'by_format' => $by_format, 'by_ratio' => $by_ratio, 'images' => $kept, 'total_pages' => $pages, 'page' => $page, ); if ( $pages > $page ) { $out['note'] = sprintf( /* translators: 1: first image number, 2: last image number, 3: total, 4: next page number */ __( 'Measured images %1$d to %2$d of %3$d. Ask for page %4$d to check the next ones.', 'ai-featured-image-generator' ), ($page - 1) * $window + 1, ($page - 1) * $window + $checked, count( $candidates ), $page + 1 ); } elseif ( $note !== '' ) { $out['note'] = $note; } return $out; } $total = count( $found ); $out = array( 'scope' => $scope, 'scanned' => $scanned, 'images_checked' => array_sum( $by_format ), 'matched' => $total, 'posts_matched' => ( 'posts' === $scope ? count( array_unique( wp_list_pluck( $found, 'post_id' ) ) ) : null ), 'by_format' => $by_format, 'by_ratio' => $by_ratio, 'images' => array_slice( $found, ($page - 1) * $limit, $limit ), 'total_pages' => (int) ceil( $total / $limit ), 'page' => $page, ); if ( $note !== '' ) { $out['note'] = $note; } return $out; } /** * The attachment a per-image tool works on: attachment_id, or the featured image of post_id. * * @param array $input Tool input. * @param bool $read_only True for tools that only look at the image. * @return int|\WP_Error */ private function resolve_image_input( $input, $read_only = false ) { $input = (array) $input; $id = ( isset( $input['attachment_id'] ) ? absint( $input['attachment_id'] ) : 0 ); if ( $id && wp_attachment_is_image( $id ) && !$this->can_view_attachment( $id ) ) { return new \WP_Error('rest_forbidden', __( 'You are not allowed to view this image.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } if ( !$id && !empty( $input['post_id'] ) ) { $post = $this->get_target_post( $input, $read_only ); if ( is_wp_error( $post ) ) { return $post; } $id = (int) get_post_thumbnail_id( $post->ID ); if ( !$id ) { return new \WP_Error('no_featured_image', __( 'This post has no featured image.', 'ai-featured-image-generator' ), array( 'status' => 404, )); } } if ( !$id ) { return new \WP_Error('missing_image', __( 'Give an attachment_id or a post_id.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } if ( !wp_attachment_is_image( $id ) ) { return new \WP_Error('invalid_attachment', __( 'That attachment is not an image in the Media Library.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } return $id; } /** * Whether the caller may look at a Media Library item picked by ID: anyone who * uploads files, or who may edit the item, or read the post it was uploaded to. * * @param int $attachment_id Attachment. * @return bool */ private function can_view_attachment( $attachment_id ) { if ( current_user_can( 'upload_files' ) || current_user_can( 'edit_post', $attachment_id ) ) { return true; } $parent = (int) get_post_field( 'post_parent', $attachment_id ); return $parent > 0 && current_user_can( 'read_post', $parent ); } /** * Load an image into GD, downscaled so the longest side is at most $max. * * @param string $path Image file. * @param int $max Longest side. * @return resource|\GdImage|null */ private function load_small_gd( $path, $max ) { if ( !function_exists( 'imagecreatefromstring' ) ) { return null; } // A very large original (big-image downscaling turned off) can need hundreds of MB // to open; give up early instead of running out of memory on every try. $size = @getimagesize( $path ); if ( is_array( $size ) && !empty( $size[0] ) && !empty( $size[1] ) ) { wp_raise_memory_limit( 'image' ); $limit = wp_convert_hr_to_bytes( (string) ini_get( 'memory_limit' ) ); $need = (int) $size[0] * (int) $size[1] * 5 + 10 * MB_IN_BYTES; if ( $limit > 0 && memory_get_usage() + $need > $limit ) { return null; } } $bytes = @file_get_contents( $path ); $image = ( $bytes ? @imagecreatefromstring( $bytes ) : false ); if ( !$image ) { return null; } // PNG-8 and GIF load as palette images, where imagecolorat() gives a palette // index instead of a colour, so the pixel checks would read nonsense. if ( !imageistruecolor( $image ) && function_exists( 'imagepalettetotruecolor' ) ) { imagepalettetotruecolor( $image ); } $w = imagesx( $image ); $h = imagesy( $image ); $scale = ( max( $w, $h ) > $max ? $max / max( $w, $h ) : 1 ); if ( $scale < 1 ) { $small = imagecreatetruecolor( max( 1, (int) round( $w * $scale ) ), max( 1, (int) round( $h * $scale ) ) ); imagealphablending( $small, false ); imagesavealpha( $small, true ); imagecopyresampled( $small, $image, 0, 0, 0, 0, imagesx( $small ), imagesy( $small ), $w, $h ); imagedestroy( $image ); $image = $small; } return $image; } /** * Grayscale values of a GD image, row by row. * * @param resource|\GdImage $image Image. * @return float[][] */ private static function gray_rows( $image ) { $w = imagesx( $image ); $h = imagesy( $image ); $gray = array(); for ($y = 0; $y < $h; $y++) { $row = array(); for ($x = 0; $x < $w; $x++) { $rgb = imagecolorat( $image, $x, $y ); $row[] = (($rgb >> 16 & 255) * 299 + ($rgb >> 8 & 255) * 587 + ($rgb & 255) * 114) / 1000; } $gray[] = $row; } return $gray; } /** * Variance of a Laplacian filter: little local contrast means blur. * * @param float[][] $gray Grayscale rows. * @return float */ private static function laplacian_variance( $gray ) { $h = count( $gray ); $w = ( $h ? count( $gray[0] ) : 0 ); $sum = 0; $sq = 0; $n = 0; for ($y = 1; $y < $h - 1; $y++) { for ($x = 1; $x < $w - 1; $x++) { $lap = 4 * $gray[$y][$x] - $gray[$y - 1][$x] - $gray[$y + 1][$x] - $gray[$y][$x - 1] - $gray[$y][$x + 1]; $sum += $lap; $sq += $lap * $lap; $n++; } } return ( $n ? $sq / $n - ($sum / $n) ** 2 : 0 ); } /** * Sharpness and edge measurements. * * Sharpness is measured on a centre crop at the image's own resolution (the * "large" size WordPress keeps, so even a 4K original costs little): the * Laplacian variance of the crop divided by that of a slightly blurred copy. * A sharp picture loses a lot to the blur, an already blurry one loses almost * nothing, whatever the subject. Edge checks run on a small copy of the whole * image: a border strip as busy as the middle hints at something cut off, a * strip with no change at all is padding or a letterbox bar. * * Ground, cities, tables and other scenery run off the bottom and the sides of * most pictures on purpose, so those edges count only when one thing crosses * them with calm space at both ends of the edge. The top edge, where titles and * heads get cut, counts as soon as it is as busy as the middle. * * @param string $path Original file. * @param string $detail_path File to measure sharpness on, usually the "large" size. * @return array|null */ private function measure_image( $path, $detail_path = '' ) { if ( !function_exists( 'imagecreatefromstring' ) ) { return null; } $detail_path = ( $detail_path !== '' && file_exists( $detail_path ) ? $detail_path : $path ); // A very large original can need more memory than PHP has; give up instead of crashing. if ( !Image_Pixels::fits_in_memory( $detail_path ) ) { return null; } $bytes = @file_get_contents( $detail_path ); $full = ( $bytes ? @imagecreatefromstring( $bytes ) : false ); if ( !$full ) { return null; } $w = imagesx( $full ); $h = imagesy( $full ); $cw = min( 400, $w ); $ch = min( 400, $h ); if ( $cw < 8 || $ch < 8 ) { imagedestroy( $full ); return null; } $crop = imagecreatetruecolor( $cw, $ch ); imagecopy( $crop, $full, 0, 0, (int) (($w - $cw) / 2), (int) (($h - $ch) / 2), $cw, $ch ); imagedestroy( $full ); $gray = self::gray_rows( $crop ); imagedestroy( $crop ); $detail = self::laplacian_variance( $gray ); $blurred = $gray; for ($y = 1; $y < $ch - 1; $y++) { for ($x = 1; $x < $cw - 1; $x++) { $t = 0; for ($dy = -1; $dy <= 1; $dy++) { for ($dx = -1; $dx <= 1; $dx++) { $t += $gray[$y + $dy][$x + $dx]; } } $blurred[$y][$x] = $t / 9; } } $ratio = $detail / max( 0.001, self::laplacian_variance( $blurred ) ); if ( $ratio < 4 || $detail < 60 ) { $label = 'blurry'; } elseif ( $ratio < 6.5 || $detail < 150 ) { $label = 'soft'; } else { $label = 'sharp'; } unset($gray, $blurred); // Edges, on a small copy of the whole picture. $small = $this->load_small_gd( $path, 400 ); $busy = array(); $flat = array(); $full_bleed = false; if ( $small && imagesx( $small ) >= 8 && imagesy( $small ) >= 8 ) { $gray = self::gray_rows( $small ); $sw = imagesx( $small ); $sh = imagesy( $small ); imagedestroy( $small ); $strip = max( 2, (int) round( min( $sw, $sh ) * 0.04 ) ); $zones = array( 'top' => 0, 'bottom' => 0, 'left' => 0, 'right' => 0, 'middle' => 0, ); $counts = $zones; // Each edge strip is also split into 8 parts along its length. $parts = array_fill_keys( array( 'top', 'bottom', 'left', 'right' ), array_fill( 0, 8, 0 ) ); $pcount = $parts; for ($y = 1; $y < $sh - 1; $y++) { for ($x = 1; $x < $sw - 1; $x++) { $g = abs( $gray[$y][$x + 1] - $gray[$y][$x - 1] ) + abs( $gray[$y + 1][$x] - $gray[$y - 1][$x] ); if ( $y < $strip ) { $zone = 'top'; $part = (int) ($x * 8 / $sw); } elseif ( $y >= $sh - $strip ) { $zone = 'bottom'; $part = (int) ($x * 8 / $sw); } elseif ( $x < $strip ) { $zone = 'left'; $part = (int) ($y * 8 / $sh); } elseif ( $x >= $sw - $strip ) { $zone = 'right'; $part = (int) ($y * 8 / $sh); } else { $zone = 'middle'; } $zones[$zone] += $g; $counts[$zone] += 1; if ( 'middle' !== $zone ) { $parts[$zone][$part] += $g; $pcount[$zone][$part] += 1; } } } foreach ( $zones as $zone => $total ) { $zones[$zone] = ( $counts[$zone] ? $total / $counts[$zone] : 0 ); } foreach ( array( 'top', 'bottom', 'left', 'right' ) as $side ) { if ( $zones[$side] < 0.2 ) { $flat[] = $side; } elseif ( $zones[$side] >= 4 && $zones[$side] >= 0.9 * $zones['middle'] ) { $busy[] = $side; } } if ( count( $busy ) === 4 ) { // Detail everywhere is a pattern or texture, not a crop problem. $full_bleed = true; $busy = array(); } $middle = max( 0.001, $zones['middle'] ); $busy = array_values( array_filter( $busy, function ( $side ) use($parts, $pcount, $middle) { if ( 'top' === $side ) { return true; } $level = array(); foreach ( $parts[$side] as $i => $total ) { $level[] = ( $pcount[$side][$i] ? $total / $pcount[$side][$i] / $middle : 0 ); } $detailed = count( array_filter( $level, function ( $v ) { return $v >= 1; } ) ); $calm_start = $level[0] < 0.5 || $level[1] < 0.5; $calm_end = $level[6] < 0.5 || $level[7] < 0.5; return $detailed >= 2 && $calm_start && $calm_end; } ) ); } elseif ( $small ) { imagedestroy( $small ); } return array( 'sharpness' => round( $ratio, 1 ), 'detail' => (int) round( $detail ), 'sharpness_label' => $label, 'busy_edges' => $busy, 'flat_edges' => $flat, 'full_bleed' => $full_bleed, ); } public function execute_inspect_image( $input ) { $id = $this->resolve_image_input( $input, true ); if ( is_wp_error( $id ) ) { return $id; } $facts = $this->image_facts( $id ); $path = (string) get_attached_file( $id ); $facts['file_exists'] = $path !== '' && file_exists( $path ); $facts['mime'] = (string) get_post_mime_type( $id ); $facts['date'] = get_the_date( 'Y-m-d', $id ); // Where it is used: as a featured image, or inside content. Only posts the caller may // read are listed, so private posts and other people's drafts stay hidden. $used = array(); $featured = get_posts( array( 'post_type' => 'any', 'post_status' => 'any', 'numberposts' => 20, 'fields' => 'ids', 'meta_key' => '_thumbnail_id', 'meta_value' => $id, ) ); foreach ( $featured as $post_id ) { if ( !current_user_can( 'read_post', $post_id ) ) { continue; } $used[] = array( 'post_id' => (int) $post_id, 'title' => get_the_title( $post_id ), 'as' => 'featured', ); } $in_content = get_posts( array( 'post_type' => 'any', 'post_status' => 'any', 'numberposts' => 20, 'fields' => 'ids', 's' => 'wp-image-' . $id, 'sentence' => true, ) ); foreach ( $in_content as $post_id ) { // The search matches substrings, so wp-image-12 also finds wp-image-123: check the exact id. if ( !preg_match( '/\\bwp-image-' . (int) $id . '\\b/', (string) get_post_field( 'post_content', $post_id ) ) ) { continue; } if ( !current_user_can( 'read_post', $post_id ) ) { continue; } $used[] = array( 'post_id' => (int) $post_id, 'title' => get_the_title( $post_id ), 'as' => 'content', ); } $facts['used_by'] = $used; $hints = array(); if ( $facts['alt'] === '' ) { $hints[] = __( 'No alt text.', 'ai-featured-image-generator' ); } if ( $facts['width'] && $facts['width'] < 800 ) { $hints[] = __( 'Narrower than 800 px, which is small for a featured image.', 'ai-featured-image-generator' ); } if ( $facts['kb'] > 600 ) { $hints[] = __( 'Larger than 600 KB, which slows the page down.', 'ai-featured-image-generator' ); } if ( $facts['file_exists'] && 'svg' !== $facts['format'] ) { $large = image_get_intermediate_size( $id, 'large' ); $uploads = wp_upload_dir(); $measure = $this->measure_image( $path, ( $large && !empty( $large['path'] ) && empty( $uploads['error'] ) ? $uploads['basedir'] . '/' . $large['path'] : '' ) ); if ( $measure ) { $facts = array_merge( $facts, $measure ); if ( 'blurry' === $measure['sharpness_label'] ) { $hints[] = __( 'Looks blurry or very smooth.', 'ai-featured-image-generator' ); } if ( $measure['busy_edges'] ) { $hints[] = sprintf( /* translators: %s: list of edges, such as "top, left" */ __( 'Detail runs right into the %s edge, so something may be cut off. Check with view-image.', 'ai-featured-image-generator' ), implode( ', ', $measure['busy_edges'] ) ); } if ( $measure['full_bleed'] ) { $hints[] = __( 'Detail runs to every edge, like a pattern or texture.', 'ai-featured-image-generator' ); } if ( $measure['flat_edges'] ) { $hints[] = sprintf( /* translators: %s: list of edges, such as "top, bottom" */ __( 'The %s edge is flat, like padding or a letterbox bar.', 'ai-featured-image-generator' ), implode( ', ', $measure['flat_edges'] ) ); } } } $facts['hints'] = $hints; return $facts; } public function execute_view_image( $input ) { $input = (array) $input; $id = $this->resolve_image_input( $input, true ); if ( is_wp_error( $id ) ) { return $id; } if ( 'image/svg+xml' === get_post_mime_type( $id ) ) { return new \WP_Error('svg_no_preview', __( 'Vector images have no preview here; open the URL instead.', 'ai-featured-image-generator' ), array( 'status' => 415, )); } $path = (string) get_attached_file( $id ); if ( $path === '' || !file_exists( $path ) ) { return new \WP_Error('image_not_found', __( 'The image file is missing from the server.', 'ai-featured-image-generator' ), array( 'status' => 404, )); } $max = ( isset( $input['max_size'] ) ? max( 256, min( 1600, (int) $input['max_size'] ) ) : 1024 ); $image = $this->load_small_gd( $path, $max ); if ( !$image ) { return new \WP_Error('unsupported_image', __( 'This image format cannot be previewed on this server.', 'ai-featured-image-generator' ), array( 'status' => 415, )); } // JPEG keeps the preview small. Transparent areas are shown on white. $canvas = imagecreatetruecolor( imagesx( $image ), imagesy( $image ) ); imagefill( $canvas, 0, 0, imagecolorallocate( $canvas, 255, 255, 255 ) ); imagecopy( $canvas, $image, 0, 0, 0, 0, imagesx( $image ), imagesy( $image ) ); imagedestroy( $image ); ob_start(); imagejpeg( $canvas, null, 82 ); $bytes = (string) ob_get_clean(); imagedestroy( $canvas ); if ( $bytes === '' ) { return new \WP_Error('preview_failed', __( 'Could not make a preview of this image.', 'ai-featured-image-generator' ), array( 'status' => 500, )); } // The MCP Adapter turns this shape into an image the assistant can see. return array( 'type' => 'image', 'mimeType' => 'image/jpeg', 'results' => $bytes, ); } /** * Turn an author input (display name, username or email) into a user ID. * * @param array $input Tool input. * @return int|\WP_Error 0 when no author was given. */ private function resolve_author( $input ) { $value = ( isset( $input['author'] ) ? trim( (string) $input['author'] ) : '' ); if ( $value === '' ) { return 0; } // Only callers who may list users can look someone up by email or see other names, // so the tools cannot be used to find out who has an account. $can_list = current_user_can( 'list_users' ); foreach ( ( $can_list ? array('login', 'email', 'slug') : array('login', 'slug') ) as $field ) { $user = get_user_by( $field, $value ); // Without list_users, only people with published posts (public on the site anyway) // are found, so an exact username cannot be used to test whether an account exists. if ( $user && ($can_list || count_user_posts( $user->ID, 'post', true ) > 0 || count_user_posts( $user->ID, 'page', true ) > 0) ) { return (int) $user->ID; } } $search = array( 'search' => '*' . $value . '*', 'search_columns' => array('display_name', 'user_nicename', 'user_login'), 'number' => 2, 'fields' => array('ID', 'display_name'), ); if ( !$can_list ) { // Names of people with published posts are public on the site anyway. $search['has_published_posts'] = true; } $users = get_users( $search ); if ( count( $users ) === 1 ) { return (int) $users[0]->ID; } if ( !$can_list ) { return ( count( $users ) > 1 ? new \WP_Error('ambiguous_author', sprintf( /* translators: %s: what was asked for */ __( 'More than one user matches "%s". Use the exact name or username.', 'ai-featured-image-generator' ), $value ), array( 'status' => 400, )) : new \WP_Error('unknown_author', sprintf( /* translators: %s: what was asked for */ __( 'There is no author called "%s". Use the exact name or username.', 'ai-featured-image-generator' ), $value ), array( 'status' => 400, )) ); } $names = $this->author_candidates(); if ( count( $users ) > 1 ) { return new \WP_Error('ambiguous_author', sprintf( /* translators: 1: what was asked for, 2: comma-separated list of user names */ __( 'More than one user matches "%1$s". Use the exact name or username. Users: %2$s', 'ai-featured-image-generator' ), $value, implode( ', ', $names ) ), array( 'status' => 400, )); } return new \WP_Error('unknown_author', sprintf( /* translators: 1: what was asked for, 2: comma-separated list of user names */ __( 'There is no user called "%1$s". Users: %2$s', 'ai-featured-image-generator' ), $value, implode( ', ', $names ) ), array( 'status' => 400, )); } /** * Up to 30 names to suggest when an author is not found: people with published * posts, plus the caller, whose own posts they can always edit. * * @return string[] */ private function author_candidates() { $names = wp_list_pluck( get_users( array( 'number' => 30, 'fields' => array('display_name'), 'orderby' => 'display_name', 'has_published_posts' => true, ) ), 'display_name' ); $me = wp_get_current_user(); if ( $me && $me->exists() && !in_array( $me->display_name, $names, true ) ) { $names[] = $me->display_name; } return array_values( array_filter( array_map( 'strval', $names ) ) ); } public function execute_update_image( $input ) { $input = (array) $input; $id = ( isset( $input['attachment_id'] ) ? absint( $input['attachment_id'] ) : 0 ); if ( !$id || !wp_attachment_is_image( $id ) ) { return new \WP_Error('invalid_attachment', __( 'That attachment is not an image in the Media Library.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } if ( !current_user_can( 'edit_post', $id ) ) { return new \WP_Error('rest_forbidden', __( 'You are not allowed to edit this image.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } $fields = array_intersect_key( $input, array_flip( array( 'title', 'alt', 'caption', 'description', 'filename' ) ) ); if ( !$fields ) { return new \WP_Error('nothing_to_change', __( 'Say what to change: title, alt, caption, description or filename.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $changed = array(); $updated = array(); // A new file name means a renamed copy, so nothing that links to the old file breaks. // Renaming is Pro; checked before anything changes so a Free call edits nothing. if ( isset( $fields['filename'] ) ) { $pro = $this->require_pro( __( 'Renaming images', 'ai-featured-image-generator' ) ); if ( true !== $pro ) { return $pro; } $copy = $this->rename_image_copy( $id, (string) $fields['filename'] ); if ( is_wp_error( $copy ) ) { return $copy; } $changed['filename'] = array( 'from' => wp_basename( (string) get_attached_file( $id ) ), 'to' => wp_basename( (string) get_attached_file( $copy['id'] ) ), ); $updated = $copy['updated_posts']; $still = $copy['still_referencing']; $old_id = $id; $id = $copy['id']; } $post = get_post( $id ); $data = array(); $map = array( 'title' => 'post_title', 'caption' => 'post_excerpt', 'description' => 'post_content', ); foreach ( $map as $key => $column ) { if ( !isset( $fields[$key] ) ) { continue; } $value = ( 'description' === $key ? wp_kses_post( (string) $fields[$key] ) : sanitize_text_field( (string) $fields[$key] ) ); if ( (string) $post->{$column} !== $value ) { $changed[$key] = array( 'from' => (string) $post->{$column}, 'to' => $value, ); $data[$column] = $value; } } if ( $data ) { $data['ID'] = $id; $result = wp_update_post( wp_slash( $data ), true ); if ( is_wp_error( $result ) ) { return $result; } } if ( isset( $fields['alt'] ) ) { $alt = sanitize_text_field( (string) $fields['alt'] ); $before = (string) get_post_meta( $id, '_wp_attachment_image_alt', true ); if ( $before !== $alt ) { update_post_meta( $id, '_wp_attachment_image_alt', $alt ); $changed['alt'] = array( 'from' => $before, 'to' => $alt, ); } } $out = array( 'changed' => (object) $changed, 'image' => $this->image_facts( $id ), ); if ( isset( $old_id ) ) { $out['old_attachment_id'] = $old_id; $out['updated_posts'] = $updated; $out['still_referencing'] = $still; $out['note'] = $this->repoint_note( $still, __( 'The old file is still in the Media Library in case anything outside this site links to it.', 'ai-featured-image-generator' ) ); } return $out; } public function execute_convert_image( $input ) { $input = (array) $input; return $this->pro_tool_error(); } /** * Copy an image under a new file name, carry its text and meta over, and * point every post that used the old one at the copy. * * @param int $id Attachment to copy. * @param string $name New file name without extension. * @return array|\WP_Error id, updated_posts, still_referencing */ private function rename_image_copy( $id, $name ) { return $this->pro_tool_error(); } /** * Add a file to the Media Library as a copy of an existing image (same title, * caption, description, alt and markers), then point every post that used the * old image at the copy: featured images and images inside the content. * * @param int $id Attachment being replaced. * @param string $file Temp file to add; it is deleted afterwards. * @param string $name File name for the copy, with extension. * @return array|\WP_Error id, updated_posts, still_referencing (posts that still use the old file) */ private function copy_image_and_repoint( $id, $file, $name ) { return $this->pro_tool_error(); } /** * The note after a copy: the old file stays, and which posts still use it. * * @param array $still Rows of posts that still use the old file. * @param string $kept Sentence saying the old file stays. * @return string */ private function repoint_note( $still, $kept ) { if ( !$still ) { return $kept; } return $kept . ' ' . sprintf( /* translators: %d: number of posts */ _n( '%d post still uses the old file and could not be changed (see still_referencing). Update it by hand before deleting the old image.', '%d posts still use the old file and could not be changed (see still_referencing). Update them by hand before deleting the old image.', count( $still ), 'ai-featured-image-generator' ), count( $still ) ); } /** * IDs of every post matching a query, read 200 at a time, with no overall cap. * * @param array $args WP_Query arguments. * @return int[] */ private function post_ids_paged( $args ) { $ids = array(); $page = 1; do { $query = new \WP_Query(array_merge( $args, array( 'fields' => 'ids', 'posts_per_page' => 200, 'paged' => $page, 'orderby' => 'ID', 'order' => 'ASC', 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'suppress_filters' => true, ) )); $batch = array_map( 'intval', $query->posts ); $ids = array_merge( $ids, $batch ); $page++; } while ( count( $batch ) === 200 ); return array_values( array_unique( $ids ) ); } /** * How content refers to an image's files, and where each one should point on the copy. * * Every file in the old image's metadata counts: the full file, the original before * WordPress scaled it, each size, plus any other "-WxH" size of the same name. They are * matched by their path inside the uploads folder, so http, https, another host or a * relative link all match. * * @param int $old_id Attachment being replaced. * @param int $new_id The copy. * @return array pattern (regex, group 1 is the uploads-relative path), map (lowercase * path => new URL), dims (WxH => new URL), full (new URL), needles (search words). */ private function file_references( $old_id, $new_id ) { $old_meta = wp_get_attachment_metadata( $old_id ); $old_meta = ( is_array( $old_meta ) ? $old_meta : array() ); $new_meta = wp_get_attachment_metadata( $new_id ); $new_meta = ( is_array( $new_meta ) ? $new_meta : array() ); $new_full = (string) wp_get_attachment_url( $new_id ); $new_dir = trailingslashit( dirname( $new_full ) ); $new_orig = ( function_exists( 'wp_get_original_image_url' ) ? (string) wp_get_original_image_url( $new_id ) : '' ); $new_orig = ( $new_orig !== '' ? $new_orig : $new_full ); $new_size = function ( $size ) use($new_meta, $new_dir, $new_full) { return ( !empty( $new_meta['sizes'][$size]['file'] ) ? $new_dir . $new_meta['sizes'][$size]['file'] : $new_full ); }; $dims = array(); foreach ( ( isset( $new_meta['sizes'] ) && is_array( $new_meta['sizes'] ) ? $new_meta['sizes'] : array() ) as $size ) { if ( !empty( $size['file'] ) && !empty( $size['width'] ) && !empty( $size['height'] ) ) { $dims[(int) $size['width'] . 'x' . (int) $size['height']] = $new_dir . $size['file']; } } $file = ( !empty( $old_meta['file'] ) ? (string) $old_meta['file'] : (string) get_post_meta( $old_id, '_wp_attached_file', true ) ); $dir = dirname( $file ); $dir = ( '.' === $dir || '' === $dir ? '' : trailingslashit( $dir ) ); $ext = (string) pathinfo( $file, PATHINFO_EXTENSION ); $stem = preg_replace( '/-scaled$/', '', (string) pathinfo( $file, PATHINFO_FILENAME ) ); $map = array(); $add = function ( $rel, $url ) use(&$map) { $key = strtolower( $rel ); if ( $rel !== '' && !isset( $map[$key] ) ) { $map[$key] = $url; } }; $add( $file, $new_full ); if ( !empty( $old_meta['original_image'] ) ) { $add( $dir . $old_meta['original_image'], $new_orig ); } if ( $ext !== '' ) { // A "-scaled" file without a recorded original still has the unscaled name in old links. $add( $dir . $stem . '.' . $ext, $new_orig ); } foreach ( ( isset( $old_meta['sizes'] ) && is_array( $old_meta['sizes'] ) ? $old_meta['sizes'] : array() ) as $size => $data ) { if ( !empty( $data['file'] ) ) { $add( $dir . $data['file'], $new_size( $size ) ); } } $alts = array_map( function ( $rel ) { return preg_quote( $rel, '#' ); }, array_keys( $map ) ); usort( $alts, function ( $a, $b ) { return strlen( $b ) - strlen( $a ); } ); if ( $ext !== '' && $stem !== '' ) { // Sizes that are no longer in the metadata, such as those of an older theme. $alts[] = preg_quote( $dir . $stem, '#' ) . '-\\d+x\\d+\\.' . preg_quote( $ext, '#' ); } $uploads = wp_get_upload_dir(); $base_path = untrailingslashit( (string) wp_parse_url( (string) $uploads['baseurl'], PHP_URL_PATH ) ); // Any scheme, host and leading path (a CDN folder, a subsite), then the uploads path. $pattern = ( $alts ? '#(?:(?:https?:)?//[^\\s"\'<>()]*?)?' . preg_quote( $base_path . '/', '#' ) . '(' . implode( '|', $alts ) . ')(?![\\w.-])#i' : '' ); $needles = array('wp-image-' . (int) $old_id, '"id":' . (int) $old_id); if ( $stem !== '' ) { $needles[] = wp_basename( $stem ); } return array( 'pattern' => $pattern, 'map' => $map, 'dims' => $dims, 'full' => $new_full, 'needles' => $needles, ); } /** * Whether content still uses an image: its wp-image class or one of its files. * * @param string $content Post content. * @param int $id Attachment. * @param string $pattern file_references() pattern, may be empty. * @return bool */ private function mentions_image( $content, $id, $pattern ) { if ( preg_match( '/\\bwp-image-' . (int) $id . '\\b/', $content ) ) { return true; } return $pattern !== '' && (bool) preg_match( $pattern, $content ); } /** * Point content at the copy: file links (each size onto the same size of the copy, * else its full file), the wp-image class and block "id" attributes. * * @param string $content Post content. * @param int $old_id Attachment being replaced. * @param int $new_id The copy. * @param array $refs file_references() result. * @return string */ private function repoint_content( $content, $old_id, $new_id, $refs ) { if ( $refs['pattern'] !== '' ) { $content = preg_replace_callback( $refs['pattern'], function ( $m ) use($refs) { $key = strtolower( $m[1] ); if ( isset( $refs['map'][$key] ) ) { return $refs['map'][$key]; } if ( preg_match( '/-(\\d+x\\d+)\\.[a-z0-9]+$/i', $m[1], $d ) && isset( $refs['dims'][$d[1]] ) ) { return $refs['dims'][$d[1]]; } return $refs['full']; }, $content ); } $content = preg_replace( '/\\bwp-image-' . (int) $old_id . '\\b/', 'wp-image-' . (int) $new_id, $content ); return preg_replace( '/("id":\\s*)' . (int) $old_id . '\\b/', '${1}' . (int) $new_id, $content ); } /* --------------------------------------------------------------------- * Content helpers (Pro tools only) * ------------------------------------------------------------------ */ /** * Core image block markup for an attachment. * * @param int $attachment_id Attachment. * @param string $alt Alt text. * @param string $caption Caption, may be empty. * @return string Empty string on a build without the Pro tools. */ private function build_image_block( $attachment_id, $alt, $caption ) { return ''; } /** * Insert a block after the Nth paragraph. * * Block content: counts only top-level paragraph blocks (not paragraphs inside * quotes, groups or columns) and splices the new block in right after the Nth * one's closing comment, so every other byte of the post stays as it was. * Classic content: counts closing

tags. * * @param string $content Post content. * @param string $block Block markup to insert. * @param int $index 1-based paragraph number. * @return string|null Null when there are fewer paragraphs. */ private function insert_after_paragraph( $content, $block, $index ) { return null; } /** * @param string $content Post content. * @return int Paragraphs that insert_after_paragraph() can target. */ private function count_paragraphs( $content ) { return count( $this->paragraph_end_offsets( $content ) ); } /** * Byte offsets just past the end of each paragraph, in order. * * Block content: the end of the closing comment of each top-level core/paragraph * block, found with the same delimiter pattern as the core block parser. * Classic content: the end of each

tag. * * @param string $content Post content. * @return int[] */ private function paragraph_end_offsets( $content ) { $ends = array(); if ( !has_blocks( $content ) ) { if ( preg_match_all( '##i', $content, $tags, PREG_OFFSET_CAPTURE ) ) { foreach ( $tags[0] as $tag ) { $ends[] = $tag[1] + strlen( $tag[0] ); } } return $ends; } // Delimiter pattern from WP_Block_Parser::next_token(), with the curly // braces written as \x7B and \x7D so the build tools see balanced code. $pattern = '/).)*+)?\\x7D\\s+)?(?P\\/)?-->/s'; if ( !preg_match_all( $pattern, $content, $tokens, PREG_SET_ORDER | PREG_OFFSET_CAPTURE ) ) { return $ends; } $depth = 0; $top = ''; foreach ( $tokens as $token ) { $namespace = ( isset( $token['namespace'] ) && $token['namespace'][1] !== -1 && $token['namespace'][0] !== '' ? $token['namespace'][0] : 'core/' ); $name = $namespace . $token['name'][0]; $is_closer = isset( $token['closer'] ) && $token['closer'][1] !== -1 && $token['closer'][0] !== ''; $is_void = isset( $token['void'] ) && $token['void'][1] !== -1 && $token['void'][0] !== ''; if ( $is_closer ) { if ( $depth > 0 ) { $depth--; if ( 0 === $depth && 'core/paragraph' === $top && 'core/paragraph' === $name ) { $ends[] = $token[0][1] + strlen( $token[0][0] ); } } continue; } if ( $is_void ) { continue; } if ( 0 === $depth ) { $top = $name; } $depth++; } return $ends; } }