prompt_factory = new PromptFactory(); } /** * Legacy v1 generation: derive attachment IDs from the product (see * collect_image_ids()) and delegate to the v2 selections path. */ public function bulk_generate( array $product_ids, array $options, ?callable $pair_authorizer = null ): array { $selections = []; foreach ( $product_ids as $product_id ) { $product_id = absint( $product_id ); $product = wc_get_product( $product_id ); if ( ! $product ) { continue; } $attachment_ids = $this->collect_image_ids( $product, $options ); if ( ! empty( $attachment_ids ) ) { $selections[] = [ 'productId' => $product_id, 'attachmentIds' => $attachment_ids, ]; } else { $selections[] = [ 'productId' => $product_id, 'attachmentIds' => [], '_no_images' => true, ]; } } return $this->bulk_generate_by_selections( $selections, $options, $pair_authorizer ); } /** * @param array $selections [{productId, attachmentIds}, ...]. * @param array $options Validated request options. * @param callable|null $pair_authorizer fn(int $attachment_id, int $product_id): ?string — * the specific refusal reason, or null when the * pair may be generated for. Omitted entirely for * an unattended caller with no request context. * @return array */ public function bulk_generate_by_selections( array $selections, array $options, ?callable $pair_authorizer = null ): array { $results = []; $api_provider = sanitize_text_field( $options['provider'] ?? get_option( 'aipt_api_provider', 'openai' ) ); $model = $options['model'] ?? null; $max_length = isset( $options['maxLength'] ) ? absint( $options['maxLength'] ) : 125; $max_length = $max_length > 0 ? max( 50, min( 250, $max_length ) ) : 125; $language = ( isset( $options['language'] ) && is_string( $options['language'] ) && '' !== trim( $options['language'] ) ) ? $options['language'] : get_option( 'aipt_language', 'English' ); $client = null; $use_blueprint = BlueprintIntegration::usesBlueprint( Generators::IMAGE_ALT, BlueprintIntegration::jobTrustedFacts() ); foreach ( $selections as $selection ) { $product_id = absint( $selection['productId'] ?? 0 ); $attachment_ids = array_filter( array_map( 'absint', (array) ( $selection['attachmentIds'] ?? [] ) ) ); if ( $product_id <= 0 ) { continue; } $product = wc_get_product( $product_id ); if ( ! $product ) { continue; } if ( empty( $attachment_ids ) ) { $results[] = [ 'product_id' => $product_id, 'attachment_id' => 0, 'image_url' => '', 'alt_text' => '', 'status' => 'error', 'error' => __( 'No images selected for this product.', 'ai-product-tools' ), ]; continue; } $product_data = null; $additional_section = ''; foreach ( $attachment_ids as $attachment_id ) { if ( null !== $pair_authorizer ) { $authorization_error = $pair_authorizer( $attachment_id, $product_id ); if ( null !== $authorization_error ) { $results[] = [ 'product_id' => $product_id, 'attachment_id' => $attachment_id, 'image_url' => '', 'alt_text' => '', 'status' => 'error', 'error' => $authorization_error, ]; continue; } } $image_url = \wp_get_attachment_url( $attachment_id ); if ( empty( $image_url ) ) { $results[] = [ 'product_id' => $product_id, 'attachment_id' => $attachment_id, 'image_url' => '', 'alt_text' => '', 'status' => 'error', 'error' => __( 'Could not retrieve image URL for attachment.', 'ai-product-tools' ), ]; continue; } if ( $use_blueprint ) { $results[] = $this->generateViaBlueprint( $product_id, $attachment_id, $image_url, $options ); continue; } if ( null === $product_data ) { $product_data = ProductDataFormatter::getFormattedProductData( $product ); /** * Filter the additional instructions section of this * product's vision prompts, placed right after the product * data. The Premium build renders the merchant's additional * instructions (site-level and per-request) here. * * @since 2.8.0 * @param string $additional_section Section ('' by default). * @param array $options Validated request options. * @param array $product_data Formatted product data. */ $additional_section = (string) apply_filters( 'aipt_image_alt_additional_section', '', $options, $product_data ); } try { if ( null === $client ) { $client = AIClientFactory::create( $api_provider, [ 'generation_type' => 'image_alt', 'model' => $model, ] ); } $prompts = $this->prompt_factory->getPrompts( $options, [ 'name' => $product_data['name'] ?? $product->get_name(), 'categories' => $product_data['categories'] ?? '', 'description' => $product_data['description'] ?? HtmlToText::convert( (string) $product->get_description() ), ], $additional_section, (string) $language ); /** * Filter the vision user prompt for one product image. The * Premium build adds the product attribute block when the * request kept `enrichWithAttributes`. * * @since 2.8.0 * @param string $user_prompt User prompt. * @param \WC_Product $product Product the image belongs to. * @param array $options Validated request options. */ $prompts['user_prompt'] = (string) apply_filters( 'aipt_image_alt_user_prompt', $prompts['user_prompt'], $product, $options ); $alt_text = $client->generate_from_vision( $prompts['system_prompt'], $prompts['user_prompt'], $image_url, $model ); $alt_text = \wp_strip_all_tags( trim( $alt_text ) ); $alt_text = (string) preg_replace( '/^(["\'`])((?:(?!\1).)*)\1$/su', '$2', $alt_text ); $alt_text = FormulaText::trimToWordBoundary( $alt_text, $max_length )['text']; if ( '' === trim( $alt_text ) ) { throw new \Exception( 'No valid alt text was generated' ); } $results[] = array_merge( [ 'product_id' => $product_id, 'attachment_id' => $attachment_id, 'current_alt' => (string) \get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ), 'image_url' => \esc_url_raw( $image_url ), 'alt_text' => $alt_text, 'status' => 'pending', ], BlueprintIntegration::advancedResponseFields() ); } catch ( \Exception $e ) { $results[] = array_merge( BlueprintIntegration::advancedResponseFields(), [ 'product_id' => $product_id, 'attachment_id' => $attachment_id, 'image_url' => \esc_url_raw( $image_url ), 'alt_text' => '', 'status' => 'error', 'error' => ProviderCallException::displayMessage( $e, $api_provider ), 'providerError' => ProviderCallException::providerErrorFor( $e, $api_provider ), ] ); } } } return $results; } /** * Generate one attachment's alt text through the content structure * engine. Returns the EXACT per-attachment shape the legacy branch * returns (`current_alt`, `image_url`, `alt_text`, `status`), plus * this method's additional response fields, so the * controller's existing review-staging/apply/`can_update_attachment_alt` * handling needs no changes. An empty answer is a generation failure, * same invariant as the legacy vision path (and Title/Desc). * * @since 2.8.0 * * @param int $product_id Parent product id. * @param int $attachment_id Attachment id. * @param string $image_url Already-resolved attachment URL (for the response only; the engine resolves its own vision URL internally). * @param array $options Request options (generationMode, provider, model, language, blueprintRun, blueprintId, overwrite). * @return array */ private function generateViaBlueprint( int $product_id, int $attachment_id, string $image_url, array $options ): array { $run_options = [ 'language' => ( isset( $options['language'] ) && is_string( $options['language'] ) && '' !== trim( $options['language'] ) ) ? $options['language'] : 'store', 'provider' => isset( $options['provider'] ) && is_string( $options['provider'] ) ? $options['provider'] : '', 'model' => isset( $options['model'] ) && is_string( $options['model'] ) ? $options['model'] : '', ]; $result = BlueprintIntegration::run( Generators::IMAGE_ALT, [ 'type' => 'attachment', 'id' => $attachment_id, 'productId' => $product_id ], $options, $run_options, 'bulk' ); if ( is_wp_error( $result ) ) { return [ 'product_id' => $product_id, 'attachment_id' => $attachment_id, 'image_url' => \esc_url_raw( $image_url ), 'alt_text' => '', 'status' => 'error', 'error' => $result->get_error_message(), ]; } $alt_text = (string) ( $result['outputs']['alt'][ (string) $attachment_id ] ?? '' ); $blueprint_fields = BlueprintIntegration::responseFields( $result ); $item = [ 'product_id' => $product_id, 'attachment_id' => $attachment_id, 'current_alt' => (string) \get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ), 'image_url' => \esc_url_raw( $image_url ), 'alt_text' => $alt_text, 'status' => '' === $alt_text ? 'error' : 'pending', ]; if ( '' === $alt_text ) { $item['error'] = ProviderErrorMessage::fromResponseFields( $blueprint_fields ) ?? __( 'No valid alt text was generated', 'ai-product-tools' ); } $item = array_merge( $item, $blueprint_fields ); $generation_mode = is_string( $options['generationMode'] ?? null ) ? $options['generationMode'] : 'client_preview'; $destination = BlueprintIntegration::destinationForMode( $generation_mode ); if ( '' !== $alt_text && BlueprintIntegration::isHeldBack( $result, $destination ) ) { $item['status'] = 'needs_review'; } return $item; } public function get_product_images( int $product_id ): array { $product = wc_get_product( $product_id ); if ( ! $product ) { return [ 'product_id' => $product_id, 'product_name' => '', 'featured' => null, 'gallery' => [], ]; } $result = [ 'product_id' => $product_id, 'product_name' => $product->get_name(), 'featured' => null, 'gallery' => [], ]; $featured_id = (int) $product->get_image_id(); if ( $featured_id > 0 ) { $result['featured'] = $this->format_attachment( $featured_id, true ); } $gallery_ids = array_map( 'absint', (array) $product->get_gallery_image_ids() ); foreach ( $gallery_ids as $gallery_id ) { if ( $gallery_id > 0 ) { $result['gallery'][] = $this->format_attachment( $gallery_id, false ); } } $already_listed = array_fill_keys( array_filter( array_merge( [ $featured_id ], $gallery_ids ) ), true ); foreach ( self::variation_images( $product ) as $variation_image ) { if ( isset( $already_listed[ $variation_image['id'] ] ) ) { continue; } $already_listed[ $variation_image['id'] ] = true; $attachment = $this->format_attachment( $variation_image['id'], false ); $attachment['variation_label'] = $variation_image['label']; $result['gallery'][] = $attachment; } return $result; } /** * This product's own variations, each with the one image (if any) it * claims as its own distinct picture: {@see \WC_Product_Variation::get_image_id()} * already falls back to the PARENT's own image when a variation has * none of its own, so only a variation that actually overrides its * image is listed here — every other variation already shares whatever * the parent's own featured image already lists. * * Shared by get_product_images() (the generator's own image list), * collect_image_ids() (the v1/Automation product-level path) and * ImageAltController::authorizationFailureMessage() (the identical * per-attachment authorization every other product image already * gets), so a variation's image is selectable, generatable and * writable through the SAME parent-product flow, with no separate * variation picker or id. * * @since 2.8.1 * @param \WC_Product $product Parent product (never a variation itself — * ProductEligibility has already refused one). * @return array One entry per variation * with its own distinct image, in variation order. */ public static function variation_images( \WC_Product $product ): array { if ( ! $product->is_type( 'variable' ) ) { return []; } $parent_image_id = (int) $product->get_image_id(); $seen = []; $images = []; foreach ( (array) $product->get_children() as $variation_id ) { $variation = wc_get_product( absint( $variation_id ) ); if ( ! $variation instanceof \WC_Product_Variation ) { continue; } $image_id = (int) $variation->get_image_id(); if ( $image_id <= 0 || $image_id === $parent_image_id || isset( $seen[ $image_id ] ) ) { continue; } $seen[ $image_id ] = true; $images[] = [ 'id' => $image_id, 'label' => (string) wc_get_formatted_variation( $variation, true ), ]; } return $images; } private function format_attachment( int $attachment_id, bool $is_featured ): array { $url = \wp_get_attachment_url( $attachment_id ); $thumbnail_url = \wp_get_attachment_image_url( $attachment_id, 'thumbnail' ); $metadata = \wp_get_attachment_metadata( $attachment_id ); $attached_file = \get_attached_file( $attachment_id ); $filename = $attached_file ? basename( $attached_file ) : ''; $current_alt = \get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); return [ 'id' => $attachment_id, 'url' => \esc_url_raw( $url ?: '' ), 'thumbnail_url' => \esc_url_raw( $thumbnail_url ?: $url ?: '' ), 'filename' => sanitize_text_field( $filename ), 'width' => (int) ( $metadata['width'] ?? 0 ), 'height' => (int) ( $metadata['height'] ?? 0 ), 'is_featured' => $is_featured, 'current_alt' => sanitize_text_field( is_string( $current_alt ) ? $current_alt : '' ), ]; } private function collect_image_ids( \WC_Product $product, array $options ): array { $ids = []; $featured_id = (int) $product->get_image_id(); if ( $featured_id > 0 ) { $ids[] = $featured_id; } /** * Filter the images a product-level (v1 productIds) request writes alt * text for: the featured image by default. The Premium build adds the * gallery images when the request kept `includeGallery`. * * @since 2.8.0 * @param int[] $ids Attachment ids. * @param \WC_Product $product Product. * @param array $options Validated request options. */ $filtered = apply_filters( 'aipt_image_alt_image_ids', $ids, $product, $options ); $ids = array_values( array_filter( array_map( 'absint', is_array( $filtered ) ? $filtered : $ids ) ) ); foreach ( self::variation_images( $product ) as $variation_image ) { $ids[] = $variation_image['id']; } return array_values( array_unique( $ids ) ); } }