target_mode = ( in_array( $mode, Product_Images::MODES, true ) ? (string) $mode : 'studio' ); } /** * Which photos this request looks at: all, main (main images only) or gallery. * * @var string */ private $photos = 'all'; /** * Photo choices for scan and run. */ const PHOTOS = array('all', 'main', 'gallery'); /** * Set which photos this request looks at. * * @param mixed $photos Requested choice. */ private function set_photos( $photos ) { $this->photos = ( in_array( $photos, self::PHOTOS, true ) ? (string) $photos : 'all' ); } /** * Whether one extra filter value narrows the list (any status and empty values do not). * * @param string $value Filter value. * @return bool */ private static function is_narrowing( $value ) { return '' !== (string) $value && 'any' !== (string) $value; } /** * Extra product filters for this request (Bulk images: status, date added). * * @var array */ private $query_extra = array(); /** * Whether scan() keeps running totals across pages (the summary). Bulk images reads only * the rows, so it turns this off and no growing cache is written on every page. * * @var bool */ private $keep_summary = true; /** * The type of shot an image is remade as. Main images follow the Main image choice of the * product set (Studio unless the owner chose otherwise), the same as product sets and bulk; * gallery photos are remade as Studio. * * @param string $role main or gallery. * @return string */ private function mode_for( $role ) { return ( 'main' === $role ? $this->product_images->main_mode() : $this->target_mode ); } /** * Constructor. * * @param Settings $settings Settings. * @param Product_Images $product_images Product Images module. */ public function __construct( Settings $settings, Product_Images $product_images ) { $this->settings = $settings; $this->product_images = $product_images; } /** * Hooks. */ public function register_hooks() { add_action( 'rest_api_init', array($this, 'register_routes') ); } /** * The upgrade message. * * @return \WP_Error */ private function premium_error() { return new \WP_Error('premium_required', __( 'Matching product photos is a Pro feature. Please upgrade to use it.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } /* --------------------------------------------------------------------- * Checking images * ------------------------------------------------------------------ */ /** * A product's images: the main image first, then the gallery. * * @param int $post_id Product. * @return array[] Each array( 'role' => main|gallery, 'id' => int ). */ public function images_for( $post_id ) { $out = array(); $main = $this->product_images->get_main_id( $post_id ); if ( $main ) { $out[] = array( 'role' => 'main', 'id' => $main, ); } foreach ( $this->product_images->get_gallery_ids( $post_id ) as $gid ) { $out[] = array( 'role' => 'gallery', 'id' => $gid, ); } return $out; } /** * What differs between an image and the chosen Product Images look. * * An image AIFIG made for this product gets a wider colour tolerance, so a slightly off * shade of its own background is not remade (and paid for) on every run. * * @param array|null $facts Image_Pixels::facts(). * @param array $settings Plugin settings. * @param int $product_id Product. * @param int $attachment_id The image (0 when unknown). * @return string[] Any of background_differs, shot_differs, ratio_differs, size_differs, format_differs. */ public function compare( $facts, $settings, $product_id, $attachment_id = 0 ) { if ( !is_array( $facts ) ) { return array(); } $o = $this->product_images->options( $settings ); $want = $o['product_background']; $scan = ( is_array( $facts['scan'] ) ? $facts['scan'] : null ); $differs = array(); if ( !in_array( $this->target_mode, Product_Images::PLAIN_MODES, true ) ) { // Showroom and Lifestyle are real places, so there is no background to measure: // every image that AIFIG did not already make in that shot type is remade. $made_as = ( $attachment_id && $this->is_ours( $attachment_id, $product_id ) ? (string) get_post_meta( $attachment_id, Product_Images::META_MODE, true ) : '' ); if ( $made_as !== $this->target_mode ) { $differs[] = 'shot_differs'; } $scan = null; } if ( $scan && 'unknown' === $scan['background'] ) { $scan = null; // Not measured (file too large): shown as Check, never remade for its background. } if ( $scan && $attachment_id && $this->is_ours( $attachment_id, $product_id ) && 'transparent' !== $want && empty( $scan['transparent'] ) ) { $named = array( 'white' => '#ffffff', 'light_grey' => '#e5e5e5', 'beige' => '#f1e7d8', ); $hex = ( 'custom' === $want ? Settings::normalize_brand_colors( array((string) $o['product_background_hex']) ) : array(( isset( $named[$want] ) ? $named[$want] : '#ffffff' )) ); $goal = self::rgb( ( $hex ? $hex[0] : '#ffffff' ) ); $got = self::rgb( (string) $scan['hex'] ); // Custom colours: twice the usual 30. Named colours sit about 45 apart, so 30 keeps // a beige image on a white look flagged while an off-white one is left alone. $limit = ( 'custom' === $want ? 60 : 30 ); if ( $goal && $got && Image_Pixels::color_distance( $goal, $got ) <= $limit ) { $scan = null; // Close enough to the look: AIFIG made it, so leave it. } } if ( $scan ) { if ( 'transparent' === $want ) { if ( empty( $scan['transparent'] ) ) { $differs[] = 'background_differs'; } } elseif ( !empty( $scan['transparent'] ) ) { $differs[] = 'background_differs'; } elseif ( 'custom' === $want ) { $hex = Settings::normalize_brand_colors( array((string) $o['product_background_hex']) ); $rgb = self::rgb( ( $hex ? $hex[0] : '#ffffff' ) ); $got = self::rgb( (string) $scan['hex'] ); if ( !$got || Image_Pixels::color_distance( $rgb, $got ) > 30 ) { $differs[] = 'background_differs'; } } elseif ( $scan['background'] !== $want ) { $differs[] = 'background_differs'; } } $model = $this->product_images->resolve_model(); $model = ( is_wp_error( $model ) ? 'gpt-image-2.6-flare' : $model ); $provider = Product_Images::MODELS[$model]; $expected = $this->product_images->generator()->expected_ratio( $provider, $model, $o['product_size'] ); if ( $expected > 0 && !empty( $facts['ratio'] ) && abs( $facts['ratio'] - $expected ) / $expected > 0.02 ) { $differs[] = 'ratio_differs'; } if ( !empty( $facts['width'] ) && min( (int) $facts['width'], (int) $facts['height'] ) < Product_Images::MIN_EDGE ) { $differs[] = 'size_differs'; } if ( 'transparent' === $want && in_array( $this->target_mode, Product_Images::PLAIN_MODES, true ) && !in_array( $facts['format'], array('png', 'webp'), true ) ) { $differs[] = 'format_differs'; } /** * Filter what Unify reports as different for one product image. * * @param string[] $differs Differences. * @param array $facts Width, height, ratio, format and background scan. * @param array $settings Plugin settings. * @param int $product_id Product. */ $differs = apply_filters( 'aifi_product_unify_checks', array_values( array_unique( $differs ) ), $facts, $settings, $product_id ); $ai = $this->ai_style_check( $facts, $settings, $product_id ); if ( is_array( $ai ) ) { $differs = array_values( array_unique( array_merge( (array) $differs, $ai ) ) ); } return array_values( (array) $differs ); } /** * Reserved for a later paid AI look check. Returns null (no extra findings). * * @param array $facts Facts. * @param array $settings Settings. * @param int $product_id Product. * @return array|null */ public function ai_style_check( $facts, $settings, $product_id ) { return null; } /** * Whether AIFIG made this image for this product. * * @param int $attachment_id Image. * @param int $product_id Product. * @return bool */ private function is_ours( $attachment_id, $product_id ) { return (int) get_post_meta( $attachment_id, Product_Images::META_OF, true ) === (int) $product_id && '' !== (string) get_post_meta( $attachment_id, Product_Images::META_MODE, true ); } /** * Whether AIFIG made this image for this product as a Showroom or Lifestyle picture. Those * are real places on purpose, so Unify keeps them unless the user asks to include them. * * @param int $attachment_id Image. * @param int $product_id Product. * @return bool */ private function is_our_scene( $attachment_id, $product_id ) { return $this->is_ours( $attachment_id, $product_id ) && !in_array( (string) get_post_meta( $attachment_id, Product_Images::META_MODE, true ), Product_Images::PLAIN_MODES, true ); } /** * RGB of a #rrggbb string. * * @param string $hex Colour. * @return int[]|null */ private static function rgb( $hex ) { if ( !preg_match( '/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i', trim( $hex ), $m ) ) { return null; } return array(hexdec( $m[1] ), hexdec( $m[2] ), hexdec( $m[3] )); } /** * One product's row: its images with their facts and differences. * * @param int $pid Product. * @param array $settings Settings. * @return array */ private function row( $pid, $settings ) { $images = array(); $target = $this->target_mode; foreach ( $this->images_for( $pid ) as $img ) { if ( 'all' !== $this->photos && $img['role'] !== $this->photos ) { continue; } // Compare each image against the shot type it would be remade as (main: always Studio). $this->target_mode = $this->mode_for( $img['role'] ); $facts = Image_Pixels::facts( $img['id'] ); $differs = $this->compare( $facts, $settings, $pid, (int) $img['id'] ); $scan = ( is_array( $facts ) && is_array( $facts['scan'] ) ? $facts['scan'] : null ); $kept = !$this->include_scenes && $this->is_our_scene( (int) $img['id'], $pid ) && (string) get_post_meta( (int) $img['id'], Product_Images::META_MODE, true ) !== $this->target_mode; if ( $kept ) { $differs = array(); } $images[] = array( 'attachment_id' => (int) $img['id'], 'role' => $img['role'], 'thumb' => (string) wp_get_attachment_image_url( $img['id'], 'thumbnail' ), 'url' => (string) wp_get_attachment_url( $img['id'] ), 'width' => ( is_array( $facts ) ? (int) $facts['width'] : 0 ), 'height' => ( is_array( $facts ) ? (int) $facts['height'] : 0 ), 'format' => ( is_array( $facts ) ? (string) $facts['format'] : '' ), 'scan' => $scan, 'differs' => $differs, 'check' => !$kept && $scan && 'check' === $scan['confidence'], 'kept' => $kept, ); $this->target_mode = $target; } $this->target_mode = $target; return array( 'product_id' => (int) $pid, 'title' => Product_Images::plain_title( $pid ), 'images' => $images, 'has_originals' => metadata_exists( 'post', $pid, Product_Images::META_ORIGINAL_IMAGE ), 'has_photos' => (bool) $this->images_for( $pid ), 'edit' => (string) get_edit_post_link( $pid, 'raw' ), ); } /** * The counts one row adds to the summary (all the scan cache keeps per product). * * @param array $row Row. * @return int[] Only the non-zero counts. */ private static function row_counts( array $row ) { $c = array(); if ( empty( $row['images'] ) ) { return array( 'no_image' => 1, ); } foreach ( $row['images'] as $img ) { $keys = (array) $img['differs']; $keys[] = 'scanned_images'; if ( !empty( $img['check'] ) ) { $keys[] = 'check'; } foreach ( $keys as $k ) { $c[$k] = ( isset( $c[$k] ) ? $c[$k] + 1 : 1 ); } } return $c; } /** * Scan one page of products. Each product's summary counts are kept for ten minutes so * the summary covers every page scanned so far; the rows themselves are built fresh for * each page from the facts kept on each image. * * @param string $filter all, category or no_main. * @param int $category product_cat term ID. * @param int $page Page (1-based). * @param int $per_page Products per page (1..20). * @param bool $refresh Start again. * @param bool $include_scenes Also report lifestyle and showroom pictures AIFIG made. * @param string $target_mode Type of shot to unify to: studio, 3d, showroom or lifestyle. * @return array summary, rows, total, pages, scanned_pages. */ public function scan( $filter = 'all', $category = 0, $page = 1, $per_page = self::SCAN_PER_PAGE, $refresh = false, $include_scenes = false, $target_mode = 'studio', $photos = 'all' ) { $filter = ( in_array( $filter, self::FILTERS, true ) ? $filter : 'all' ); $per_page = max( 1, min( self::SCAN_PER_PAGE, (int) $per_page ) ); $page = max( 1, (int) $page ); $this->include_scenes = (bool) $include_scenes; $this->set_target_mode( $target_mode ); $this->set_photos( $photos ); $key = 'aifi_unify_' . md5( $filter . '|' . (int) $category . '|' . (( $this->include_scenes ? 1 : 0 )) . (( 'studio' === $this->target_mode ? '' : '|' . $this->target_mode )) . (( 'all' === $this->photos ? '' : '|p:' . $this->photos )) . (( array_filter( $this->query_extra, array(__CLASS__, 'is_narrowing') ) ? '|x:' . wp_json_encode( $this->query_extra ) : '' )) ) . '_' . get_current_user_id(); if ( $refresh ) { delete_transient( $key ); } $kept = ( $this->keep_summary ? get_transient( $key ) : false ); $kept = ( is_array( $kept ) && isset( $kept['counts'] ) ? $kept : array( 'counts' => array(), 'pages' => array(), ) ); $args = $this->product_images->query_args( $filter, (int) $category, $this->query_extra ); $args['posts_per_page'] = $per_page; $args['paged'] = $page; $query = new \WP_Query($args); $settings = $this->settings->get_settings(); $rows = array(); foreach ( array_map( 'intval', $query->posts ) as $pid ) { $row = $this->row( $pid, $settings ); $rows[] = $row; $kept['counts'][$pid] = self::row_counts( $row ); } $kept['pages'][$page] = true; if ( $this->keep_summary ) { set_transient( $key, $kept, self::SCAN_TTL ); } return array( 'summary' => self::summarize( $kept['counts'] ), 'rows' => $rows, 'total' => (int) $query->found_posts, 'pages' => (int) $query->max_num_pages, 'scanned_pages' => array_keys( $kept['pages'] ), ); } /** * Totals over the kept per-product counts. * * @param array $counts row_counts() by product ID. * @return array */ private static function summarize( array $counts ) { $s = array( 'products' => count( $counts ), 'scanned_images' => 0, 'background_differs' => 0, 'size_differs' => 0, 'ratio_differs' => 0, 'format_differs' => 0, 'shot_differs' => 0, 'no_image' => 0, 'check' => 0, ); foreach ( $counts as $c ) { foreach ( (array) $c as $k => $n ) { if ( isset( $s[$k] ) && 'products' !== $k ) { $s[$k] += (int) $n; } } } return $s; } /** * Forget every kept scan of this user. */ private function forget_scans() { global $wpdb; $like = $wpdb->esc_like( '_transient_aifi_unify_' ) . '%' . $wpdb->esc_like( '_' . get_current_user_id() ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", $like ) ); foreach ( (array) $names as $name ) { delete_transient( substr( $name, strlen( '_transient_' ) ) ); } } /* --------------------------------------------------------------------- * REST routes * ------------------------------------------------------------------ */ /** * Register the aifi/v1/product-images/unify routes. */ public function register_routes() { $filter = array( 'required' => false, 'type' => 'string', 'enum' => self::FILTERS, 'default' => 'all', ); $category = array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 0, ); $perm = array($this->product_images, 'check_shop_permission'); register_rest_route( 'aifi/v1', '/product-images/unify/scan', array( 'methods' => 'GET', 'callback' => array($this, 'rest_scan'), 'permission_callback' => $perm, 'args' => array( 'filter' => $filter, 'category' => $category, 'refresh' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'include_scenes' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'target_mode' => array( 'required' => false, 'type' => 'string', 'enum' => Product_Images::MODES, 'default' => 'studio', ), 'photos' => array( 'required' => false, 'type' => 'string', 'enum' => self::PHOTOS, 'default' => 'all', ), 'page' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 1, ), 'per_page' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => self::SCAN_PER_PAGE, ), 'summary' => array( 'required' => false, 'type' => 'boolean', 'default' => true, 'sanitize_callback' => 'rest_sanitize_boolean', ), ) + Product_Images::filter_route_args(), ) ); register_rest_route( 'aifi/v1', '/product-images/unify/run', array( 'methods' => 'POST', 'callback' => array($this, 'rest_run'), 'permission_callback' => $perm, 'args' => array( 'offset' => array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ), 'filter' => $filter, 'category' => $category, 'product_ids' => array( 'required' => false, 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ), 'max_images' => array( 'required' => false, 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 0, ), 'image_ids' => array( 'required' => false, 'type' => 'array', 'items' => array( 'type' => 'integer', ), ), 'unsure' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'include_scenes' => array( 'required' => false, 'type' => 'boolean', 'default' => false, 'sanitize_callback' => 'rest_sanitize_boolean', ), 'target_mode' => array( 'required' => false, 'type' => 'string', 'enum' => Product_Images::MODES, 'default' => 'studio', ), 'photos' => array( 'required' => false, 'type' => 'string', 'enum' => self::PHOTOS, 'default' => 'all', ), ), ) ); } /** * GET /product-images/unify/scan. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_scan( $request ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * Remake one target image of a product. It starts from the photo the target was made * from when AIFIG made it, else from the target itself. * * @param int $pid Product. * @param int $target_id Image to remake. * @return array|\WP_Error generate() result. */ private function remake( $pid, $target_id, $mode = null ) { $source = (int) get_post_meta( $target_id, Product_Images::META_SOURCE, true ); if ( !$source || !wp_attachment_is_image( $source ) || !file_exists( (string) get_attached_file( $source ) ) ) { $source = $target_id; } $mode = ( in_array( $mode, Product_Images::MODES, true ) ? $mode : $this->target_mode ); return $this->product_images->generate( $pid, $source, array( 'mode' => $mode, ) ); } /** * The product IDs the owner confirmed, in order, or null when none were sent. * * @param mixed $raw Request value. * @return int[]|null */ private static function planned_ids( $raw ) { if ( !is_array( $raw ) ) { return null; } $ids = array_values( array_unique( array_filter( array_map( 'absint', $raw ) ) ) ); return ( $ids ? $ids : null ); } /** * POST /product-images/unify/run: one product per call, at offset in the confirmed list * (product_ids), or in the filtered list when no list is sent. Makes at most max_images * images (0 = no cap), and only the photos in image_ids when it is sent (an empty list * makes nothing). Each new photo replaces the one it was made from straight away. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_run( $request ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } }