'openai', 'gpt-image-2.6-flare' => 'openai', 'gpt-image-2.6-sunburst' => 'openai', 'gemini-nano-banana-2.1' => 'gemini', 'gemini-3-pro-image' => 'gemini', ); const SIZES = array( '1:1', '3:2', '2:3', '4:3', '3:4', '16:9', '9:16' ); const GUARD = 'Keep the product exactly as shown: same shape, colours, materials, logo and details. Change only the background, lighting and scene.'; const TAIL = 'no text, no captions, no words, no letters, no writing'; const SET_MAX = 6; const MIN_EDGE = 800; const LOCK_TTL = 900; const META_ORIGINAL_IMAGE = '_aifi_product_original_image'; const META_ORIGINAL_GALLERY = '_aifi_product_original_gallery'; const META_GENERATED = '_aifi_product_generated'; const META_SOURCE = '_aifi_product_source'; const META_OF = '_aifi_product_of'; const META_MODE = '_aifi_generated_mode'; /** * Settings. * * @var Settings */ private $settings; /** * Generator. * * @var Generator */ private $generator; /** * Lock values this request holds, by product ID. * * @var string[] */ private static $locks = array(); /** * Constructor. * * @param Settings $settings Settings. * @param Generator $generator Generator. */ public function __construct( Settings $settings, Generator $generator ) { $this->settings = $settings; $this->generator = $generator; } /** * The generator (used by Product_Unify for the expected image shape). * * @return Generator */ public function generator() { return $this->generator; } /** * The post meta box, whose "Listen to this post" section the product box reuses. * * @var Meta_Box|null */ private $meta_box = null; /** * Share the post meta box so products ticked on the Audio tab get the audio section. * * @param Meta_Box $meta_box Meta box. */ public function set_meta_box( Meta_Box $meta_box ) { $this->meta_box = $meta_box; } /** * Hooks. */ public function register_hooks() { add_action( 'rest_api_init', array($this, 'register_routes') ); add_action( 'add_meta_boxes', array($this, 'add_meta_box') ); add_action( 'admin_enqueue_scripts', array($this, 'enqueue_product_screen') ); } /* --------------------------------------------------------------------- * Licence and locks * ------------------------------------------------------------------ */ /** * The upgrade message. * * @return \WP_Error */ private function premium_error() { return new \WP_Error('premium_required', __( 'Product Images is a Pro feature. Please upgrade to use it.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } /** * Options row that holds a product's lock. * * @param int $product_id Product. * @return string */ public static function lock_name( $product_id ) { return 'aifi_lock_product_' . (int) $product_id; } /** * The stored lock value (token|expiry), read past every cache. * * @param string $name Option name. * @return string|null Null when nobody holds the lock. */ private static function lock_value( $name ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $value = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $name ) ); return ( null === $value ? null : (string) $value ); } /** * Expiry time of a lock value. A value in an unknown shape counts as expired. * * @param string $value token|expiry. * @return int */ private static function lock_expiry( $value ) { $parts = explode( '|', (string) $value ); return ( isset( $parts[1] ) ? (int) $parts[1] : 0 ); } /** * Take the per-product lock. * * The lock is one options row created with INSERT IGNORE, so only one request can create * it. It holds an owner token and an expiry. A lock past its expiry is taken over with a * compare-and-swap on the old value, so two requests cannot both take it over. * * @param int $product_id Product. * @return true|\WP_Error */ public function lock( $product_id ) { global $wpdb; $product_id = (int) $product_id; $name = self::lock_name( $product_id ); $value = wp_generate_password( 20, false ) . '|' . (time() + self::LOCK_TTL); $taken = false; for ($try = 0; $try < 2 && !$taken; $try++) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $taken = (bool) $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", $name, $value ) ); if ( $taken ) { break; } $held = self::lock_value( $name ); if ( null === $held ) { continue; // Released in between: try to create it once more. } if ( self::lock_expiry( $held ) < time() ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $taken = (bool) $wpdb->update( $wpdb->options, array( 'option_value' => $value, ), array( 'option_name' => $name, 'option_value' => $held, ) ); } break; } if ( !$taken ) { return new \WP_Error('product_busy', __( 'This product is already being processed. Try again in a few seconds.', 'ai-featured-image-generator' ), array( 'status' => 429, )); } // A request that dies (time limit, fatal error) skips every finally block; release its // locks at shutdown so the product is not stuck as busy for the whole lock time. if ( !self::$locks ) { register_shutdown_function( array($this, 'unlock_all') ); } self::$locks[$product_id] = $value; return true; } /** * Release every lock this request still holds (shutdown safety net). */ public function unlock_all() { foreach ( array_keys( self::$locks ) as $product_id ) { $this->unlock( $product_id ); } } /** * Push the lock's expiry forward. Does nothing unless this request holds the lock. * * @param int $product_id Product. * @return bool True when this request still holds the lock. */ public function touch_lock( $product_id ) { global $wpdb; $product_id = (int) $product_id; if ( !isset( self::$locks[$product_id] ) ) { return false; } $old = self::$locks[$product_id]; $parts = explode( '|', $old ); $value = $parts[0] . '|' . (time() + self::LOCK_TTL); if ( $value === $old ) { return self::lock_value( self::lock_name( $product_id ) ) === $old; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching if ( $wpdb->update( $wpdb->options, array( 'option_value' => $value, ), array( 'option_name' => self::lock_name( $product_id ), 'option_value' => $old, ) ) ) { self::$locks[$product_id] = $value; return true; } return false; } /** * Release the per-product lock, only when this request still owns it. * * @param int $product_id Product. */ public function unlock( $product_id ) { global $wpdb; $product_id = (int) $product_id; if ( !isset( self::$locks[$product_id] ) ) { return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->delete( $wpdb->options, array( 'option_name' => self::lock_name( $product_id ), 'option_value' => self::$locks[$product_id], ) ); unset(self::$locks[$product_id]); } /** * Give a long request more time and memory, where the host allows it. * * @param int $seconds Seconds from now. */ public static function allow_long_run( $seconds = 600 ) { if ( function_exists( 'wp_raise_memory_limit' ) ) { wp_raise_memory_limit( 'admin' ); } if ( function_exists( 'set_time_limit' ) ) { @set_time_limit( (int) $seconds ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Squiz.PHP.DiscouragedFunctions.Discouraged } } /** * A product title as plain text (no HTML entities), for scripts that print it with text(). * * @param int $product_id Product. * @return string */ public static function plain_title( $product_id ) { return html_entity_decode( wp_strip_all_tags( (string) get_the_title( $product_id ) ), ENT_QUOTES, 'UTF-8' ); } /** * WooCommerce (or the test stand-in) is present. * * @return true|\WP_Error */ public function require_products() { if ( !post_type_exists( 'product' ) ) { return new \WP_Error('product_no_woocommerce', __( 'WooCommerce is not active.', 'ai-featured-image-generator' ), array( 'status' => 404, )); } return true; } /** * A product the plugin may change: a parent product, never a variation. * * @param int $product_id Product. * @return \WP_Post|\WP_Error */ public function get_product_post( $product_id ) { $post = get_post( (int) $product_id ); if ( $post && 'product_variation' === $post->post_type ) { return new \WP_Error('product_variation', __( 'Product images work on the main product, not on variations.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } if ( !$post || 'product' !== $post->post_type ) { return new \WP_Error('invalid_product', __( 'No product with that ID exists.', 'ai-featured-image-generator' ), array( 'status' => 404, )); } if ( 'trash' === $post->post_status ) { return new \WP_Error('product_in_trash', __( 'This product is in the trash. Restore it first.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } if ( 'auto-draft' === $post->post_status ) { return new \WP_Error('product_not_saved', __( 'Save the product once before making images.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } return $post; } /* --------------------------------------------------------------------- * WooCommerce helpers (CRUD when WooCommerce runs, raw meta otherwise) * ------------------------------------------------------------------ */ /** * WooCommerce product object, when WooCommerce is loaded. * * @param int $product_id Product. * @return \WC_Product|null */ private function wc( $product_id ) { if ( class_exists( 'WooCommerce' ) && function_exists( 'wc_get_product' ) ) { $p = wc_get_product( (int) $product_id ); return ( $p ? $p : null ); } return null; } /** * Main image ID. * * @param int $product_id Product. * @return int */ public function get_main_id( $product_id ) { $p = $this->wc( $product_id ); return ( $p ? (int) $p->get_image_id() : (int) get_post_meta( $product_id, '_thumbnail_id', true ) ); } /** * Gallery image IDs. * * @param int $product_id Product. * @return int[] */ public function get_gallery_ids( $product_id ) { $p = $this->wc( $product_id ); if ( $p ) { return array_values( array_map( 'intval', $p->get_gallery_image_ids() ) ); } $raw = (string) get_post_meta( $product_id, '_product_image_gallery', true ); return array_values( array_filter( array_map( 'intval', explode( ',', $raw ) ) ) ); } /** * Save the main image and gallery. * * @param int $product_id Product. * @param int $main_id Main image (0 for none). * @param int[] $gallery Gallery images. */ private function save_images( $product_id, $main_id, array $gallery ) { $gallery = array_values( array_unique( array_filter( array_map( 'intval', $gallery ) ) ) ); $gallery = array_values( array_diff( $gallery, array((int) $main_id) ) ); $p = $this->wc( $product_id ); if ( $p ) { $p->set_image_id( (int) $main_id ); $p->set_gallery_image_ids( $gallery ); $p->save(); return; } if ( $main_id ) { update_post_meta( $product_id, '_thumbnail_id', (int) $main_id ); } else { delete_post_meta( $product_id, '_thumbnail_id' ); } update_post_meta( $product_id, '_product_image_gallery', implode( ',', $gallery ) ); } /** * Keep the product's images from before AIFIG first changed them (only once). * * @param int $product_id Product. */ public function remember_originals( $product_id ) { if ( !metadata_exists( 'post', $product_id, self::META_ORIGINAL_IMAGE ) ) { update_post_meta( $product_id, self::META_ORIGINAL_IMAGE, $this->get_main_id( $product_id ) ); update_post_meta( $product_id, self::META_ORIGINAL_GALLERY, $this->get_gallery_ids( $product_id ) ); } } /** * Note an image AIFIG put on the product. * * @param int $product_id Product. * @param int $new_id New image. * @param int $from_id Image it replaced (0 when added). * @param string $role main or gallery. */ private function record_generated( $product_id, $new_id, $from_id, $role ) { $list = get_post_meta( $product_id, self::META_GENERATED, true ); $list = ( is_array( $list ) ? $list : array() ); $list[] = array( 'id' => (int) $new_id, 'from' => (int) $from_id, 'role' => $role, 'mode' => (string) get_post_meta( $new_id, self::META_MODE, true ), 'time' => time(), ); update_post_meta( $product_id, self::META_GENERATED, $list ); } /** * Make an image the main image. * * @param int $product_id Product. * @param int $new_id Image. */ public function set_main( $product_id, $new_id ) { $this->remember_originals( $product_id ); $old = $this->get_main_id( $product_id ); $this->save_images( $product_id, $new_id, $this->get_gallery_ids( $product_id ) ); $this->record_generated( $product_id, $new_id, $old, 'main' ); } /** * Put images at the front of the gallery (or at a position), keeping the ones already there. * * @param int $product_id Product. * @param int[] $ids Images, in order. * @param int $at Gallery position to insert at (0 = the front). */ public function add_to_gallery( $product_id, array $ids, $at = 0 ) { $this->remember_originals( $product_id ); $ids = array_values( array_map( 'intval', $ids ) ); $gallery = array_values( array_diff( $this->get_gallery_ids( $product_id ), $ids ) ); array_splice( $gallery, max( 0, min( count( $gallery ), (int) $at ) ), 0, $ids ); $this->save_images( $product_id, $this->get_main_id( $product_id ), $gallery ); foreach ( $ids as $id ) { $this->record_generated( $product_id, $id, 0, 'gallery' ); } } /** * Swap one of the product's images for a new one, in the same place. * * @param int $product_id Product. * @param int $target_id Image to replace (main or gallery). * @param int $new_id New image. * @return true|\WP_Error */ public function replace_image( $product_id, $target_id, $new_id ) { $main = $this->get_main_id( $product_id ); $gallery = $this->get_gallery_ids( $product_id ); if ( (int) $target_id === $main ) { $this->remember_originals( $product_id ); $this->save_images( $product_id, $new_id, $gallery ); $this->record_generated( $product_id, $new_id, $target_id, 'main' ); return true; } $pos = array_search( (int) $target_id, $gallery, true ); if ( false === $pos ) { return new \WP_Error('not_on_product', __( 'That image is not on this product any more.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $this->remember_originals( $product_id ); $gallery[$pos] = (int) $new_id; $this->save_images( $product_id, $main, $gallery ); $this->record_generated( $product_id, $new_id, $target_id, 'gallery' ); return true; } /** * Put the original images back. Generated files stay in the Media Library. * * @param int $product_id Product. * @return array array( 'restored' => bool, 'missing' => int[] ). */ public function restore( $product_id ) { if ( !metadata_exists( 'post', $product_id, self::META_ORIGINAL_IMAGE ) ) { return array( 'restored' => false, 'missing' => array(), ); } $main = (int) get_post_meta( $product_id, self::META_ORIGINAL_IMAGE, true ); $gallery = get_post_meta( $product_id, self::META_ORIGINAL_GALLERY, true ); $gallery = ( is_array( $gallery ) ? array_map( 'intval', $gallery ) : array() ); $missing = array(); if ( $main && !wp_attachment_is_image( $main ) ) { $missing[] = $main; $main = 0; } $keep = array(); foreach ( $gallery as $id ) { if ( wp_attachment_is_image( $id ) ) { $keep[] = $id; } else { $missing[] = $id; } } $this->save_images( $product_id, $main, $keep ); delete_post_meta( $product_id, self::META_ORIGINAL_IMAGE ); delete_post_meta( $product_id, self::META_ORIGINAL_GALLERY ); delete_post_meta( $product_id, self::META_GENERATED ); return array( 'restored' => true, 'missing' => $missing, ); } /** * The product has no photo to start from. * * @param int $product_id Product. * @return bool */ public function needs_photo( $product_id ) { return 0 === $this->pick_source( $product_id ); } /** * Whether an attachment is an image whose file is still on disk. * * @param int $id Attachment. * @return bool */ private static function usable_photo( $id ) { return $id && wp_attachment_is_image( $id ) && file_exists( (string) get_attached_file( $id ) ); } /** * The photo to start from, so a redo never starts from an AI image: the current main * image when it is a real photo (not one this plugin made, so a photo the owner uploaded * later wins), else the original main image kept before the plugin changed it, else the * photo the current main image was made from, else the first gallery image. * * @param int $product_id Product. * @return int 0 when the product has no usable photo. */ public function pick_source( $product_id ) { $main = $this->get_main_id( $product_id ); $real = $main && !get_post_meta( $main, self::META_OF, true ) && !get_post_meta( $main, self::META_MODE, true ); $ids = array( ( $real ? $main : 0 ), (int) get_post_meta( $product_id, self::META_ORIGINAL_IMAGE, true ), ( $main ? (int) get_post_meta( $main, self::META_SOURCE, true ) : 0 ), $main ); foreach ( array_merge( $ids, $this->get_gallery_ids( $product_id ) ) as $id ) { if ( self::usable_photo( $id ) ) { return (int) $id; } } return 0; } /** * Whether a photo belongs to this product: on it now, kept as an original, or the photo * one of its current images was made from. * * @param int $product_id Product. * @param int $id Attachment. * @return bool */ public function is_product_photo( $product_id, $id ) { $id = (int) $id; $current = array_merge( array($this->get_main_id( $product_id )), $this->get_gallery_ids( $product_id ) ); if ( in_array( $id, $current, true ) ) { return true; } $original = get_post_meta( $product_id, self::META_ORIGINAL_GALLERY, true ); $known = array_merge( array((int) get_post_meta( $product_id, self::META_ORIGINAL_IMAGE, true )), ( is_array( $original ) ? array_map( 'intval', $original ) : array() ) ); foreach ( $current as $cid ) { if ( $cid ) { $known[] = (int) get_post_meta( $cid, self::META_SOURCE, true ); } } return in_array( $id, $known, true ); } /** * The product's images and whether originals are kept. * * @param int $product_id Product. * @return array */ public function state( $product_id ) { return array( 'main_id' => $this->get_main_id( $product_id ), 'gallery_ids' => $this->get_gallery_ids( $product_id ), 'has_originals' => metadata_exists( 'post', $product_id, self::META_ORIGINAL_IMAGE ), ); } /* --------------------------------------------------------------------- * Making an image * ------------------------------------------------------------------ */ /** * Make one store image from a product photo. Never changes the product. * * @param int $product_id Product. * @param int $source_id Photo (0 = pick_source). * @param array $opts mode, background, background_hex, style, extra_prompt, size, add_logo. * @return array|\WP_Error attachment_id, url, thumb, width, height, provider, model, mode, background, source_id, notes. */ public function generate( $product_id, $source_id = 0, $opts = array() ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * The body of generate(), reached only from Pro code. * * @param int $product_id Product. * @param int $source_id Photo. * @param array $opts Options for this image; missing ones come from the settings. * @return array|\WP_Error */ private function make_image( $product_id, $source_id, array $opts ) { $product = $this->get_product_post( $product_id ); if ( is_wp_error( $product ) ) { return $product; } if ( $source_id ) { $ok = self::usable_photo( $source_id ); $on = $this->is_product_photo( $product_id, $source_id ); if ( !$ok || !$on && !current_user_can( 'edit_post', $source_id ) ) { return new \WP_Error('invalid_source', __( 'That photo cannot be used for this product.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } } else { $source_id = $this->pick_source( $product_id ); if ( !$source_id ) { return new \WP_Error('product_needs_photo', __( 'Add a product photo first.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } } $saved = $this->options(); $settings = $this->settings->get_settings(); $pick = function ( $key, $setting, array $allowed ) use($opts, $saved) { if ( isset( $opts[$key] ) && in_array( $opts[$key], $allowed, true ) ) { return $opts[$key]; } return ( in_array( $saved[$setting], $allowed, true ) ? $saved[$setting] : $allowed[0] ); }; $mode = $pick( 'mode', 'product_mode', self::MODES ); $size = $pick( 'size', 'product_size', self::SIZES ); $bg = $pick( 'background', 'product_background', self::BACKGROUNDS ); if ( !in_array( $mode, self::PLAIN_MODES, true ) ) { // Showroom and Lifestyle are real places: the background choice does not apply. $bg = 'white'; } $model = $this->resolve_model(); if ( is_wp_error( $model ) ) { return $model; } $provider = self::MODELS[$model]; $this->generator->reset_notes(); // Transparent: decided before any request. $native = false; if ( 'transparent' === $bg ) { if ( 'openai' === $provider ) { if ( !Settings::is_gpt25_model( $model ) ) { $model = 'gpt-image-2.6-flare'; $this->generator->note( __( 'Switched to GPT Image 2.6 Flare for the transparent background.', 'ai-featured-image-generator' ) ); } $native = true; } elseif ( Providers::has_api_key( $settings, 'openai' ) ) { $provider = 'openai'; $model = 'gpt-image-2.6-flare'; $native = true; $this->generator->note( __( 'Switched to GPT Image 2.6 Flare for the transparent background.', 'ai-featured-image-generator' ) ); } else { return new \WP_Error('transparent_needs_key', __( 'A transparent background needs an OpenAI key.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } } $built = self::build_prompt( array( 'mode' => $mode, 'background' => $bg, 'background_hex' => ( isset( $opts['background_hex'] ) ? $opts['background_hex'] : $saved['product_background_hex'] ), 'style' => $pick( 'style', 'product_style', self::STYLES ), 'extra_prompt' => ( isset( $opts['extra_prompt'] ) ? self::limit_text( $opts['extra_prompt'], 300 ) : '' ), ), $provider, $native ); foreach ( $built['notes'] as $note ) { $this->generator->note( $note ); } $overrides = array( 'ai_provider' => $provider, 'ai_model' => $model, 'aspect_ratio' => $size, 'transparent' => $native, ); // A drawn checkerboard only matters when a transparent background was asked for; a // tiled floor or a gingham cloth on a solid background is a real scene. $temp = ''; for ($try = 0; $try < 2; $try++) { $temp = $this->generator->generate_from_reference( $source_id, $built['prompt'], $overrides ); if ( is_wp_error( $temp ) ) { return $temp; } $this->touch_lock( $product_id ); if ( 'transparent' !== $bg || !Image_Pixels::looks_like_checkerboard( $temp ) ) { break; } wp_delete_file( $temp ); $temp = ''; } if ( '' === $temp ) { return new \WP_Error('fake_checkerboard', __( 'The image came back with a drawn checkerboard instead of a real transparent background, so it was not saved. Try again or choose a solid background.', 'ai-featured-image-generator' ), array( 'status' => 502, )); } $add_logo = ( isset( $opts['add_logo'] ) ? !empty( $opts['add_logo'] ) : !empty( $saved['product_add_logo'] ) ); $save_settings = $settings; $save_settings['ai_provider'] = $provider; $save_settings['ai_model'] = $model; $save_settings['aifi_apply_brand_logo'] = $add_logo && $this->generator->brand_kit()->has_logo(); if ( 'transparent' === $bg ) { // Keep the alpha channel: the site's WebP choice stays WebP, anything else becomes PNG. foreach ( array('output_format', 'gemini_output_format') as $format_key ) { if ( !isset( $save_settings[$format_key] ) || 'webp' !== $save_settings[$format_key] ) { $save_settings[$format_key] = 'png'; } } } $title = self::plain_title( $product_id ); $attachment_id = $this->generator->save_generated_file( $temp, $product_id, $title . '-' . $mode, $save_settings ); if ( is_wp_error( $attachment_id ) ) { return $attachment_id; } $this->touch_lock( $product_id ); $alt = $this->generator->build_alt_text( array( 'title' => $title, 'prompt' => $title, 'style' => '', ) ); update_post_meta( $attachment_id, '_wp_attachment_image_alt', ( '' !== $alt ? $alt : $title ) ); update_post_meta( $attachment_id, self::META_SOURCE, $source_id ); update_post_meta( $attachment_id, self::META_OF, $product_id ); update_post_meta( $attachment_id, self::META_MODE, $mode ); /** * After a product image is made (it is not on the product yet). * * @param int $attachment_id New image. * @param int $product_id Product. * @param string $mode studio, showroom, lifestyle or 3d. */ do_action( 'aifi_after_product_image', $attachment_id, $product_id, $mode ); $meta = wp_get_attachment_metadata( $attachment_id ); return array( 'attachment_id' => (int) $attachment_id, 'url' => (string) wp_get_attachment_url( $attachment_id ), 'thumb' => (string) wp_get_attachment_image_url( $attachment_id, 'medium' ), 'width' => ( is_array( $meta ) ? (int) ($meta['width'] ?? 0) : 0 ), 'height' => ( is_array( $meta ) ? (int) ($meta['height'] ?? 0) : 0 ), 'provider' => $provider, 'model' => $model, 'mode' => $mode, 'background' => $bg, 'source_id' => $source_id, 'notes' => $this->generator->get_last_notes(), ); } /** * Default settings for the Product Images tab. * * @return array */ public static function defaults() { return array( 'product_background' => 'white', 'product_background_hex' => '#ffffff', 'product_mode' => 'studio', 'product_style' => 'clean_studio', 'product_model' => 'gpt-image-2.6-flare', 'product_size' => '1:1', 'product_add_logo' => 0, 'product_set_count' => 3, 'product_set_modes' => array('studio', 'showroom', 'lifestyle'), ); } /** * Saved Product Images settings merged over the defaults. * * @param array|null $settings Plugin settings, or null to read them. * @return array */ public function options( $settings = null ) { $settings = ( is_array( $settings ) ? $settings : $this->settings->get_settings() ); $out = array(); foreach ( self::defaults() as $key => $default ) { $out[$key] = ( array_key_exists( $key, $settings ) ? $settings[$key] : $default ); } return $out; } /** * Clean the Product Images settings from a form save. * * @param array $input Submitted values. * @param array $sanitized Settings being saved (other tabs' values kept). * @return array The sanitized settings with the Product Images keys set. */ public static function sanitize( array $input, array $sanitized ) { $d = self::defaults(); $pick = function ( $key, array $allowed ) use($input, $d) { return ( isset( $input[$key] ) && in_array( $input[$key], $allowed, true ) ? $input[$key] : $d[$key] ); }; $sanitized['product_background'] = $pick( 'product_background', self::BACKGROUNDS ); $hex = Settings::normalize_brand_colors( array(( isset( $input['product_background_hex'] ) ? (string) $input['product_background_hex'] : '' )) ); $sanitized['product_background_hex'] = ( $hex ? $hex[0] : $d['product_background_hex'] ); $sanitized['product_mode'] = $pick( 'product_mode', self::MODES ); $sanitized['product_style'] = $pick( 'product_style', self::STYLES ); $sanitized['product_model'] = $pick( 'product_model', array_keys( self::MODELS ) ); $sanitized['product_size'] = $pick( 'product_size', self::SIZES ); $sanitized['product_add_logo'] = ( !empty( $input['product_add_logo'] ) ? 1 : 0 ); $count = ( isset( $input['product_set_count'] ) ? (int) $input['product_set_count'] : $d['product_set_count'] ); $sanitized['product_set_count'] = max( 1, min( self::SET_MAX, $count ) ); $sanitized['product_set_modes'] = self::normalize_set_modes( ( isset( $input['product_set_modes'] ) && is_array( $input['product_set_modes'] ) ? $input['product_set_modes'] : $d['product_set_modes'] ), $sanitized['product_set_count'] ); return $sanitized; } /** * Plain text cut to a length. * * @param mixed $value Value. * @param int $max Characters. * @return string */ private static function limit_text( $value, $max ) { $text = sanitize_text_field( (string) $value ); return ( function_exists( 'mb_substr' ) ? mb_substr( $text, 0, $max ) : substr( $text, 0, $max ) ); } /** * Modes for a product set: known modes only, slot 1 always studio, padded with studio or cut to the count. * * @param array $modes Modes. * @param int $count Images in the set. * @return string[] */ public static function normalize_set_modes( array $modes, $count ) { $count = max( 1, min( self::SET_MAX, (int) $count ) ); $clean = array(); foreach ( array_values( $modes ) as $mode ) { $clean[] = ( in_array( $mode, self::MODES, true ) ? $mode : 'studio' ); } // The first slot is the main image. It starts on Studio (what Google Shopping and Amazon // want) but the shop owner may choose another type of shot. return array_slice( array_pad( $clean, $count, 'studio' ), 0, $count ); } /** * The type of shot for main images: the first slot of the product set. Used by product sets, * bulk and Unify, so the main image follows one choice everywhere. * * @return string */ public function main_mode() { $o = $this->options(); $modes = self::normalize_set_modes( (array) $o['product_set_modes'], 1 ); return $modes[0]; } /** * The slots of a product set: the first is the main image, the rest go to the gallery. * * @param int|null $count Images (default: setting). * @param array|null $modes Modes (default: setting). * @return array[] Each array( 'role' => main|gallery, 'mode' => string ). */ public function set_plan( $count = null, $modes = null ) { $o = $this->options(); $count = ( null === $count ? (int) $o['product_set_count'] : (int) $count ); $modes = self::normalize_set_modes( ( is_array( $modes ) ? $modes : (array) $o['product_set_modes'] ), $count ); $plan = array(); foreach ( $modes as $i => $mode ) { $plan[] = array( 'role' => ( 0 === $i ? 'main' : 'gallery' ), 'mode' => $mode, ); } return $plan; } /** * Labels for every option list, for the settings tab, the product box and the assistant. * * @return array */ public static function labels() { return array( 'backgrounds' => array( 'white' => __( 'White', 'ai-featured-image-generator' ), 'light_grey' => __( 'Light grey', 'ai-featured-image-generator' ), 'beige' => __( 'Beige', 'ai-featured-image-generator' ), 'custom' => __( 'Custom colour', 'ai-featured-image-generator' ), 'transparent' => __( 'Transparent (no background)', 'ai-featured-image-generator' ), ), 'modes' => array( 'studio' => __( 'Studio', 'ai-featured-image-generator' ), 'showroom' => __( 'Showroom', 'ai-featured-image-generator' ), 'lifestyle' => __( 'Lifestyle', 'ai-featured-image-generator' ), '3d' => __( '3D', 'ai-featured-image-generator' ), ), 'styles' => array( 'clean_studio' => __( 'Clean', 'ai-featured-image-generator' ), 'premium' => __( 'Premium', 'ai-featured-image-generator' ), 'natural_light' => __( 'Soft daylight', 'ai-featured-image-generator' ), 'dramatic' => __( 'Dramatic', 'ai-featured-image-generator' ), 'minimal' => __( 'Minimal', 'ai-featured-image-generator' ), 'cinematic' => __( 'Cinematic', 'ai-featured-image-generator' ), ), 'sizes' => array( '1:1' => __( 'Square 1:1', 'ai-featured-image-generator' ), '3:2' => __( 'Landscape 3:2', 'ai-featured-image-generator' ), '2:3' => __( 'Portrait 2:3', 'ai-featured-image-generator' ), '4:3' => __( 'Landscape 4:3', 'ai-featured-image-generator' ), '3:4' => __( 'Portrait 3:4', 'ai-featured-image-generator' ), '16:9' => __( 'Wide 16:9', 'ai-featured-image-generator' ), '9:16' => __( 'Tall 9:16', 'ai-featured-image-generator' ), ), 'models' => self::model_labels(), ); } /** * Model labels from the provider registry. * * @return array slug => label. */ public static function model_labels() { $out = array(); foreach ( self::MODELS as $slug => $provider ) { $models = Providers::image_models( $provider ); $out[$slug] = ( isset( $models[$slug] ) ? $models[$slug] : $slug ); } return $out; } /** * Build the prompt. Sentences in a fixed order, the guard first. * * The background only applies to Studio and 3D shots; Showroom and Lifestyle are real * places, so a plain background sentence would contradict them. Studio and 3D shots get a * soft natural shadow unless the background is transparent. Lifestyle lets the model pick * a setting that suits the product, unless the extra words name one. * * @param array $opts mode, background, background_hex, style, extra_prompt. * @param string $provider openai or gemini. * @param bool $native_transparent True when the model makes the transparent background itself. * @return array array( 'prompt' => string, 'notes' => string[] ). */ public static function build_prompt( array $opts, $provider, $native_transparent = false ) { $mode = ( isset( $opts['mode'] ) && in_array( $opts['mode'], self::MODES, true ) ? $opts['mode'] : 'studio' ); $background = ( isset( $opts['background'] ) && in_array( $opts['background'], self::BACKGROUNDS, true ) ? $opts['background'] : 'white' ); $style = ( isset( $opts['style'] ) && in_array( $opts['style'], self::STYLES, true ) ? $opts['style'] : 'clean_studio' ); $parts = array(self::GUARD); $mode_text = array( 'studio' => 'Professional studio product photograph, product centred, sharp focus.', 'showroom' => 'Product displayed in an elegant showroom setting with depth.', 'lifestyle' => 'Product in a realistic lifestyle setting, in use, natural composition.', '3d' => 'Clean 3D product render look, crisp edges, neutral environment.', ); $parts[] = $mode_text[$mode]; if ( in_array( $mode, self::PLAIN_MODES, true ) ) { $white = 'On a plain pure white background.'; switch ( $background ) { case 'light_grey': $parts[] = 'On a plain light grey background (#e5e5e5).'; break; case 'beige': $parts[] = 'On a plain warm beige background (#f1e7d8).'; break; case 'custom': $hex = Settings::normalize_brand_colors( array(( isset( $opts['background_hex'] ) ? (string) $opts['background_hex'] : '' )) ); $parts[] = sprintf( 'On a plain solid background coloured %s.', ( $hex ? $hex[0] : '#ffffff' ) ); break; case 'transparent': $parts[] = ( 'openai' === $provider && $native_transparent ? 'Isolated product, no background.' : $white ); break; default: $parts[] = $white; } if ( 'transparent' !== $background ) { $parts[] = 'With a soft natural drop shadow.'; } } elseif ( 'lifestyle' === $mode ) { $parts[] = 'Set in a realistic everyday setting that suits this product and how it is used.'; } $style_text = array( 'clean_studio' => 'Clean, bright e-commerce look.', 'premium' => 'Premium, luxurious look with refined lighting.', 'natural_light' => 'Soft natural daylight.', 'dramatic' => 'Dramatic contrast with deep shadows.', 'minimal' => 'Minimal composition with lots of empty space.', 'cinematic' => 'Cinematic colour grading and depth of field.', ); $parts[] = $style_text[$style]; $extra = trim( sanitize_text_field( ( isset( $opts['extra_prompt'] ) ? (string) $opts['extra_prompt'] : '' ) ) ); if ( '' !== $extra ) { $parts[] = ( 'gemini' === $provider ? self::strip_transparent( $extra ) : $extra ); } $parts[] = self::TAIL; $prompt = trim( preg_replace( '/\\s+/', ' ', implode( ' ', array_filter( $parts, 'strlen' ) ) ) ); return array( 'prompt' => $prompt, 'notes' => array(), ); } /** * Remove the word transparent (Gemini draws a fake checkerboard when it reads it). * * @param string $text Text. * @return string */ private static function strip_transparent( $text ) { return trim( preg_replace( '/\\s+/', ' ', str_ireplace( array('transparency', 'transparent'), '', $text ) ) ); } /** * The model to use: the requested one if its provider has a key, else GPT Image 2.6 Flare, * else Nano Banana 2.1, else an error. * * @param string|null $requested Model slug (default: setting). * @return string|\WP_Error */ public function resolve_model( $requested = null ) { $settings = $this->settings->get_settings(); $requested = ( null === $requested ? (string) $this->options( $settings )['product_model'] : (string) $requested ); if ( isset( self::MODELS[$requested] ) && Providers::has_api_key( $settings, self::MODELS[$requested] ) ) { return $requested; } if ( Providers::has_api_key( $settings, 'openai' ) ) { return 'gpt-image-2.6-flare'; } if ( Providers::has_api_key( $settings, 'gemini' ) ) { return 'gemini-nano-banana-2.1'; } return new \WP_Error('product_no_provider', __( 'Product Images needs an OpenAI or Gemini key.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } /* --------------------------------------------------------------------- * REST routes * ------------------------------------------------------------------ */ /** * Register the aifi/v1/product-images routes. */ public function register_routes() { $id = array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ); $txt = array( 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ); register_rest_route( 'aifi/v1', '/product-images/generate', array( 'methods' => 'POST', 'callback' => array($this, 'rest_generate'), 'permission_callback' => array($this, 'check_product_permission'), 'args' => array( 'product_id' => $id, 'attachment_id' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 0, ), 'mode' => $txt, 'background' => $txt, 'background_hex' => $txt, 'style' => $txt, 'extra_prompt' => $txt, 'size' => $txt, 'add_logo' => array( 'required' => false, 'type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); register_rest_route( 'aifi/v1', '/product-images/set', array( 'methods' => 'GET', 'callback' => array($this, 'rest_set'), 'permission_callback' => array($this, 'check_product_permission'), 'args' => array( 'product_id' => $id, 'count' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', ), 'modes' => array( 'required' => false, 'type' => 'array', 'items' => array( 'type' => 'string', ), ), ), ) ); register_rest_route( 'aifi/v1', '/product-images/attach', array( 'methods' => 'POST', 'callback' => array($this, 'rest_attach'), 'permission_callback' => array($this, 'check_product_permission'), 'args' => array( 'product_id' => $id, 'attachment_ids' => array( 'required' => true, 'type' => 'array', 'items' => array( 'type' => 'integer', ), ), 'action' => array( 'required' => true, 'type' => 'string', 'enum' => array( 'set_main', 'add_gallery', 'replace', 'use_set' ), ), 'replace_id' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 0, ), ), ) ); register_rest_route( 'aifi/v1', '/product-images/restore', array( 'methods' => 'POST', 'callback' => array($this, 'rest_restore'), 'permission_callback' => array($this, 'check_product_permission'), 'args' => array( 'product_id' => $id, ), ) ); register_rest_route( 'aifi/v1', '/product-images/products', array( 'methods' => 'GET', 'callback' => array($this, 'rest_products'), 'permission_callback' => array($this, 'check_shop_permission'), 'args' => array_merge( array( 'filter' => array( 'required' => false, 'type' => 'string', 'enum' => array( 'all', 'category', 'no_main', 'no_gallery' ), 'default' => 'all', ), 'category' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 0, ), 'todo' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'page' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 1, ), 'per_page' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 100, ), ), self::filter_route_args() ), ) ); register_rest_route( 'aifi/v1', '/product-images/bulk', array( 'methods' => 'POST', 'callback' => array($this, 'rest_bulk'), 'permission_callback' => array($this, 'check_bulk_permission'), 'args' => array( 'product_id' => $id, 'set' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'redo' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ) ); } /** * Valid nonce from the plugin's own screens. * * @param \WP_REST_Request $request Request. * @return true|\WP_Error */ private function check_nonce( $request ) { if ( !wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) { return new \WP_Error('rest_forbidden', __( 'Invalid nonce.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } return true; } /** * Routes for one product: nonce, a product and edit rights on it. * * @param \WP_REST_Request $request Request. * @return true|\WP_Error */ public function check_product_permission( $request ) { $nonce = $this->check_nonce( $request ); if ( is_wp_error( $nonce ) ) { return $nonce; } $product_id = absint( $request['product_id'] ); if ( !current_user_can( 'edit_post', $product_id ) ) { return new \WP_Error('rest_forbidden', __( 'Sorry, you are not allowed to edit this product.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } $post = get_post( $product_id ); if ( !$post || !in_array( $post->post_type, array('product', 'product_variation'), true ) ) { return new \WP_Error('invalid_product', __( 'No product with that ID exists.', 'ai-featured-image-generator' ), array( 'status' => 404, )); } return true; } /** * Shop-wide routes: Shop Managers and administrators. * * @param \WP_REST_Request $request Request. * @return true|\WP_Error */ public function check_shop_permission( $request ) { $nonce = $this->check_nonce( $request ); if ( is_wp_error( $nonce ) ) { return $nonce; } if ( !current_user_can( 'manage_woocommerce' ) && !current_user_can( 'manage_options' ) ) { return new \WP_Error('rest_forbidden', __( 'Sorry, you are not allowed to manage product images.', 'ai-featured-image-generator' ), array( 'status' => rest_authorization_required_code(), )); } return true; } /** * Bulk: shop rights and edit rights on the product. * * @param \WP_REST_Request $request Request. * @return true|\WP_Error */ public function check_bulk_permission( $request ) { $shop = $this->check_shop_permission( $request ); return ( is_wp_error( $shop ) ? $shop : $this->check_product_permission( $request ) ); } /** * Options for one image from a request. * * @param \WP_REST_Request $request Request. * @return array */ private function request_opts( $request ) { $opts = array(); foreach ( array( 'mode', 'background', 'background_hex', 'style', 'extra_prompt', 'size' ) as $key ) { if ( null !== $request[$key] && '' !== $request[$key] ) { $opts[$key] = (string) $request[$key]; } } if ( null !== $request['add_logo'] ) { $opts['add_logo'] = (bool) $request['add_logo']; } return $opts; } /** * POST /product-images/generate: one image, not attached. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_generate( $request ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * GET /product-images/set: the slots of a product set and its photo. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_set( $request ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * POST /product-images/attach: put made images on the product. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_attach( $request ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * POST /product-images/restore: put the original images back. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_restore( $request ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * The product's images with thumbnails, for the product box. * * @param int $product_id Product. * @return array */ public function state_with_thumbs( $product_id ) { $state = $this->state( $product_id ); $state['main'] = ( $state['main_id'] ? array( 'id' => $state['main_id'], 'thumb' => (string) wp_get_attachment_image_url( $state['main_id'], 'thumbnail' ), ) : null ); $state['gallery'] = array(); foreach ( $state['gallery_ids'] as $gid ) { $state['gallery'][] = array( 'id' => $gid, 'thumb' => (string) wp_get_attachment_image_url( $gid, 'thumbnail' ), ); } // The photo a new image starts from by default (the real photo, never an AI image). $source = $this->pick_source( $product_id ); $state['source'] = ( $source ? array( 'id' => $source, 'thumb' => (string) wp_get_attachment_image_url( $source, 'thumbnail' ), ) : null ); return $state; } /** * REST args for the extra product filters on Bulk images: status and date added. * * @return array[] */ public static function filter_route_args() { return array( 'status' => array( 'required' => false, 'type' => 'string', 'enum' => array('any', 'publish', 'draft'), 'default' => 'any', ), 'date_from' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), 'date_to' => array( 'required' => false, 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), ); } /** * The extra filters from a request, in the shape query_args() takes. * * @param \WP_REST_Request $request Request. * @return array */ public static function filter_extra( $request ) { $extra = array(); foreach ( array_keys( self::filter_route_args() ) as $key ) { $extra[$key] = (string) $request[$key]; } return $extra; } /** * Product query arguments for a filter. * * @param string $filter all, category, no_main (gallery photos but no main image) or * no_gallery (a main image but no gallery photos). * @param int $category product_cat term ID (also narrows no_main and no_gallery). * @param array $extra status (any, publish, draft), and date_from and date_to (Y-m-d, * inclusive, by date added). * @return array */ public function query_args( $filter, $category, $extra = array() ) { $status = ( isset( $extra['status'] ) ? (string) $extra['status'] : 'any' ); $args = array( 'post_type' => 'product', 'post_status' => ( 'publish' === $status || 'draft' === $status ? array($status) : array( 'publish', 'draft', 'pending', 'private', 'future' ) ), 'orderby' => 'ID', 'order' => 'ASC', 'fields' => 'ids', 'no_found_rows' => false, ); $dates = array(); foreach ( array( 'date_from' => 'after', 'date_to' => 'before', ) as $key => $side ) { $day = ( isset( $extra[$key] ) ? (string) $extra[$key] : '' ); if ( preg_match( '/^\\d{4}-\\d{2}-\\d{2}$/', $day ) ) { $dates[$side] = $day; } } if ( $dates ) { $dates['inclusive'] = true; $args['date_query'] = array($dates); } if ( in_array( $filter, array('category', 'no_main', 'no_gallery'), true ) && $category ) { $args['tax_query'] = array(array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => (int) $category, )); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query } if ( 'no_gallery' === $filter ) { // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query $args['meta_query'] = array( 'relation' => 'AND', array( 'key' => '_thumbnail_id', 'value' => array('', '0'), 'compare' => 'NOT IN', ), array( 'relation' => 'OR', array( 'key' => '_product_image_gallery', 'compare' => 'NOT EXISTS', ), array( 'key' => '_product_image_gallery', 'value' => '', ), ), ); } if ( 'no_main' === $filter ) { // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query $args['meta_query'] = array( 'relation' => 'AND', array( 'relation' => 'OR', array( 'key' => '_thumbnail_id', 'compare' => 'NOT EXISTS', ), array( 'key' => '_thumbnail_id', 'value' => array('', '0'), 'compare' => 'IN', ), ), array( 'key' => '_product_image_gallery', 'value' => '', 'compare' => '!=', ), ); } return $args; } /** * GET /product-images/products: products to work through, one page at a time. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_products( $request ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * POST /product-images/bulk: one product per call. A studio main image from the * product's photo, and the gallery images of a set when asked. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_bulk( $request ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * Whether AIFIG already made this product's main image. * * @param int $product_id Product. * @return bool */ public function has_generated_main( $product_id ) { $list = get_post_meta( $product_id, self::META_GENERATED, true ); if ( !is_array( $list ) ) { return false; } foreach ( $list as $item ) { if ( isset( $item['role'] ) && 'main' === $item['role'] ) { return true; } } return false; } /* --------------------------------------------------------------------- * Product edit screen * ------------------------------------------------------------------ */ /** * The AI Product Images box on products (the only AIFIG box there). */ public function add_meta_box() { if ( !post_type_exists( 'product' ) ) { return; } add_meta_box( 'aifi_product_images_box', __( 'AI Product Images', 'ai-featured-image-generator' ), array($this, 'render_meta_box'), 'product', 'normal', 'high' ); } /** * Product box markup. The script fills in the photos and results. * * @param \WP_Post $post Product. */ public function render_meta_box( $post ) { if ( !current_user_can( 'edit_post', $post->ID ) ) { return; } if ( !Providers::can_use_premium() ) { $upgrade_url = ( function_exists( 'afig_fs' ) ? afig_fs()->get_upgrade_url() : '#' ); ?>
options(); $labels = self::labels(); $plan = $this->set_plan(); ?>