service = new FAQGeneratorService(); } public function register_routes(): void { $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, ), 'options' => array( 'type' => 'object', 'required' => false, ), ), ); register_rest_route( 'aipt/v1', '/faq-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', '/faq-generator/editor-bulk-generate', $editor_bulk_generate_endpoint ); register_rest_route( 'aipt/v1', '/faq-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', '/faq-generator/bulk-reject', array( 'methods' => 'POST', 'callback' => array( $this, 'bulk_reject' ), 'permission_callback' => array( $this, 'check_permissions_write' ), 'args' => array( 'productIds' => array( 'type' => 'array', 'required' => true, 'items' => array( 'type' => 'integer' ), 'maxItems' => self::MAX_BULK_REJECT_ITEMS, ), 'reviewProductIds' => array( 'type' => 'array', 'required' => false, 'items' => array( 'type' => 'integer' ), 'maxItems' => self::MAX_BULK_REJECT_ITEMS, ), ), ) ); register_rest_route( 'aipt/v1', '/faq-generator/product-faq', array( 'methods' => 'GET', 'callback' => array( $this, 'get_product_faqs' ), 'permission_callback' => array( $this, 'check_permissions' ), 'args' => array( 'product_ids' => array( 'type' => 'array', 'required' => true, 'items' => array( 'type' => 'integer' ), ), ), ) ); } /** * Apply free-plan defaults to FAQ options. * * Overrides premium-only fields with free defaults, then exposes * the result via a filter so the Premium module can restore the * original values when a valid licence is present. * * @since 2.6.0 * * @param array $options Raw request options. * @return array Options with free defaults applied (or premium values restored via filter). */ private function applyFreeDefaults( array $options ): array { $free_defaults = array( 'faqMode' => 'both', 'writeMode' => 'append', 'faqSources' => array( 'product_description' ), ); $controlled = array_merge( $options, $free_defaults ); /** * Filter FAQ generator validated options. * * Premium module can hook here to restore premium option values * when a valid license is present. * * @since 2.6.0 * * @param array $controlled Options with free defaults applied. * @param array $options Original request options. */ return apply_filters( 'aipt_faq_validate_options', $controlled, $options ); } /** * Identify controlled parameters present in sanitized request options. * * @since 2.6.0 * * @param array $options Sanitized request options. * @return string[] Controlled parameter names. */ private function getControlledParameters( array $options ): array { return array_values( array_filter( array( 'faqMode', 'writeMode', 'faqSources' ), static function ( string $param ) use ( $options ): bool { return array_key_exists( $param, $options ); } ) ); } /** * Resolve the write mode for a direct (non-review-queue) apply. * * Replace stays Business on every FAQ apply path through the same * named `aipt_faq_replace_enabled` filter the review-queue applier, * the Automation draft applier and the job-save guard already use * (`faqReplaceMode`), not the broader `aipt_faq_validate_options` * free-default restore every other FAQ option goes through: that * filter checks a generic premium-plan signal, not this specific, * named tier, so the two could disagree if the plugin ever sells a * second paid tier. A non-entitled request falls back to append. * * @param string $write_mode Requested write mode ('append'|'replace'). * @return string */ private function resolveWriteMode( string $write_mode ): string { $write_mode = in_array( $write_mode, array( 'append', 'replace' ), true ) ? $write_mode : 'append'; if ( 'replace' === $write_mode && ! apply_filters( 'aipt_faq_replace_enabled', false ) ) { return 'append'; } return $write_mode; } /** * Sanitize FAQ generator options from REST requests. * * @param array $options Raw request options. * @return array Sanitized options. */ private function sanitizeOptions( array $options ): array { $sanitized = array(); foreach ( array( 'faqFormat', 'faqMode', 'writeMode', 'language', 'provider', 'model', 'generationMode', 'overwrite' ) as $key ) { if ( isset( $options[ $key ] ) ) { $sanitized[ $key ] = sanitize_text_field( (string) $options[ $key ] ); } } if ( isset( $options['faqCount'] ) ) { $sanitized['faqCount'] = FAQGeneratorService::normalize_faq_count( $options['faqCount'] ); } if ( isset( $options['faqSources'] ) && is_array( $options['faqSources'] ) ) { $sanitized['faqSources'] = array_values( array_unique( array_filter( array_map( static function ( $source ): string { return sanitize_text_field( (string) $source ); }, $options['faqSources'] ) ) ) ); } if ( isset( $options['excludeQuestions'] ) && is_array( $options['excludeQuestions'] ) ) { $sanitized['excludeQuestions'] = array_values( array_slice( array_unique( array_filter( array_map( static function ( $question ): string { return is_string( $question ) ? sanitize_text_field( $question ) : ''; }, $options['excludeQuestions'] ) ) ), 0, 50 ) ); } return $sanitized; } public function bulk_generate( WP_REST_Request $request ) { $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { return $ai_gate; } $rate_check = $this->checkRateLimit( (int) get_current_user_id(), static::RATE_LIMIT_SCOPE ); if ( ! $rate_check['allowed'] ) { return $this->rateLimitResponse( $rate_check ); } $product_ids = array_values( array_filter( array_map( 'absint', (array) $request->get_param( 'productIds' ) ) ) ); $options = $request->get_param( 'options' ); if ( ! is_array( $product_ids ) || empty( $product_ids ) ) { return new WP_Error( 'aipt_faq_invalid_products', __( 'Please select at least one product to generate FAQs.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $options = is_array( $options ) ? $this->sanitizeOptions( $options ) : array(); $options = $this->enforce_generation_mode( $options ); $controlled_parameters = $this->getControlledParameters( $options ); $requested_options = $options; $options = $this->applyFreeDefaults( $options ); $applied_defaults = array(); foreach ( $controlled_parameters as $param ) { $requested_value = $requested_options[ $param ] ?? null; if ( array() === $requested_value || ( is_string( $requested_value ) && '' === trim( $requested_value ) ) ) { continue; } if ( $requested_value !== ( $options[ $param ] ?? null ) ) { $applied_defaults[] = $param; } } if ( self::site_additional_prompt_skipped( Generators::FAQ, 'aipt_faq_additional_prompt', 'aipt_faq_additional_prompt_enabled' ) ) { $applied_defaults[] = 'siteAdditionalPrompt'; } $authorized_ids = array(); $denied_results = array(); foreach ( $product_ids as $product_id ) { $product = wc_get_product( $product_id ); $refusal = ProductEligibility::refusalMessage( $product ); if ( null !== $refusal ) { $denied_results[] = array( 'product_id' => $product_id, 'error' => $refusal, ); continue; } if ( current_user_can( 'edit_post', $product_id ) ) { $authorized_ids[] = $product_id; continue; } $denied_results[] = array( 'product_id' => $product_id, 'error' => __( 'You do not have permission to edit this product.', 'ai-product-tools' ), ); } try { $results = empty( $authorized_ids ) ? array() : $this->service->bulk_generate( $authorized_ids, $options ); if ( 'server_review' === ( $options['generationMode'] ?? '' ) ) { $reviewStore = new ContentReviewStore(); foreach ( $results as &$item ) { if ( ! is_array( $item ) ) { continue; } $product_id = $item['product_id'] ?? 0; if ( $product_id <= 0 ) { continue; } if ( 'needs_review' === ( $item['status'] ?? '' ) || ! empty( $item['error'] ) ) { continue; } if ( ! $this->can_stage_review_for_product( (int) $product_id ) ) { $item['review_stage_failed'] = true; $item['review_stage_error'] = __( 'This product could not be queued for review.', 'ai-product-tools' ); continue; } $faqs = $item['faqs'] ?? array(); if ( empty( $faqs ) || ! is_array( $faqs ) ) { continue; } $write_mode = $options['writeMode'] ?? 'append'; $encoded = wp_json_encode( $faqs ); if ( false === $encoded ) { continue; } $item_blueprint = isset( $item['blueprint'] ) && is_array( $item['blueprint'] ) ? $item['blueprint'] : array(); $reviewId = $reviewStore->stage( (int) $product_id, 'faq', 'faq', 0, $encoded, array( 'apply_context' => array( 'writeMode' => $write_mode, '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 product is still in progress. Try again shortly.', 'ai-product-tools' ); } } unset( $item ); } \AIPT\Core\Services\UsageTracker::record_event( 'faq', 'generated', is_array( $results ) ? count( $results ) : count( $product_ids ), array( 'product_id' => is_array( $product_ids ) && ! empty( $product_ids ) ? (int) $product_ids[ array_key_first( $product_ids ) ] : 0, ) ); if ( ! empty( $denied_results ) ) { $results = array_merge( is_array( $results ) ? $results : array(), $denied_results ); } $outcome = BatchOutcome::of( (array) $results, __( 'FAQ generation failed.', 'ai-product-tools' ) ); $response_data = array( 'success' => $outcome['success'], 'message' => $outcome['success'] ? __( 'FAQ generation completed.', 'ai-product-tools' ) : $outcome['message'], 'results' => $results, 'applied_free_defaults' => $applied_defaults, ); if ( ! empty( $applied_defaults ) ) { $response_data['applied_free_defaults_reason'] = PlanDenial::reason( array( 'siteAdditionalPrompt' ) === $applied_defaults ? 'additionalFaqPrompts' : 'advancedFaqOptions', 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 $exception ) { return new WP_Error( 'aipt_faq_generation_failed', $exception->getMessage(), array( 'status' => 500 ) ); } } public function bulk_apply( WP_REST_Request $request ) { $payloads = $request->get_param( 'results' ); if ( ! is_array( $payloads ) || empty( $payloads ) ) { return new WP_Error( 'aipt_faq_invalid_results', __( 'No FAQ results were provided for applying content.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $apply_options = $request->get_param( 'options' ); $apply_options = is_array( $apply_options ) ? $this->sanitizeOptions( $apply_options ) : array(); $requested_apply_write_mode = isset( $apply_options['writeMode'] ) ? strtolower( (string) $apply_options['writeMode'] ) : 'append'; $default_overwrite = isset( $apply_options['overwrite'] ) && 'empty_only' === $apply_options['overwrite'] ? 'empty_only' : 'replace'; $apply_options = $this->applyFreeDefaults( $apply_options ); $applied = 0; $failed = 0; $responses = array(); $applied_defaults = array(); $write_mode_reason = null; foreach ( $payloads as $result ) { if ( ! is_array( $result ) ) { continue; } $product_id = isset( $result['product_id'] ) ? absint( $result['product_id'] ) : 0; if ( $product_id <= 0 ) { $failed++; $responses[] = array( 'product_id' => 0, 'status' => 'error', 'message' => __( 'Invalid product identifier.', 'ai-product-tools' ), ); continue; } if ( ! current_user_can( 'edit_post', $product_id ) ) { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => __( 'You do not have permission to edit this product.', 'ai-product-tools' ), ); continue; } $product = wc_get_product( $product_id ); if ( ! ProductEligibility::isEligible( $product ) ) { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => ProductEligibility::refusalMessage( $product ), ); continue; } if ( 'needs_review' === ( $result['status'] ?? '' ) || ! empty( $result['error'] ) ) { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => ! empty( $result['error'] ) ? __( 'This FAQ failed to generate and cannot be applied.', 'ai-product-tools' ) : __( 'This FAQ still needs review before it can be applied.', 'ai-product-tools' ), ); continue; } $release = null; try { $write_mode = isset( $result['writeMode'] ) && is_string( $result['writeMode'] ) ? strtolower( $result['writeMode'] ) : $requested_apply_write_mode; if ( ! empty( $result['review'] ) ) { $review_overwrite = isset( $result['overwrite'] ) && 'empty_only' === $result['overwrite'] ? 'empty_only' : $default_overwrite; $result_blueprint = BlueprintAttributionSanitizer::sanitize( $result['blueprint'] ?? null ); $outcome = $this->approveQueuedReview( $product_id, $result['faqs'] ?? null, $write_mode, $review_overwrite, $result_blueprint ); if ( $outcome['success'] ) { $applied++; $responses[] = array( 'product_id' => $product_id, 'status' => 'success', 'message' => __( 'FAQ content applied successfully.', 'ai-product-tools' ), ); $write_mode_reason = $write_mode_reason ?? ( $outcome['applied_free_defaults']['writeMode'] ?? null ); if ( isset( $outcome['applied_free_defaults']['writeMode'] ) ) { $applied_defaults[] = 'writeMode'; } } else { $failed++; $failure = array( 'product_id' => $product_id, 'status' => 'error', 'message' => (string) ( $outcome['message'] ?? '' ), ); if ( isset( $outcome['reason'] ) ) { $failure['reason'] = $outcome['reason']; } $responses[] = $failure; } continue; } $requested_write_mode = $write_mode; $write_mode = $this->resolveWriteMode( $write_mode ); if ( $requested_write_mode !== $write_mode ) { if ( 'replace' === $requested_write_mode ) { $write_mode_reason = $write_mode_reason ?? PlanDenial::reason( 'faqReplaceMode', PlanDenial::PLAN_PAID ); if ( PlanDenial::isVerificationUnavailable( $write_mode_reason ) ) { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'reason' => $write_mode_reason, 'message' => PlanDenial::message( $write_mode_reason, '' ), ); continue; } } $applied_defaults[] = 'writeMode'; } if ( empty( $result['faqs'] ) || ! is_array( $result['faqs'] ) ) { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => __( 'No FAQ items provided.', 'ai-product-tools' ), ); continue; } $legacy_mode_parts = \AIPT\Api\ContentStructure\Integration\BlueprintIntegration::PATH_ADVANCED === ( $result['executionPath'] ?? null ) ? $this->service->modeParts( is_string( $result['mode'] ?? null ) ? $result['mode'] : '' ) : null; $structured_faqs = $this->structuredFaqs( $result['faqs'], $legacy_mode_parts ); if ( empty( $structured_faqs ) ) { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => __( 'FAQ items could not be validated.', 'ai-product-tools' ), ); continue; } $release = \AIPT\Api\Helpers\ProductWriteLock::acquire( $product_id ); if ( ! is_callable( $release ) ) { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => __( 'This product is being saved elsewhere or its save lock is unavailable. Please retry.', 'ai-product-tools' ), ); continue; } wp_cache_delete( $product_id, 'post_meta' ); $overwrite = isset( $result['overwrite'] ) && 'empty_only' === $result['overwrite'] ? 'empty_only' : $default_overwrite; $existing_json = get_post_meta( $product_id, '_aipt_faq_data', true ); $existing_faqs = ( is_string( $existing_json ) && '' !== $existing_json ) ? json_decode( $existing_json, true ) : array(); $existing_faqs = is_array( $existing_faqs ) ? $existing_faqs : array(); if ( 'empty_only' === $overwrite && ! empty( $existing_faqs ) ) { $responses[] = array( 'product_id' => $product_id, 'status' => 'skipped', 'message' => __( 'This product already has FAQ content; nothing was written.', 'ai-product-tools' ), ); continue; } if ( 'append' === $write_mode ) { $structured_faqs = FaqList::append( $existing_faqs, $structured_faqs ); } $json_to_save = wp_json_encode( $structured_faqs ); if ( false === $json_to_save ) { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => __( 'Failed to encode FAQ data.', 'ai-product-tools' ), ); continue; } $result_blueprint = BlueprintAttributionSanitizer::sanitizeOrEmpty( $result['blueprint'] ?? null ); \AIPT\Api\Rollback\ContentApplyDispatcher::before( $product_id, array( 'faq' => $structured_faqs, 'blueprint_id' => $result_blueprint['id'], 'blueprint_name' => $result_blueprint['name'], 'blueprint_revision' => $result_blueprint['revision'], 'blueprint_builtin' => $result_blueprint['builtin'], ), 'faq' ); $meta_result = update_post_meta( $product_id, '_aipt_faq_data', wp_slash( $json_to_save ) ); $write_succeeded = false !== $meta_result || ContentMarkService::wroteLiveValue( $product_id, '_aipt_faq_data', $json_to_save ); \AIPT\Api\Rollback\ContentApplyDispatcher::after( $product_id, $write_succeeded ); if ( $write_succeeded ) { \AIPT\Api\ProductEditor\ProductEditorConcurrencyToken::bump_revision( $product_id ); ContentMarkService::mark( $product_id, 'faq', array( 'gen' => MetaKeys::GEN_BULK_ADVANCED ) ); $applied++; $responses[] = array( 'product_id' => $product_id, 'status' => 'success', 'message' => __( 'FAQ content applied successfully.', 'ai-product-tools' ), ); } else { $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => __( 'FAQ content could not be saved.', 'ai-product-tools' ), ); } } catch ( \Throwable $exception ) { \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStaged( $product_id, false ); $failed++; $responses[] = array( 'product_id' => $product_id, 'status' => 'error', 'message' => $exception->getMessage(), ); } finally { if ( is_callable( $release ) ) { $release(); } } } if ( $applied > 0 ) { $first_applied_pid = 0; foreach ( $responses as $resp ) { if ( isset( $resp['status'], $resp['product_id'] ) && 'success' === $resp['status'] ) { $first_applied_pid = (int) $resp['product_id']; break; } } \AIPT\Core\Services\UsageTracker::record_event( 'faq', 'applied', $applied, array( 'product_id' => $first_applied_pid ) ); } $response_data = array( 'success' => 0 === $failed, 'applied_count' => $applied, 'failed_count' => $failed, 'results' => $responses, 'applied_free_defaults' => array_values( array_unique( $applied_defaults ) ), ); if ( ! empty( $applied_defaults ) ) { $response_data['applied_free_defaults_reason'] = $write_mode_reason ?? PlanDenial::reason( 'faqReplaceMode', PlanDenial::PLAN_PAID ); } return new WP_REST_Response( $response_data, 200 ); } /** * FAQ items with at least one non-blank half, sanitized for storage. A * pair with neither half filled is always dropped; $mode_parts can drop * a surviving pair further still, when it is missing the one specific * half that mode requires. * * @param mixed $faqs Submitted FAQ items. * @param array{question:bool,answer:bool}|null $mode_parts When given, a pair missing the half this mode requires is dropped too (defense-in-depth re-check for a caller that knows the originating mode; null applies only the fully-blank-pair check above, e.g. for an already-validated Blueprint result or a saved-data read-back). * @return array */ private function structuredFaqs( $faqs, ?array $mode_parts = null ): array { $structured_faqs = array(); foreach ( (array) $faqs as $faq ) { if ( ! is_array( $faq ) || ! isset( $faq['question'], $faq['answer'] ) ) { continue; } $question = sanitize_text_field( (string) $faq['question'] ); $answer = wp_kses_post( (string) $faq['answer'] ); $question_is_blank = '' === trim( wp_strip_all_tags( $question ) ); $answer_is_blank = '' === trim( wp_strip_all_tags( $answer ) ); if ( $question_is_blank && $answer_is_blank ) { continue; } if ( null !== $mode_parts && ( ( $mode_parts['question'] && $question_is_blank ) || ( $mode_parts['answer'] && $answer_is_blank ) ) ) { continue; } $structured_faqs[] = array( 'question' => $question, 'answer' => $answer, ); } return $structured_faqs; } /** * Approve an FAQ queued for review with the submitted questions. * * @param int $product_id Product ID. * @param mixed $faqs Submitted FAQ items. * @param string $write_mode Requested write mode. * @param string $overwrite 'replace' or 'empty_only' (approve() restages the row with these options). * @param array|null $blueprint Sanitized denormalized blueprint attribution * `{id,name,revision,builtin}` for this item, or null * when the request carried no (or a malformed) blueprint * — the row's existing attribution is then left untouched. * @return array ReviewQueueDecision outcome. */ private function approveQueuedReview( int $product_id, $faqs, string $write_mode, string $overwrite = 'replace', ?array $blueprint = null ): array { $structured_faqs = is_array( $faqs ) ? $this->structuredFaqs( $faqs ) : array(); $encoded = empty( $structured_faqs ) ? false : wp_json_encode( $structured_faqs ); if ( false === $encoded ) { return array( 'success' => false, 'message' => __( 'FAQ items could not be validated.', 'ai-product-tools' ), ); } $opts = array( 'apply_context' => array( 'writeMode' => 'replace' === $write_mode ? 'replace' : 'append', 'overwrite' => 'empty_only' === $overwrite ? 'empty_only' : 'replace', ), ); if ( null !== $blueprint ) { $opts['blueprint_id'] = $blueprint['id']; $opts['blueprint_name'] = $blueprint['name']; $opts['blueprint_revision'] = $blueprint['revision']; $opts['blueprint_builtin'] = $blueprint['builtin']; } return ( new ReviewQueueDecision() )->approve( $product_id, 'faq', array( 'faq' => array( 'value' => $encoded, 'opts' => $opts, ), ), array( 'faq' ), array( 'faq' ) ); } public function bulk_reject( WP_REST_Request $request ) { $product_ids = array_values( array_filter( array_map( 'absint', (array) $request->get_param( 'productIds' ) ) ) ); if ( empty( $product_ids ) ) { return new WP_Error( 'aipt_faq_invalid_reject_payload', __( 'A valid product list is required to reject FAQ results.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $review_ids = array_intersect( array_map( 'absint', (array) $request->get_param( 'reviewProductIds' ) ), $product_ids ); $failures = array(); foreach ( $review_ids as $product_id ) { $outcome = current_user_can( 'edit_post', $product_id ) ? ( new ReviewQueueDecision() )->reject( $product_id, 'faq', array( 'faq' ) ) : array( 'success' => false, 'message' => __( 'You do not have permission to edit this product.', 'ai-product-tools' ), ); if ( ! $outcome['success'] ) { $failure = array( 'product_id' => $product_id, 'message' => (string) ( $outcome['message'] ?? '' ), ); if ( isset( $outcome['reason'] ) ) { $failure['reason'] = $outcome['reason']; } $failures[] = $failure; } } $total = count( $product_ids ) - count( $failures ); if ( $total > 0 ) { \AIPT\Core\Services\UsageTracker::record_event( 'faq', 'rejected', $total, array( 'product_id' => is_array( $product_ids ) && ! empty( $product_ids ) ? (int) $product_ids[ array_key_first( $product_ids ) ] : 0, ) ); } return new WP_REST_Response( array( 'success' => true, 'rejectedCount' => $total, 'failures' => $failures, 'message' => sprintf( /* translators: %d: rejected product count */ __( 'Rejected FAQ results for %d products.', 'ai-product-tools' ), $total ), ), 200 ); } /** * Read a batch of products' already-saved FAQ (`_aipt_faq_data`). * * Lets the FAQ Generator hydrate the open inspector, every expanded row, * AND the master list's own row preview from one request per page of * products, instead of one REST round trip per visible row (a request * storm on shared hosting once a page holds dozens or hundreds of rows). * * @param WP_REST_Request $request Incoming REST request. * @return WP_REST_Response|WP_Error */ public function get_product_faqs( WP_REST_Request $request ) { try { $ids = $this->normalize_product_ids( $request->get_param( 'product_ids' ) ); if ( count( $ids ) > self::MAX_PRODUCT_FAQ_IDS ) { return $this->error_response( 'too_many_product_ids', sprintf( /* translators: %d: maximum number of product IDs accepted in one request. */ __( 'No more than %d product IDs may be requested at once.', 'ai-product-tools' ), self::MAX_PRODUCT_FAQ_IDS ), 400 ); } if ( ! empty( $ids ) && function_exists( '_prime_post_caches' ) ) { _prime_post_caches( $ids, false, true ); } $faqs = array(); foreach ( $ids as $product_id ) { $product = wc_get_product( $product_id ); if ( ! ProductEligibility::isEligible( $product ) ) { continue; } if ( ! current_user_can( 'edit_post', $product_id ) ) { continue; } $existing_json = get_post_meta( $product_id, '_aipt_faq_data', true ); $existing_faqs = ( is_string( $existing_json ) && '' !== $existing_json ) ? json_decode( $existing_json, true ) : array(); $faqs[ (string) $product_id ] = $this->structuredFaqs( is_array( $existing_faqs ) ? $existing_faqs : array() ); } return $this->success_response( array( 'faqs' => $faqs, ) ); } catch ( \Exception $e ) { return $this->error_response( 'fetch_product_faq_error', ErrorHandler::sanitize_error_for_display( $e->getMessage() ), 500 ); } } /** * Normalize the `product_ids` request param into a deduplicated list of * positive ints. * * This controller registers no `sanitize_callback`/`validate_callback` * for its id-list args (matching `productIds` on the bulk-generate route * above), so `$request->get_param()` returns whatever shape the caller * sent: a real array, or a comma-separated string * (`?product_ids=1,2,3`) — the same string shape WordPress's own * array-type REST arg schema accepts via `wp_parse_list()`. Handling * both here keeps that acceptance regardless of how the request reached * this method. * * @param mixed $raw Raw `product_ids` param — an array, a comma-separated string, or absent. * @return array Deduplicated, positive product IDs. */ private function normalize_product_ids( $raw ): array { if ( is_string( $raw ) ) { $raw = explode( ',', $raw ); } if ( ! is_array( $raw ) ) { return array(); } return array_values( array_unique( array_filter( array_map( 'absint', $raw ) ) ) ); } /** * 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; } /** * Register _aipt_faq_data post meta for REST exposure. * * Called from Init::register_hooks() so the meta is available in the REST API. */ public static function register_meta(): void { \register_post_meta( 'product', '_aipt_faq_data', array( 'type' => 'string', 'description' => 'Structured FAQ data for accordion rendering', 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => array( __CLASS__, 'sanitize_faq_json' ), 'auth_callback' => function () { return current_user_can( 'manage_woocommerce' ); }, ) ); } /** * Sanitize FAQ JSON meta value. * * Validates JSON structure (array of question/answer pairs). * Returns the original JSON string only if valid, empty string otherwise. * * @param string $value Raw meta value. * @return string Sanitized JSON string or empty string. */ public static function sanitize_faq_json( $value ): string { if ( ! is_string( $value ) || '' === $value ) { return ''; } $decoded = json_decode( $value, true ); if ( ! is_array( $decoded ) ) { return ''; } $sanitized = array(); foreach ( $decoded as $faq ) { if ( ! is_array( $faq ) || ! isset( $faq['question'], $faq['answer'] ) ) { continue; } $sanitized[] = array( 'question' => sanitize_text_field( (string) $faq['question'] ), 'answer' => wp_kses_post( (string) $faq['answer'] ), ); } if ( empty( $sanitized ) ) { return ''; } $json = wp_json_encode( $sanitized ); return is_string( $json ) ? $json : ''; } }