service = new Service(); } public function register_routes(): void { $bulk_generate_endpoint = [ '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' => [], 'sanitize_callback' => function ( $param ) { return array_map( 'absint', (array) $param ); }, ], 'options' => [ 'type' => 'object', 'required' => false, 'default' => [], ], ], ]; 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['permission_callback'] = [ $this, 'check_permissions_editor_bulk_write' ]; 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; } 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'] ?? [] ); $options = $this->enforce_generation_mode( $options ); $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' ) ); } $results = $this->service->bulk_generate_by_selections( $sanitized_selections, $options, [ $this, 'authorizationFailureMessage' ] ); } 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' ) ); } $results = $this->service->bulk_generate( array_values( $product_ids ), $options, [ $this, 'authorizationFailureMessage' ] ); } if ( 'server_review' === ( $options['generationMode'] ?? '' ) ) { $reviewStore = new ContentReviewStore(); foreach ( $results as &$item ) { if ( ! is_array( $item ) ) { continue; } $product_id = $item['product_id'] ?? 0; $attachment_id = $item['attachment_id'] ?? 0; $alt_text = sanitize_text_field( (string) ( $item['alt_text'] ?? '' ) ); $status = $item['status'] ?? ''; if ( $product_id <= 0 || $attachment_id <= 0 || ! $this->can_update_attachment_alt( (int) $attachment_id, (int) $product_id ) ) { continue; } if ( 'error' === $status || 'needs_review' === $status || '' === $alt_text ) { continue; } $encoded = wp_json_encode( array( array( 'attachment_id' => (int) $attachment_id, 'alt_text' => (string) $alt_text, ), ) ); if ( false === $encoded ) { $item['review_stage_failed'] = true; $item['review_stage_error'] = __( 'Could not encode the alt text for review staging. Try again.', 'ai-product-tools' ); continue; } $item_blueprint = isset( $item['blueprint'] ) && is_array( $item['blueprint'] ) ? $item['blueprint'] : array(); $reviewId = $reviewStore->stage( (int) $product_id, 'image_alt', 'image_alt', (int) $attachment_id, $encoded, array( 'apply_context' => array( 'overwrite' => 'empty_only' === ( $options['overwrite'] ?? 'replace' ) ? 'empty_only' : 'replace', ), 'blueprint_id' => isset( $item_blueprint['id'] ) ? (int) $item_blueprint['id'] : 0, 'blueprint_name' => isset( $item_blueprint['name'] ) ? (string) $item_blueprint['name'] : '', 'blueprint_revision' => isset( $item_blueprint['revision'] ) ? (int) $item_blueprint['revision'] : 0, 'blueprint_builtin' => ! empty( $item_blueprint['builtin'] ), ) ); if ( null === $reviewId ) { $item['review_stage_failed'] = true; $item['review_stage_error'] = __( 'A previous approval for this image is still in progress. Try again shortly.', 'ai-product-tools' ); continue; } $item['staged_for_review'] = true; } unset( $item ); } $first_image_pid = 0; if ( ! empty( $sanitized_selections ) && isset( $sanitized_selections[0]['productId'] ) ) { $first_image_pid = (int) $sanitized_selections[0]['productId']; } elseif ( isset( $product_ids ) && is_array( $product_ids ) && ! empty( $product_ids ) ) { $first_image_pid = (int) $product_ids[ array_key_first( $product_ids ) ]; } \AIPT\Core\Services\UsageTracker::record_event( 'image_alt', 'generated', is_array( $results ) ? count( $results ) : 1, array( 'product_id' => $first_image_pid ) ); $succeeded_count = 0; foreach ( (array) $results as $item ) { if ( is_array( $item ) && empty( $item['error'] ) && empty( $item['review_stage_failed'] ) ) { ++$succeeded_count; } } $response_data = array( 'results' => $results, 'success' => $succeeded_count > 0, 'applied_free_defaults' => $applied_defaults, ); 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->success_response( $response_data ); } catch ( \Exception $e ) { $requested_provider = isset( $options['provider'] ) && is_string( $options['provider'] ) && '' !== $options['provider'] ? $options['provider'] : get_option( 'aipt_api_provider', 'openai' ); return ErrorHandler::create_wp_error( ProviderCallException::displayMessage( $e, (string) $requested_provider ), 'aipt_image_alt_generation_error' ); } } /** * 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; } /** * Enforce the tri-state generationMode contract server-side. * * Sanitizes the incoming mode and downgrades 'server_review' to * 'client_preview' when the content review feature is not enabled * (non-Business, non-grandfathered). * * @param array $options Request options. * @return array Options with enforced generationMode. */ private function enforce_generation_mode( array $options ): array { $mode = ( isset( $options['generationMode'] ) && is_string( $options['generationMode'] ) ) ? $options['generationMode'] : ''; $options['generationMode'] = in_array( $mode, array( 'immediate', 'client_preview', 'server_review' ), true ) ? $mode : 'client_preview'; if ( 'server_review' === $options['generationMode'] && ! apply_filters( 'aipt_content_review_enabled', false ) ) { $options['generationMode'] = 'client_preview'; $options['downgraded_mode'] = true; } return $options; } 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(); $reviewStore = new ContentReviewStore(); 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 ( $reviewStore->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 ); \AIPT\Api\Rollback\ContentApplyDispatcher::before( $product_id, array( 'image_alt' => array( array( 'attachment_id' => $attachment_id ) ), 'blueprint_id' => $item_blueprint['id'], 'blueprint_name' => $item_blueprint['name'], 'blueprint_revision' => $item_blueprint['revision'], 'blueprint_builtin' => $item_blueprint['builtin'], ), 'image_alt' ); $result = update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( $alt_text ) ); $success = false !== $result; \AIPT\Api\Rollback\ContentApplyDispatcher::after( $product_id, $success ); if ( ! $success ) { $failed++; $outcome['message'] = __( 'Alt text could not be saved. Please retry.', 'ai-product-tools' ); } else { $updated++; $outcome['status'] = 'applied'; $changed_products[ $product_id ] = true; \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( $attachment_id ); } $outcomes[] = $outcome; } foreach ( array_keys( $changed_products ) as $marked_product_id ) { ContentMarkService::mark( (int) $marked_product_id, 'image_alt', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) ); \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( (int) $marked_product_id ); } 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 ); } } 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 ); } } }