service = new TitleGeneratorService(); } public function register_routes() { $bulk_generate_endpoint = array( 'methods' => 'POST', 'callback' => array( $this, 'bulk_generate' ), 'permission_callback' => array( $this, 'check_permissions_write' ), 'args' => array( 'productIds' => array( 'type' => 'array', 'required' => true, 'sanitize_callback' => function ( $param ) { if ( ! is_array( $param ) ) { return array(); } return array_map( 'absint', $param ); }, ), 'options' => array( 'type' => 'object', 'required' => true, ), ), ); register_rest_route( 'aipt/v1', '/title-generator/bulk-generate', $bulk_generate_endpoint ); $editor_bulk_generate_endpoint = $bulk_generate_endpoint; $editor_bulk_generate_endpoint['permission_callback'] = array( $this, 'check_permissions_editor_bulk_write' ); register_rest_route( 'aipt/v1', '/title-generator/editor-bulk-generate', $editor_bulk_generate_endpoint ); register_rest_route( 'aipt/v1', '/title-generator/bulk-apply', array( 'methods' => 'POST', 'callback' => array( $this, 'bulk_apply' ), 'permission_callback' => array( $this, 'check_permissions_write' ), 'args' => array( 'results' => array( 'type' => 'array', 'required' => true, ), 'options' => array( 'type' => 'object', 'required' => false, ), ), ) ); register_rest_route( 'aipt/v1', '/title-generator/bulk-reject', array( 'methods' => 'POST', 'callback' => array( $this, 'bulk_reject' ), 'permission_callback' => array( $this, 'check_permissions_write' ), 'args' => array( 'results' => array( 'required' => true, 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'product_id' => array( 'required' => true, 'type' => 'integer', ), ), ), 'maxItems' => self::MAX_BULK_REJECT_ITEMS, ), ), ) ); } /** * Tones available to every plan. * * Tone selection was freed for all plans in the 2026-09 Free/Business tier * decision; the list mirrors TitlePromptFactory::getToneGuidance() keys so * every accepted tone has real prompt guidance behind it. * * @var string[] */ public const FREE_TONES = array( 'SEO-Focused', 'Professional', 'Casual', 'Luxury', 'Technical', 'Persuasive' ); /** * 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 : 'SEO-Focused'; } /** * Free defaults of the options the premium restore filter controls. * * @var array */ private const FREE_OPTION_DEFAULTS = array( 'keywords' => '', 'mode' => 'rewrite', 'titleSources' => array( 'product_description' ), ); /** * Title sources TitlePromptFactory::buildSourceData() reads. * * @var string[] */ private const TITLE_SOURCES = array( 'existing_title', 'product_name', 'product_description', 'product_tags', 'product_categories', 'product_attributes' ); /** * The title sources every plan may select: the product name and the * description. The others (existing title, tags, categories, attributes) * are Business. * * @var string[] */ public const FREE_TITLE_SOURCES = array( 'product_name', 'product_description' ); /** * The title sources a non-entitled site keeps from a request: the free * ones it asked for, else the free default (the description alone). * What an entitled site keeps is decided by the premium restore filter, * which sees the original request as well. * * @param mixed $requested The request's `titleSources`. * @return string[] */ public static function freeTitleSources( $requested ): array { $sources = is_array( $requested ) ? array_values( array_unique( array_intersect( array_filter( $requested, 'is_string' ), self::FREE_TITLE_SOURCES ) ) ) : array(); return empty( $sources ) ? self::FREE_OPTION_DEFAULTS['titleSources'] : $sources; } /** * Controlled options whose requested paid value was replaced by its Free default. * * A key is reported only when the effective value IS the Free default and * the request, normalized the way generation reads it (sanitized keywords, * known modes and sources), asked for something else. A value an entitled * site kept, only reformatted by sanitization, is never reported. * * @param array $requested Request options. * @param array $effective Options after Free defaults and the premium restore filter. * @return string[] */ private static function appliedFreeDefaults( array $requested, array $effective ): array { $applied = array(); foreach ( self::FREE_OPTION_DEFAULTS as $key => $default ) { if ( ! array_key_exists( $key, $requested ) ) { continue; } if ( 'titleSources' === $key ) { $default = self::freeTitleSources( $requested[ $key ] ); } if ( self::normalizeControlledOption( $key, $effective[ $key ] ?? $default ) !== $default ) { continue; } if ( self::normalizeControlledOption( $key, $requested[ $key ] ) !== $default ) { $applied[] = $key; } } return $applied; } /** * Normalize a controlled option for the dropped-option comparison. * * @param string $key Controlled option key. * @param mixed $value Option value. * @return mixed */ private static function normalizeControlledOption( string $key, $value ) { switch ( $key ) { case 'keywords': return is_scalar( $value ) ? sanitize_text_field( (string) $value ) : ''; case 'mode': return in_array( $value, array( 'rewrite', 'improve' ), true ) ? $value : self::FREE_OPTION_DEFAULTS['mode']; default: $sources = is_array( $value ) ? array_values( array_intersect( array_filter( $value, 'is_string' ), self::TITLE_SOURCES ) ) : array(); return empty( $sources ) ? self::FREE_OPTION_DEFAULTS['titleSources'] : $sources; } } /** * Apply premium feature controls to options. * * Uses filter hook to allow Premium module to preserve premium options. * Free version always uses default values for premium features. * * @param array $options Request options. * @return array Validated options. */ private function applyPremiumControls( $options ) { $default_options = array( 'keywords' => '', 'mode' => 'rewrite', 'titleSources' => self::freeTitleSources( $options['titleSources'] ?? null ), ); $controlled_options = array_merge( $options, $default_options ); /** * Filter title generator validated options. * * Premium module can hook here to preserve premium option values * when a valid license is present. * * @since 2.5.0 * @param array $controlled_options Options with free defaults applied. * @param array $options Original request options. */ $controlled_options = apply_filters( 'aipt_title_validate_options', $controlled_options, $options ); $controlled_options['tone'] = self::normalizeTone( $controlled_options['tone'] ?? '' ); return $controlled_options; } 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 ); } $products = $request->get_param( 'productIds' ) ?? array(); $options = $request->get_param( 'options' ) ?? array(); $requested_options = $options; $options = $this->applyPremiumControls( $options ); $applied_defaults = self::appliedFreeDefaults( $requested_options, $options ); if ( self::site_additional_prompt_skipped( Generators::TITLE, 'aipt_title_additional_prompt', 'aipt_title_additional_prompt_enabled' ) ) { $applied_defaults[] = 'siteAdditionalPrompt'; } $options = $this->enforce_generation_mode( $options ); if ( empty( $products ) ) { throw new \Exception( __( 'No products provided.', 'ai-product-tools' ) ); } if ( ! is_array( $products ) ) { throw new \Exception( __( 'Invalid products format. Expected array.', 'ai-product-tools' ) ); } $authorized_products = array(); $denied_results = array(); foreach ( $products as $product_id ) { $id = (int) $product_id; $product = wc_get_product( $id ); $refusal = ProductEligibility::refusalMessage( $product ); if ( null !== $refusal ) { $denied_results[] = array( 'product_id' => $id, 'type' => 'title', 'text' => '', 'api_error' => $refusal, ); continue; } if ( current_user_can( 'edit_post', $id ) ) { $authorized_products[] = $product_id; continue; } $denied_results[] = array( 'product_id' => $id, 'type' => 'title', 'text' => '', 'api_error' => __( 'You do not have permission to edit this product.', 'ai-product-tools' ), ); } $result = empty( $authorized_products ) ? array() : $this->service->bulk_generate( $authorized_products, $options ); if ( 'server_review' === ( $options['generationMode'] ?? '' ) && is_array( $result ) ) { $reviewStore = new ContentReviewStore(); $update_slug = ! empty( $options['updateSlug'] ); $review_overwrite = 'empty_only' === ( $options['overwrite'] ?? 'replace' ) ? 'empty_only' : 'replace'; foreach ( $result as &$item ) { $product_id = $item['product_id'] ?? 0; $title = $item['text'] ?? ( $item['variants'][0] ?? '' ); if ( 'needs_review' === ( $item['status'] ?? '' ) || ! empty( $item['api_error'] ) ) { continue; } if ( '' === $title ) { if ( ! isset( $item['api_error'] ) ) { $item['api_error'] = __( 'Title generation failed for this product.', 'ai-product-tools' ); } continue; } if ( $product_id > 0 && wc_get_product( (int) $product_id ) && current_user_can( 'edit_post', (int) $product_id ) ) { $item_blueprint = isset( $item['blueprint'] ) && is_array( $item['blueprint'] ) ? $item['blueprint'] : array(); $reviewId = $reviewStore->stage( (int) $product_id, 'title', 'title', 0, (string) $title, array( 'apply_context' => array( 'update_slug' => $update_slug, 'overwrite' => $review_overwrite, ), '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 product is still in progress. Try again shortly.', 'ai-product-tools' ); } } else { $item['review_stage_failed'] = true; $item['review_stage_error'] = __( 'This product could not be queued for review.', 'ai-product-tools' ); } } unset( $item ); } \AIPT\Core\Services\UsageTracker::record_event( 'title', 'generated', is_array( $result ) ? count( $result ) : count( (array) $products ), array( 'product_id' => is_array( $products ) && ! empty( $products ) ? (int) $products[ array_key_first( $products ) ] : 0, ) ); if ( ! empty( $denied_results ) ) { $result = array_merge( is_array( $result ) ? $result : array(), $denied_results ); } $outcome = BatchOutcome::of( (array) $result, __( 'Title generation failed.', 'ai-product-tools' ) ); $response_data = array( 'results' => $result, 'success' => $outcome['success'], 'applied_free_defaults' => $applied_defaults, ); if ( ! $outcome['success'] ) { $response_data['message'] = $outcome['message']; } if ( ! empty( $applied_defaults ) ) { $response_data['applied_free_defaults_reason'] = PlanDenial::reason( array( 'siteAdditionalPrompt' ) === $applied_defaults ? 'additionalTitlePrompts' : 'advancedTitleOptions', 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 new WP_REST_Response( $response_data, 200 ); } catch ( \Exception $e ) { $api_provider = (string) ( $options['provider'] ?? get_option( 'aipt_api_provider', 'openai' ) ); return ErrorHandler::create_wp_error( ProviderCallException::displayMessage( $e, $api_provider ), 'aipt_title_generation_error' ); } } /** * 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( $request ) { try { $rate_check = $this->checkRateLimit( (int) get_current_user_id(), static::RATE_LIMIT_SCOPE . '_apply' ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $params = $request->get_json_params(); $results = $params['results'] ?? array(); if ( empty( $results ) ) { return new \WP_Error( 'invalid_request', __( 'No titles to apply', 'ai-product-tools' ), array( 'status' => 400 ) ); } $apply_options = is_array( $params['options'] ?? null ) ? $params['options'] : array(); $default_overwrite = isset( $apply_options['overwrite'] ) && 'empty_only' === $apply_options['overwrite'] ? 'empty_only' : 'replace'; $success_count = 0; $skipped_count = 0; $failed_ids = array(); $failed_items = array(); $kept_ids = array(); $total_processed = 0; $saved_ids = array(); $prev_term = \wp_defer_term_counting(); $prev_comm = \wp_defer_comment_counting(); \wp_defer_term_counting( true ); \wp_defer_comment_counting( true ); $prev_cache = \wp_suspend_cache_invalidation( true ); $missing_text_count = 0; try { foreach ( $results as $result ) { $product_id = $result['product_id'] ?? null; $title = $result['title'] ?? null; if ( null === $title || '' === $title ) { $title = $result['text'] ?? null; } $status = $result['status'] ?? 'pending'; $update_slug = ! empty( $result['update_slug'] ); if ( null === $product_id || '' === $product_id ) { $skipped_count++; continue; } if ( null === $title || '' === $title ) { $missing_text_count++; $skipped_count++; continue; } if ( ! is_scalar( $title ) && ! ( is_object( $title ) && method_exists( $title, '__toString' ) ) ) { $failed_ids[] = (int) $product_id; $failed_items[] = array( 'product_id' => (int) $product_id, 'message' => __( 'The generated title could not be read.', 'ai-product-tools' ), ); continue; } if ( 'rejected' === $status ) { $skipped_count++; continue; } if ( 'needs_review' === $status ) { $failed_ids[] = (int) $product_id; $failed_items[] = array( 'product_id' => (int) $product_id, 'message' => __( 'This title still needs review before it can be applied.', 'ai-product-tools' ), ); continue; } if ( ! empty( $result['api_error'] ) ) { $failed_ids[] = (int) $product_id; $failed_items[] = array( 'product_id' => (int) $product_id, 'message' => __( 'This title failed to generate and cannot be applied.', 'ai-product-tools' ), ); continue; } if ( ! current_user_can( 'edit_post', (int) $product_id ) ) { $failed_ids[] = (int) $product_id; $failed_items[] = array( 'product_id' => (int) $product_id, 'message' => __( 'You do not have permission to edit this product.', 'ai-product-tools' ), ); continue; } $product = wc_get_product( $product_id ); if ( ! $product instanceof \WC_Product ) { $skipped_count++; continue; } if ( ! ProductEligibility::isEligible( $product ) ) { $failed_ids[] = (int) $product_id; $failed_items[] = array( 'product_id' => (int) $product_id, 'message' => ProductEligibility::refusalMessage( $product ), ); continue; } /** @var \WC_Product $product */ $total_processed++; $sanitized_title = sanitize_text_field( (string) $title ); if ( '' === trim( $sanitized_title ) ) { $failed_ids[] = (int) $product_id; $failed_items[] = array( 'product_id' => (int) $product_id, 'message' => __( 'The generated title is empty after removing unsupported content.', 'ai-product-tools' ), ); continue; } if ( ! empty( $result['review'] ) ) { $review_overwrite = isset( $result['overwrite'] ) && 'empty_only' === $result['overwrite'] ? 'empty_only' : $default_overwrite; $result_blueprint = BlueprintAttributionSanitizer::sanitize( $result['blueprint'] ?? null ); $title_opts = array( 'apply_context' => array( 'update_slug' => $update_slug, 'overwrite' => $review_overwrite, ), ); if ( null !== $result_blueprint ) { $title_opts['blueprint_id'] = $result_blueprint['id']; $title_opts['blueprint_name'] = $result_blueprint['name']; $title_opts['blueprint_revision'] = $result_blueprint['revision']; $title_opts['blueprint_builtin'] = $result_blueprint['builtin']; } $outcome = ( new ReviewQueueDecision() )->approve( (int) $product_id, 'title', array( 'title' => array( 'value' => $sanitized_title, 'opts' => $title_opts, ), ), array( 'title' ), array( 'title' ) ); if ( $outcome['success'] ) { $success_count++; $saved_ids[] = (int) $product_id; } else { $failed_ids[] = (int) $product_id; $failed_items[] = self::reviewFailureItem( (int) $product_id, $outcome ); } continue; } $overwrite = isset( $result['overwrite'] ) && 'empty_only' === $result['overwrite'] ? 'empty_only' : $default_overwrite; if ( 'empty_only' === $overwrite && '' !== trim( (string) $product->get_name() ) ) { $kept_ids[] = (int) $product_id; continue; } if ( ! $update_slug && $sanitized_title === (string) $product->get_name() ) { $success_count++; continue; } $title_snapshot_fields = array( 'title' => $sanitized_title ); if ( $update_slug ) { $title_snapshot_fields['slug'] = true; } $result_blueprint = BlueprintAttributionSanitizer::sanitizeOrEmpty( $result['blueprint'] ?? null ); $title_snapshot_fields['blueprint_id'] = $result_blueprint['id']; $title_snapshot_fields['blueprint_name'] = $result_blueprint['name']; $title_snapshot_fields['blueprint_revision'] = $result_blueprint['revision']; $title_snapshot_fields['blueprint_builtin'] = $result_blueprint['builtin']; \AIPT\Api\Rollback\ContentApplyDispatcher::before( (int) $product_id, $title_snapshot_fields, 'title' ); $product->set_name( $sanitized_title ); if ( $update_slug ) { $product->set_slug( sanitize_title( $sanitized_title ) ); } $save_result = \AIPT\Api\Helpers\ProductSaveVerifier::save( $product ); $saved = $save_result['landed']; \AIPT\Api\Rollback\ContentApplyDispatcher::after( (int) $product_id, $saved ); if ( $saved ) { $success_count++; $saved_ids[] = (int) $product_id; ContentMarkService::mark( (int) $product_id, 'title', array( 'gen' => MetaKeys::GEN_BULK_STANDARD ) ); } else { $failed_ids[] = $product_id; $failed_items[] = array( 'product_id' => (int) $product_id, 'message' => __( 'The product could not be saved.', 'ai-product-tools' ), ); } } } finally { \wp_suspend_cache_invalidation( $prev_cache ); \wp_defer_comment_counting( $prev_comm ); \wp_defer_term_counting( $prev_term ); foreach ( $saved_ids as $saved_id ) { \clean_post_cache( $saved_id ); \wc_delete_product_transients( $saved_id ); } } $kept_count = count( $kept_ids ); $overall_success = $success_count > 0 || ( $kept_count > 0 && empty( $failed_ids ) ); if ( $kept_count > 0 && empty( $failed_ids ) ) { $message = sprintf( /* translators: 1: Number of titles applied, 2: Number of products whose existing title was kept */ _n( '%1$d title applied. Products that kept their existing title: %2$d.', '%1$d titles applied. Products that kept their existing title: %2$d.', $success_count, 'ai-product-tools' ), $success_count, $kept_count ); } elseif ( $success_count === $total_processed && $total_processed > 0 ) { $message = sprintf( /* translators: %d: Number of titles applied */ _n( '%d title applied successfully.', '%d titles applied successfully.', $success_count, 'ai-product-tools' ), $success_count ); } elseif ( $success_count > 0 ) { $message = sprintf( /* translators: %1$d: Number of successful updates, %2$d: Number of failed updates */ _n( '%1$d title applied successfully, %2$d failed.', '%1$d titles applied successfully, %2$d failed.', $success_count, 'ai-product-tools' ), $success_count, count( $failed_ids ) ); } elseif ( 0 === $total_processed ) { $message = ( $missing_text_count > 0 && $missing_text_count === $skipped_count ) ? __( "No valid titles to apply. Each item needs a non-empty 'title' or 'text' field.", 'ai-product-tools' ) : __( 'No valid titles to apply. All items were skipped.', 'ai-product-tools' ); } else { $message = __( 'No titles were applied. All updates failed.', 'ai-product-tools' ); } if ( $success_count > 0 ) { \AIPT\Core\Services\UsageTracker::record_event( 'title', 'applied', $success_count, array( 'product_id' => is_array( $results ) && ! empty( $results ) && isset( $results[0]['product_id'] ) ? (int) $results[0]['product_id'] : 0, ) ); } return new \WP_REST_Response( array( 'success' => $overall_success, 'message' => $message, 'data' => array( 'total_processed' => $total_processed, 'updated' => $success_count, 'skipped' => $skipped_count, 'failed' => count( $failed_ids ), 'failed_ids' => $failed_ids, 'failed_items' => $failed_items, 'kept_ids' => $kept_ids, ), ), 200 ); } catch ( \Throwable $e ) { \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeAllStaged( false ); $message = ErrorHandler::sanitize_error_for_display( $e->getMessage() ); $status = ErrorHandler::extract_http_status_from_message( $message, 500 ); return new \WP_Error( 'apply_error', $message, array( 'status' => $status ) ); } } /** * Failed item for a review queue decision the queue did not carry out. * * @param int $product_id Product ID. * @param array $outcome ReviewQueueDecision outcome. * @return array */ private static function reviewFailureItem( int $product_id, array $outcome ): array { $item = array( 'product_id' => $product_id, 'message' => (string) ( $outcome['message'] ?? '' ), ); foreach ( array( 'code', 'reason' ) as $key ) { if ( isset( $outcome[ $key ] ) ) { $item[ $key ] = $outcome[ $key ]; } } return $item; } public function bulk_reject( $request ) { try { $rate_check = $this->checkRateLimit( (int) get_current_user_id(), static::RATE_LIMIT_SCOPE . '_reject' ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $params = $request->get_json_params(); $results = $params['results'] ?? array(); if ( empty( $results ) ) { return new \WP_Error( 'invalid_request', __( 'No titles to reject', 'ai-product-tools' ), array( 'status' => 400 ) ); } $success_count = 0; $failed_ids = array(); $failed_items = array(); foreach ( $results as $result ) { $product_id = is_array( $result ) ? absint( $result['product_id'] ?? 0 ) : 0; if ( $product_id <= 0 ) { continue; } if ( empty( $result['review'] ) ) { $success_count++; continue; } $outcome = current_user_can( 'edit_post', $product_id ) ? ( new ReviewQueueDecision() )->reject( $product_id, 'title', array( 'title' ) ) : array( 'success' => false, 'message' => __( 'You do not have permission to edit this product.', 'ai-product-tools' ), ); if ( $outcome['success'] ) { $success_count++; } else { $failed_ids[] = $product_id; $failed_items[] = self::reviewFailureItem( $product_id, $outcome ); } } if ( $success_count > 0 ) { \AIPT\Core\Services\UsageTracker::record_event( 'title', 'rejected', $success_count, array( 'product_id' => is_array( $results ) && ! empty( $results ) && isset( $results[0]['product_id'] ) ? (int) $results[0]['product_id'] : 0, ) ); } return new WP_REST_Response( array( 'success' => true, 'message' => sprintf( /* translators: %d: Number of titles that were rejected */ _n( '%d title rejected successfully.', '%d titles rejected successfully.', $success_count, 'ai-product-tools' ), $success_count ), 'rejected_count' => $success_count, 'data' => array( 'failed_ids' => $failed_ids, 'failed_items' => $failed_items, ), ), 200 ); } catch ( \Exception $e ) { $message = ErrorHandler::sanitize_error_for_display( $e->getMessage() ); $status = ErrorHandler::extract_http_status_from_message( $message, 500 ); return new \WP_Error( 'server_error', $message, array( 'status' => $status ) ); } } }