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- 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