service = new Service(); } /** * The `bulk-generate` endpoint. The Product Editor's `editor-bulk-generate` * route copies it: the free build with the refusal callback, the Business * build (Premium\BulkGenerator\EditorBulkGenerateController) with this * callback and its own permission check. * * @return array */ public function bulk_generate_endpoint(): array { return [ 'methods' => 'POST', 'callback' => [ $this, 'bulk_generate' ], 'permission_callback' => [ $this, 'check_permissions_write' ], 'args' => [ /* * NEW (v2): image-level selection shape. * [ { productId: 123, attachmentIds: [45, 67] }, ... ] */ 'selections' => [ 'type' => 'array', 'required' => false, 'default' => [], ], /* * LEGACY (v1): list of product IDs. * Still accepted; backend falls back to collect_image_ids() logic. */ 'productIds' => [ 'type' => 'array', 'required' => false, 'default' => [], 'maxItems' => self::MAX_GENERATE_ITEMS, 'validate_callback' => 'rest_validate_request_arg', 'sanitize_callback' => function ( $param ) { return array_map( 'absint', (array) $param ); }, ], 'options' => [ 'type' => 'object', 'required' => false, 'default' => [], ], 'runSize' => self::run_size_arg(), ] + self::claim_args(), ]; } public function register_routes(): void { $bulk_generate_endpoint = $this->bulk_generate_endpoint(); register_rest_route( self::REST_NAMESPACE, '/image-alt-generator/bulk-generate', $bulk_generate_endpoint ); $editor_bulk_generate_endpoint = $bulk_generate_endpoint; $editor_bulk_generate_endpoint['callback'] = [ $this, 'editor_bulk_generation_required' ]; register_rest_route( self::REST_NAMESPACE, '/image-alt-generator/editor-bulk-generate', $editor_bulk_generate_endpoint ); register_rest_route( self::REST_NAMESPACE, '/image-alt-generator/bulk-apply', [ 'methods' => 'POST', 'callback' => [ $this, 'bulk_apply' ], 'permission_callback' => [ $this, 'check_permissions_write' ], 'args' => [ 'results' => [ 'type' => 'array', 'required' => true, 'validate_callback' => [ $this, 'validate_bulk_apply_results' ], ], 'options' => [ 'type' => 'object', 'required' => false, ], ], ] ); register_rest_route( self::REST_NAMESPACE, '/image-alt-generator/product-images', [ 'methods' => 'GET', 'callback' => [ $this, 'get_product_images' ], 'permission_callback' => [ $this, 'check_permissions' ], 'args' => [ 'product_id' => [ 'type' => 'integer', 'required' => true, 'sanitize_callback' => 'absint', 'validate_callback' => function ( $value ) { return is_numeric( $value ) && (int) $value > 0; }, ], ], ] ); } /** * Tones available to every plan. * * Tone selection was freed for all plans in the 2026-09 Free/Business tier * decision; single source of truth for the tone allow-list (the premium * module references this constant). * * @var string[] */ public const FREE_TONES = [ 'descriptive', 'seo-focused', 'storytelling', 'technical', 'luxury', 'playful' ]; /** * Normalize a requested tone against the free allow-list. * * Runs AFTER the premium-restore filter so even restored values are * constrained (tone is interpolated into prompts — allow-list only). * * @param mixed $tone Requested tone. * @return string Allow-listed tone or the default. */ public static function normalizeTone( $tone ): string { $tone = sanitize_text_field( (string) $tone ); return in_array( $tone, self::FREE_TONES, true ) ? $tone : 'descriptive'; } private function applyPremiumControls( array $options ): array { $free_defaults = [ 'includeGallery' => false, 'enrichWithAttributes' => false, ]; $controlled = array_merge( $options, $free_defaults ); /** * Filter image alt generator validated options. * * Premium module hooks here to preserve includeGallery and attribute * enrichment when a valid license is present. * * @since 2.6.0 * @param array $controlled Options with free defaults applied. * @param array $options Original request options. */ $controlled = apply_filters( 'aipt_image_alt_validate_options', $controlled, $options ); $controlled['tone'] = self::normalizeTone( $controlled['tone'] ?? '' ); return $controlled; } public function bulk_generate( WP_REST_Request $request ) { $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof WP_Error ) { return $ai_gate; } $claim_key = ''; try { $rate_check = $this->checkRateLimit( (int) \get_current_user_id(), static::RATE_LIMIT_SCOPE ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $data = $request->get_json_params(); if ( ! is_array( $data ) ) { return $this->error_response( 'invalid_payload', __( 'Invalid request payload.', 'ai-product-tools' ) ); } $options = (array) ( $data['options'] ?? [] ); $review_stager = ReviewQueueStaging::stager(); $options = $this->enforce_generation_mode( $options, $review_stager ); $requested_options = $options; $options = $this->applyPremiumControls( $options ); $applied_defaults = $this->detectAppliedFreeDefaults( $requested_options, $options ); /* * NEW shape: { selections: [{productId, attachmentIds}], options } * Detects whether caller sent v2 selections or v1 productIds. */ $selections = (array) ( $data['selections'] ?? [] ); $sanitized_selections = []; if ( ! empty( $selections ) ) { foreach ( $selections as $sel ) { if ( ! is_array( $sel ) ) { continue; } $product_id = absint( $sel['productId'] ?? 0 ); $attachment_ids = array_filter( array_map( 'absint', (array) ( $sel['attachmentIds'] ?? [] ) ) ); if ( $product_id > 0 && ! empty( $attachment_ids ) ) { $sanitized_selections[] = [ 'productId' => $product_id, 'attachmentIds' => array_values( $attachment_ids ), ]; } } if ( empty( $sanitized_selections ) ) { return $this->error_response( 'no_images', __( 'No valid image selections provided.', 'ai-product-tools' ) ); } $claimed_items = $sanitized_selections; $run_items = count( $sanitized_selections ); $by_selections = true; $generate = fn() => $this->service->bulk_generate_by_selections( $sanitized_selections, $options, [ $this, 'authorizationFailureMessage' ], self::MAX_IMAGE_ALT_IMAGES_PER_REQUEST ); } else { $product_ids = array_filter( array_map( 'absint', (array) ( $data['productIds'] ?? [] ) ) ); if ( empty( $product_ids ) ) { return $this->error_response( 'no_products', __( 'No products or image selections provided.', 'ai-product-tools' ) ); } $claimed_items = array_values( $product_ids ); $run_items = count( $product_ids ); $by_selections = false; $generate = fn() => $this->service->bulk_generate( array_values( $product_ids ), $options, [ $this, 'authorizationFailureMessage' ], self::MAX_IMAGE_ALT_IMAGES_PER_REQUEST ); } $claim = $this->claim_generate_request( $request, static function () use ( $claimed_items, $by_selections, $options ): array { return [ 'requested' => $claimed_items, 'authorized' => self::authorized_pairs( $claimed_items, $by_selections, $options ), ]; } ); if ( ! is_string( $claim ) ) { return $claim; } $claim_key = $claim; $results = $this->generate_in_run( $request, $run_items, $generate ); $not_attempted = array(); $not_attempted_images = array(); if ( is_array( $results ) ) { [ $results, $not_attempted, $not_attempted_images ] = GenerateTimeBudget::separateWithImages( $results ); } if ( null !== $review_stager && 'server_review' === ( $options['generationMode'] ?? '' ) && is_array( $results ) ) { $results = $review_stager->stageImageAlts( $results, $options ); } $succeeded_count = is_array( $results ) ? BatchOutcome::succeededCount( $results ) : 0; if ( $succeeded_count > 0 ) { \AIPT\Core\Services\UsageTracker::record_event( 'image_alt', 'generated', $succeeded_count, array( 'product_id' => BatchOutcome::firstSucceededProductId( $results ) ) ); } $response_data = array( 'results' => $results, 'success' => $succeeded_count > 0, 'applied_free_defaults' => $applied_defaults, ); if ( array() !== $not_attempted ) { $response_data[ GenerateTimeBudget::NOT_ATTEMPTED ] = $not_attempted; } if ( array() !== $not_attempted_images ) { $response_data['not_attempted_images'] = []; foreach ( $not_attempted_images as $skipped_product_id => $skipped_attachment_ids ) { $response_data['not_attempted_images'][] = [ 'productId' => (int) $skipped_product_id, 'attachmentIds' => $skipped_attachment_ids, ]; } } if ( ! empty( $applied_defaults ) ) { $response_data['applied_free_defaults_reason'] = PlanDenial::reason( self::PAID_OPTION_FEATURES[ $applied_defaults[0] ], PlanDenial::PLAN_PAID ); } if ( ! empty( $options['downgraded_mode'] ) ) { $response_data['downgraded_mode'] = true; $response_data['downgraded_mode_reason'] = PlanDenial::reason( 'contentReview', PlanDenial::PLAN_BUSINESS ); } return $this->finish_generate_claim( $claim_key, $this->success_response( $response_data ), $request ); } catch ( \Exception $e ) { $requested_provider = isset( $options['provider'] ) && is_string( $options['provider'] ) && '' !== $options['provider'] ? $options['provider'] : get_option( 'aipt_api_provider', 'openai' ); return $this->finish_generate_claim( $claim_key, ErrorHandler::create_wp_error( ProviderCallException::displayMessage( $e, (string) $requested_provider ), 'aipt_image_alt_generation_error' ), $request ); } } /** * The product and image pairs the current user may generate for, as the * service will decide each one. Part of the claim key, so a request * repeated after the user lost access to an image or product is not * answered from the earlier result. * * @param array $items The request's `selections` (`productId`, `attachmentIds`), or its product ids. * @param bool $by_selections Whether $items are selections; otherwise product ids, whose images the service derives. * @param array $options Validated request options. * @return string[] `product:attachment` of each allowed pair. */ private static function authorized_pairs( array $items, bool $by_selections, array $options ): array { $pairs = []; if ( $by_selections ) { foreach ( $items as $selection ) { foreach ( $selection['attachmentIds'] as $attachment_id ) { $pairs[] = [ $selection['productId'], $attachment_id ]; } } } else { foreach ( $items as $product_id ) { $product = wc_get_product( $product_id ); if ( ! $product ) { continue; } foreach ( Service::candidate_image_ids( $product, $options ) as $attachment_id ) { $pairs[] = [ $product_id, $attachment_id ]; } } } $allowed = []; foreach ( $pairs as $pair ) { if ( null === self::authorizationFailureMessage( (int) $pair[1], (int) $pair[0] ) ) { $allowed[] = $pair[0] . ':' . $pair[1]; } } return $allowed; } /** * Paid option (as reported in applied_free_defaults) => feature key. * * All of them are gated for any paid plan. The legacy v1 includeGallery * expansion shares the enrichment gate (aipt_image_alt_validate_options). * * @var array */ private const PAID_OPTION_FEATURES = [ 'includeGallery' => 'imageAltEnrichment', 'enrichWithAttributes' => 'imageAltEnrichment', 'siteAdditionalPrompt' => 'imageAltAdditionalPrompt', ]; /** * List the paid options that were requested but replaced by Free defaults. * * Only a real downgrade is reported: a flag the premium callback restored * is not. The stored site-level prompt is reported when it exists and the * gate skips it; it is read here only to report, never applied. * * @param array $requested Request options. * @param array $controlled Options after applyPremiumControls(). * @return string[] Keys of PAID_OPTION_FEATURES. */ private function detectAppliedFreeDefaults( array $requested, array $controlled ): array { $dropped = []; foreach ( [ 'includeGallery', 'enrichWithAttributes' ] as $flag ) { if ( filter_var( $requested[ $flag ] ?? false, FILTER_VALIDATE_BOOLEAN ) && empty( $controlled[ $flag ] ) ) { $dropped[] = $flag; } } if ( ! BlueprintIntegration::usesBlueprint( Generators::IMAGE_ALT, BlueprintIntegration::jobTrustedFacts() ) && ! apply_filters( 'aipt_image_alt_additional_prompt_enabled', false ) && '' !== trim( (string) get_option( 'aipt_image_alt_additional_prompt', '' ) ) ) { $dropped[] = 'siteAdditionalPrompt'; } return $dropped; } public function bulk_apply( WP_REST_Request $request ) { try { $rate_check = $this->checkRateLimit( (int) \get_current_user_id(), 'image_alt_apply' ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $params = $request->get_json_params(); if ( ! is_array( $params ) ) { return $this->error_response( 'invalid_payload', __( 'Invalid request payload.', 'ai-product-tools' ) ); } $results = (array) ( $params['results'] ?? [] ); if ( ! $this->validate_bulk_apply_results( $results ) ) { return $this->error_response( 'invalid_results', __( 'Invalid image alt results provided to apply.', 'ai-product-tools' ) ); } $apply_options = (array) ( $params['options'] ?? [] ); $default_overwrite = isset( $apply_options['overwrite'] ) && 'empty_only' === $apply_options['overwrite'] ? 'empty_only' : 'replace'; $updated = 0; $failed = 0; $outcomes = array(); $changed_products = array(); $review_queue = ReviewQueueStaging::availableStager(); try { foreach ( $results as $item ) { $attachment_id = absint( $item['attachment_id'] ?? 0 ); $product_id = absint( $item['product_id'] ?? 0 ); $alt_text = sanitize_text_field( $item['alt_text'] ?? '' ); $status = sanitize_text_field( $item['status'] ?? '' ); $outcome = array( 'product_id' => $product_id, 'attachment_id' => $attachment_id, 'status' => 'error', ); if ( $attachment_id <= 0 || $product_id <= 0 ) { $failed++; $outcome['message'] = __( 'This result has no valid image or product. Generate it again, then retry.', 'ai-product-tools' ); $outcomes[] = $outcome; continue; } if ( in_array( $status, array( 'error', 'rejected', 'needs_review' ), true ) ) { $failed++; $outcome['message'] = __( 'This result was not approved for applying. Review it or generate it again.', 'ai-product-tools' ); $outcomes[] = $outcome; continue; } $refusal = self::authorizationFailureMessage( $attachment_id, $product_id ); if ( null !== $refusal ) { $failed++; $outcome['message'] = $refusal; $outcomes[] = $outcome; continue; } if ( null !== $review_queue && $review_queue->hasActiveReview( $product_id, 'image_alt', 'image_alt', $attachment_id ) ) { $failed++; $outcome['status'] = 'review_pending'; $outcome['message'] = __( 'This image is already pending review in the Content Review queue.', 'ai-product-tools' ); $outcomes[] = $outcome; continue; } $current_alt = (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); if ( $current_alt === $alt_text ) { $updated++; $outcome['status'] = 'applied'; $outcomes[] = $outcome; continue; } $overwrite = isset( $item['overwrite'] ) && 'empty_only' === $item['overwrite'] ? 'empty_only' : $default_overwrite; if ( 'empty_only' === $overwrite && '' !== trim( $current_alt ) ) { $updated++; $outcome['status'] = 'applied'; $outcome['skipped'] = true; $outcome['message'] = __( 'This image already has alt text; nothing was written.', 'ai-product-tools' ); $outcomes[] = $outcome; continue; } if ( array_key_exists( 'current_alt', $item ) && is_scalar( $item['current_alt'] ) ) { $expected_current = (string) $item['current_alt']; if ( $current_alt !== $expected_current ) { $failed++; $outcome['status'] = 'conflict'; $outcome['message'] = __( "This image's alt text changed since this result was generated. Regenerate or apply manually.", 'ai-product-tools' ); $outcomes[] = $outcome; continue; } } $item_blueprint = BlueprintAttributionSanitizer::sanitizeOrEmpty( $item['blueprint'] ?? null ); $landed = ProductFieldWriter::apply( $product_id, 'image_alt', array( 'image_alt' => array( array( 'attachment_id' => $attachment_id ) ) ), static function () use ( $attachment_id, $alt_text ): array { $result = update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $alt_text ) ); return array( 'image_alt' => false !== $result ); }, array( 'attribution' => array( 'blueprint_id' => $item_blueprint['id'], 'blueprint_name' => $item_blueprint['name'], 'blueprint_revision' => $item_blueprint['revision'], 'blueprint_builtin' => $item_blueprint['builtin'], ), 'bumps' => array( $attachment_id ), ) ); if ( ! $landed['image_alt'] ) { $failed++; $outcome['message'] = __( 'Alt text could not be saved. Please retry.', 'ai-product-tools' ); } else { $updated++; $outcome['status'] = 'applied'; $changed_products[ $product_id ] = true; } $outcomes[] = $outcome; } } finally { $this->markChangedProducts( array_keys( $changed_products ) ); } if ( $updated > 0 ) { \AIPT\Core\Services\UsageTracker::record_event( 'image_alt', 'applied', $updated, array( 'label' => sprintf( '%d image(s)', $updated ) ) ); } return $this->success_response( [ 'updated' => $updated, 'failed' => $failed, 'results' => $outcomes, ] ); } catch ( \Throwable $e ) { \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeAllStaged( false ); return $this->error_response( 'apply_error', ErrorHandler::sanitize_error_for_display( $e->getMessage() ), 500 ); } } /** * Mark 'image_alt' and bump the edit token of each product whose alt text * changed, once per product. * * Both steps run for every product, even when an earlier step failed: a * retry skips an alt text that is already there, so a product left out * here would never get them. The alt texts are written and their * snapshots committed by now, so a failure is logged and never turns the * apply into an error, as in the product panel's description apply. * * @param array $product_ids Products with at least one changed alt text. * @return void */ private function markChangedProducts( array $product_ids ): void { foreach ( $product_ids as $product_id ) { $product_id = (int) $product_id; try { if ( ! ContentMarkService::mark( $product_id, 'image_alt', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) ) ) { Logger::error( 'generation', 'AI mark of an applied alt text was not stored', array( 'product_id' => $product_id ) ); } } catch ( \Throwable $e ) { Logger::error( 'generation', 'AI mark of an applied alt text failed', array( 'product_id' => $product_id, 'error' => $e->getMessage(), ) ); } try { \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( $product_id ); } catch ( \Throwable $e ) { Logger::error( 'generation', 'Edit token bump after an applied alt text failed', array( 'product_id' => $product_id, 'error' => $e->getMessage(), ) ); } } } public function validate_bulk_apply_results( $value ): bool { if ( ! is_array( $value ) || empty( $value ) ) { return false; } foreach ( $value as $item ) { if ( ! is_array( $item ) ) { return false; } if ( absint( $item['attachment_id'] ?? 0 ) <= 0 || absint( $item['product_id'] ?? 0 ) <= 0 ) { return false; } if ( ! array_key_exists( 'alt_text', $item ) || ! is_scalar( $item['alt_text'] ) ) { return false; } } return true; } /** * Canonical Image Alt authorization policy: the attachment must belong to * the product (featured image, gallery, or one of the product's own * variations — see Service::variation_images()) AND the current user * must be able to edit BOTH the attachment and the product. Public + * static so other apply paths (e.g. ContentReviewApplier's * ImageAltApplier) reuse the exact same policy instead of re-deriving * it. A thin wrapper over {@see authorizationFailureMessage()}, which * every caller that can show the specific reason uses instead. * * @param int $attachment_id Attachment id. * @param int $product_id Product id. * @return bool */ public static function can_update_attachment_alt( int $attachment_id, int $product_id ): bool { return null === self::authorizationFailureMessage( $attachment_id, $product_id ); } /** * The same authorization policy as {@see can_update_attachment_alt()}, * returning why a refusal happened instead of collapsing five * independent reasons into one boolean. The product-eligibility branch * reuses ProductEligibility::refusalMessage() verbatim rather than a * message of its own, so a "this is a variation"/"this status can't be * generated for" refusal reads identically everywhere it is checked. * * @param int $attachment_id Attachment id. * @param int $product_id Product id. * @return string|null A user-facing reason, or null when allowed. */ public static function authorizationFailureMessage( int $attachment_id, int $product_id ): ?string { if ( ! \wp_get_attachment_image_url( $attachment_id, 'full' ) ) { return __( 'This attachment could not be found or is not a usable image.', 'ai-product-tools' ); } if ( ! current_user_can( 'edit_post', $attachment_id ) ) { return __( 'You do not have permission to edit this image.', 'ai-product-tools' ); } $product = wc_get_product( $product_id ); $product_refusal = ProductEligibility::refusalMessage( $product ); if ( null !== $product_refusal ) { return $product_refusal; } if ( ! current_user_can( 'edit_post', $product_id ) ) { return __( 'You do not have permission to edit this product.', 'ai-product-tools' ); } if ( (int) $product->get_image_id() === $attachment_id ) { return null; } $gallery_ids = array_map( 'absint', (array) $product->get_gallery_image_ids() ); if ( in_array( $attachment_id, $gallery_ids, true ) ) { return null; } $variation_image_ids = array_column( Service::variation_images( $product ), 'id' ); if ( in_array( $attachment_id, $variation_image_ids, true ) ) { return null; } return __( "This image is not part of this product's images.", 'ai-product-tools' ); } public function get_product_images( WP_REST_Request $request ) { try { $product_id = absint( $request->get_param( 'product_id' ) ); $product = wc_get_product( $product_id ); if ( ! $product ) { return $this->error_response( 'product_not_found', __( 'Product not found.', 'ai-product-tools' ), 404 ); } if ( ! current_user_can( 'edit_post', $product_id ) ) { return $this->error_response( 'rest_forbidden', __( 'You are not allowed to view the images of this product.', 'ai-product-tools' ), 403 ); } $data = $this->service->get_product_images( $product_id ); return $this->success_response( $data ); } catch ( \Exception $e ) { return $this->error_response( 'fetch_images_error', ErrorHandler::sanitize_error_for_display( $e->getMessage() ), 500 ); } } }