'GET', 'callback' => array( __CLASS__, 'list_items' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::listArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-review/summary', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_summary' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-review/(?P\d+)/current-value', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_current_value' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint', ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-review/approve', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'approve' ), 'permission_callback' => array( __CLASS__, 'check_permissions_write' ), 'args' => array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint', ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-review/edit', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'edit' ), 'permission_callback' => array( __CLASS__, 'check_permissions_write' ), 'args' => array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint', ), 'value' => array( 'required' => true, 'type' => 'string', 'maxLength' => self::MAX_EDIT_VALUE_LENGTH, ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-review/reject', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'reject' ), 'permission_callback' => array( __CLASS__, 'check_permissions_write' ), 'args' => array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint', ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-review/bulk-approve', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'bulk_approve' ), 'permission_callback' => array( __CLASS__, 'check_permissions_write' ), 'args' => array( 'ids' => array( 'required' => true, 'type' => 'array', 'items' => array( 'type' => 'integer' ), 'maxItems' => self::MAX_BULK_IDS, ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-review/bulk-reject', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'bulk_reject' ), 'permission_callback' => array( __CLASS__, 'check_permissions_write' ), 'args' => array( 'ids' => array( 'required' => true, 'type' => 'array', 'items' => array( 'type' => 'integer' ), 'maxItems' => self::MAX_BULK_IDS, ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-review/bulk-delete', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'bulk_delete' ), 'permission_callback' => array( __CLASS__, 'check_permissions_write' ), 'args' => array( 'ids' => array( 'required' => true, 'type' => 'array', 'items' => array( 'type' => 'integer' ), 'maxItems' => self::MAX_BULK_IDS, ), ), ), ) ); } /** * Read permission: edit_products OR manage_woocommerce. * * Read is universal — no plan gate (matches the Content History * precedent) and, being a GET-only route family, no nonce either: a GET * request is never the cross-site write a nonce protects against, and * WP core's own cookie-auth gate already covers a cookie-authenticated * reader (@see \AIPT\Utils\RestNonceGuard). * * @param WP_REST_Request $request Request object. * @return true|WP_Error */ public static function check_permissions_read( $request ) { if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'edit_products' ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to view content review items.', 'ai-product-tools' ), array( 'status' => 403 ) ); } return true; } /** * Write permission: manage_woocommerce + nonce. * * The Business gate and per-product edit_post are checked in the handler * (mirrors SnapshotRestController pattern). The nonce is required only * from a cookie-authenticated request — an Application-Password/Basic-Auth * (or other non-cookie) client is already authenticated and has no way * to ever obtain one (@see \AIPT\Utils\RestNonceGuard). * * @param WP_REST_Request $request Request object. * @return true|WP_Error */ public static function check_permissions_write( $request ) { if ( ! current_user_can( 'manage_woocommerce' ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to perform this action.', 'ai-product-tools' ), array( 'status' => 403 ) ); } return \AIPT\Utils\RestNonceGuard::check( $request, __( 'Invalid or missing security nonce.', 'ai-product-tools' ) ); } /** * Check the Business entitlement via the filter bridge. * * Always-shipped code never calls PremiumFeatureManager or GrandfatherResolver * directly — the filter handler registered in todo 7 makes the real decision. * * @return bool True if content review actions are enabled. */ private static function isReviewEnabled(): bool { return (bool) apply_filters( 'aipt_content_review_enabled', false ); } /** * Return the reason-aware premium_required WP_Error for the Business * 'contentReview' gate. * * @return WP_Error */ private static function premiumRequiredError(): WP_Error { return PlanDenial::error( 'contentReview', PlanDenial::PLAN_BUSINESS, __( 'Content review actions require a Business plan.', 'ai-product-tools' ) ); } /** * List review rows with keyset pagination and filters. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function list_items( $request ) { $filters = self::listFilters( $request ); $cursor = self::sanitizeCursor( $request->get_param( 'cursor' ) ); $limit = max( 1, min( 100, absint( $request->get_param( 'limit' ) ?: 25 ) ) ); if ( isset( $filters['product_id'] ) && $filters['product_id'] > 0 ) { if ( ! current_user_can( 'edit_post', (int) $filters['product_id'] ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to view this product\'s review items.', 'ai-product-tools' ), array( 'status' => 403 ) ); } } $store = static::store(); $result = $store->list( $filters, $cursor, $limit ); $rows = self::addProductIdentity( $result['rows'] ); $rows = self::addConcurrencyTokens( $rows ); return new WP_REST_Response( array( 'success' => true, 'data' => array( 'items' => array_values( $rows ), 'next_cursor' => $result['next_cursor'], 'has_more' => $result['has_more'], 'total' => $store->count( $filters ), ), ), 200 ); } /** * Enrich rows with the product identity (name, SKU, thumbnail) their row * needs to render more than "Product #123" — one batch resolve over the * distinct product ids in this page, not one lookup per row. * * @param array> $rows Review rows, each carrying `product_id`. * @return array> */ private static function addProductIdentity( array $rows ): array { $product_ids = array(); foreach ( $rows as $row ) { if ( isset( $row['product_id'] ) ) { $product_ids[] = (int) $row['product_id']; } } $identities = ( new ProductIdentityResolver() )->resolve( $product_ids ); foreach ( $rows as &$row ) { $product_id = isset( $row['product_id'] ) ? (int) $row['product_id'] : 0; $identity = $identities[ $product_id ] ?? array( 'name' => '', 'sku' => '', 'thumbnail_url' => null, ); $row['product_name'] = $identity['name']; $row['product_sku'] = $identity['sku']; $row['thumbnail_url'] = $identity['thumbnail_url']; } unset( $row ); return $rows; } /** * Enrich rows with the live optimistic-concurrency token their subject * (the product, or the attachment for an `image_alt` row) currently * carries — see R-review-conflict. The list's own row already carries * everything {@see SnapshotSubject::fromRow()} needs to tell the two * apart. Batches one `wc_get_product()` per distinct product id on the * page, mirroring {@see addProductIdentity()}'s batching. * * Also drops the row's `staged_token` (CR-26): the stage-time token is * an internal input to {@see reviewConflictGuard()}, not something the * REST response needs to expose — the client already gets the LIVE token * via `current_token` below. * * @param array> $rows Review rows, each carrying `product_id`/`field_type`/`subject_id`. * @return array> */ private static function addConcurrencyTokens( array $rows ): array { $product_ids = array(); foreach ( $rows as $row ) { if ( ! SnapshotSubject::fromRow( $row )->isAttachment() ) { $product_ids[ (int) ( $row['product_id'] ?? 0 ) ] = true; } } $products = array(); foreach ( array_keys( $product_ids ) as $product_id ) { $products[ $product_id ] = function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : false; } foreach ( $rows as &$row ) { unset( $row['staged_token'] ); $subject = SnapshotSubject::fromRow( $row ); if ( $subject->isAttachment() ) { $row['current_token'] = self::attachmentToken( $subject->postId() ); continue; } $product = $products[ (int) ( $row['product_id'] ?? 0 ) ] ?? false; $row['current_token'] = $product ? ProductEditorConcurrencyToken::for_product( $product ) : ''; } unset( $row ); return $rows; } /** * An attachment-domain optimistic-concurrency token (image_alt rows). * Mirrors SnapshotRestController::attachmentToken() so the two conflict * guards never diverge in token format. * * @param int $attachment_id Attachment id. * @return string */ private static function attachmentToken( int $attachment_id ): string { return ProductEditorConcurrencyToken::for_post_id( $attachment_id ); } /** * Fresh live optimistic-concurrency token for a single review row's * subject — used by the write-path conflict guard (which must read the * CURRENT value at approve time, not whatever was current when the page * that built {@see addConcurrencyTokens()}'s batch was fetched). * * @param array $row Review row (product_id, field_type, subject_id). * @return string */ private static function currentTokenForRow( array $row ): string { $subject = SnapshotSubject::fromRow( $row ); if ( $subject->isAttachment() ) { return self::attachmentToken( $subject->postId() ); } $product = function_exists( 'wc_get_product' ) ? wc_get_product( $subject->postId() ) : null; return $product ? ProductEditorConcurrencyToken::for_product( $product ) : ''; } /** * The token a product would carry after exactly one revision bump on top of * the given one (same post_modified, revision + 1). * * @param string $token Token as composed by ProductEditorConcurrencyToken::compose(). * @return string */ private static function tokenAfterOneRevisionBump( string $token ): string { $separator = strrpos( $token, '|' ); if ( false === $separator ) { return ProductEditorConcurrencyToken::compose( $token, 1 ); } return ProductEditorConcurrencyToken::compose( substr( $token, 0, $separator ), ( (int) substr( $token, $separator + 1 ) ) + 1 ); } /** * Live-product-value conflict guard for Approve (R-review-conflict) — * distinct from the `expected_version` check above, which only detects * "this PROPOSAL was replaced by a newer regenerate since you loaded * it". This detects "the LIVE FIELD this proposal is about to overwrite * was edited by someone/something else since the queue was loaded" — * exactly what {@see \AIPT\Premium\Rollback\SnapshotRestController::conflictGuard()} * already protects Restore with. * * CR-26 (CodeRabbit, round1): the guard used to run ONLY when the client * echoed `expected_token`, fail-open otherwise — a client that never * adopted the field (or a stale cached bundle) got no protection at all. * The row's subject now carries a `staged_token` — the target's live * token captured by {@see ContentReviewStore::stage()} at the moment the * proposal was queued — so the comparison runs UNCONDITIONALLY against * that stored value, whether or not the client sends anything. A row * staged before this column existed has no `staged_token` (empty * string): rather than block every such legacy row, it falls back to * the original opt-in-via-`expected_token`, fail-open-on-omission * behavior, exactly as before this fix. `force` remains the explicit * override for both paths. * * @param array $row Review row (product_id, field_type, subject_id, staged_token). * @param string $expected_token Client-echoed token — only consulted for a legacy row with no staged_token. * @param bool $force Explicit override — approve despite a mismatch. * @return WP_Error|null WP_Error (409) on a genuine mismatch, null when approve may proceed. */ private static function reviewConflictGuard( array $row, string $expected_token, bool $force ) { if ( $force ) { return null; } $staged_token = isset( $row['staged_token'] ) ? (string) $row['staged_token'] : ''; if ( '' === $staged_token ) { if ( '' === $expected_token ) { return null; } return self::conflictErrorUnlessTokenMatches( $row, $expected_token ); } return self::conflictErrorUnlessTokenMatches( $row, $staged_token ); } /** * Compare a row's subject's CURRENT live token against `$expected` and * build the 409 `review_target_changed` error on a mismatch. Shared by * both branches of {@see reviewConflictGuard()}. * * @param array $row Review row (product_id, field_type, subject_id). * @param string $expected Token the row's subject is expected to still carry. * @return WP_Error|null */ private static function conflictErrorUnlessTokenMatches( array $row, string $expected ) { $current_token = self::currentTokenForRow( $row ); if ( ! hash_equals( $current_token, $expected ) ) { return new WP_Error( 'review_target_changed', __( 'This product was edited after this item was queued for review. Reload to review the current state, or approve anyway.', 'ai-product-tools' ), array( 'status' => 409, 'current_token' => $current_token, ) ); } return null; } /** * Read the live field value a review row would replace (H3-review-bank). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_current_value( $request ) { $id = absint( $request->get_param( 'id' ) ); $row = static::store()->get( $id ); if ( null === $row ) { return new WP_Error( 'review_not_found', __( 'That review item could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } $product_id = (int) ( $row['product_id'] ?? 0 ); if ( $product_id <= 0 || ! current_user_can( 'edit_post', $product_id ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to view this product\'s review items.', 'ai-product-tools' ), array( 'status' => 403 ) ); } $current_value = null; try { $current_value = ( new SnapshotStore() )->readCurrentFieldValue( $product_id, (string) ( $row['field_type'] ?? '' ), ( (int) ( $row['subject_id'] ?? 0 ) ) ?: null, ( '' !== (string) ( $row['plugin_slug'] ?? '' ) ) ? (string) $row['plugin_slug'] : null ); } catch ( \RuntimeException $e ) { $current_value = null; } return new WP_REST_Response( array( 'success' => true, 'data' => array( 'current_value' => $current_value ), ), 200 ); } /** * Summary endpoint — counts by status + entitlement echo. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public static function get_summary( $request ) { $store = static::store(); $counts = array( 'pending' => $store->count( array( 'status' => 'pending' ) ), 'in_progress' => $store->count( array( 'status' => 'in_progress' ) ), 'applied' => $store->count( array( 'status' => 'applied' ) ), 'total' => $store->count( array() ), ); return new WP_REST_Response( array( 'success' => true, 'data' => array( 'counts' => $counts, 'can_review' => self::isReviewEnabled(), ), ), 200 ); } /** * Approve a single review row — apply first, then delete. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function approve( $request ) { if ( ! self::isReviewEnabled() ) { return self::premiumRequiredError(); } $id = absint( $request->get_param( 'id' ) ); if ( $id <= 0 ) { return new WP_Error( 'invalid_params', __( 'A valid id is required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $store = static::store(); $row = $store->get( $id ); if ( null === $row ) { return new WP_Error( 'review_not_found', __( 'That review item could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } $product_id = (int) ( $row['product_id'] ?? 0 ); if ( $product_id <= 0 ) { return new WP_Error( 'review_not_found', __( 'That review item could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } if ( ! current_user_can( 'edit_post', $product_id ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to edit this product.', 'ai-product-tools' ), array( 'status' => 403 ) ); } $force = rest_sanitize_boolean( $request->get_param( 'force' ) ); $expected_token = $request->get_param( 'expected_token' ); $expected_token = is_string( $expected_token ) ? $expected_token : ''; $conflict = self::reviewConflictGuard( $row, $expected_token, $force ); if ( $conflict instanceof WP_Error ) { return $conflict; } $applier = static::applierFor( (string) ( $row['tool'] ?? '' ) ); $expected_version = $request->get_param( 'expected_version' ); $expected_version = is_numeric( $expected_version ) ? (int) $expected_version : null; if ( ! $store->approve( $id, $applier, $expected_version ) ) { $refusal = $store->lastRefusal(); if ( null !== $refusal && '' !== $refusal['message'] ) { return new WP_Error( 'approve_refused', $refusal['message'], array( 'status' => 409, 'reason' => $refusal['reason'], ) ); } $current = $store->get( $id ); if ( null !== $expected_version && null !== $current && 'pending' === (string) ( $current['status'] ?? '' ) ) { return new WP_Error( 'review_item_changed', __( 'This item changed since it was loaded. Please refresh and review the latest version.', 'ai-product-tools' ), array( 'status' => 409 ) ); } return new WP_Error( 'approve_failed', __( 'Failed to approve the selected item.', 'ai-product-tools' ), array( 'status' => 500 ) ); } $data = array( 'id' => $id, 'product_id' => $product_id, ); $applied_free_defaults = $applier instanceof ReportsAppliedFreeDefaults ? $applier->appliedFreeDefaults() : array(); if ( ! empty( $applied_free_defaults ) ) { $data['applied_free_defaults'] = array_keys( $applied_free_defaults ); $data['applied_free_defaults_reason'] = (string) reset( $applied_free_defaults ); } return new WP_REST_Response( array( 'success' => true, 'message' => __( 'Item approved and applied successfully.', 'ai-product-tools' ), 'data' => $data, ), 200 ); } /** * Replace a pending review row's value in place (R-review-edit-loss). * * The only write route that changes a staged proposal's content before * approval — a reviewer who edits a staged result in a generator's edit * modal calls this first, then approves by id with the returned * `version` as `expected_version`. Only a row still 'pending' can be * edited: {@see ContentReviewStore::restagePending()} refuses a row * that is already approved, rejected or claimed by a concurrent * approve, and that refusal is reported as the same 409 conflict * approve() itself reports for a row that moved since it was loaded. * * Only the Description tool's rows may be edited through this route — * enforced below, not just assumed, since any other tool's * `generated_value` is a JSON-encoded structure (image_alt, faq) a * generic text sanitizer has no notion of. * * Accepts the same optional `expected_version` binding approve()/ * reject() do: a client that sends the version its edit was seeded * from gets the same 409 below (never a silent overwrite) if a * regenerate or another edit replaced this row's content first. * Omitting it preserves the pre-existing unversioned behavior. * * Also runs the same {@see reviewConflictGuard()} approve() runs, BEFORE * `restagePending()` can rebase the row's `staged_token` to the * subject's current live value — otherwise an edit saved after the live * field changed would silently adopt that new value as its own * baseline, and the approval that follows would never see the conflict. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function edit( $request ) { if ( ! self::isReviewEnabled() ) { return self::premiumRequiredError(); } $id = absint( $request->get_param( 'id' ) ); if ( $id <= 0 ) { return new WP_Error( 'invalid_params', __( 'A valid id is required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $value = $request->get_param( 'value' ); if ( ! is_string( $value ) ) { return new WP_Error( 'invalid_params', __( 'A valid value is required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $store = static::store(); $row = $store->get( $id ); if ( null === $row ) { return new WP_Error( 'review_not_found', __( 'That review item could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } $product_id = (int) ( $row['product_id'] ?? 0 ); if ( $product_id <= 0 ) { return new WP_Error( 'review_not_found', __( 'That review item could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } if ( ! current_user_can( 'edit_post', $product_id ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to edit this product.', 'ai-product-tools' ), array( 'status' => 403 ) ); } if ( 'description' !== (string) ( $row['tool'] ?? '' ) ) { return new WP_Error( 'invalid_params', __( 'This item cannot be edited through this route.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $sanitized = self::sanitizeEditValue( $value, (string) ( $row['tool'] ?? '' ), (string) ( $row['field_type'] ?? '' ) ); $opts = array( 'value_format' => (string) ( $row['value_format'] ?? 'text' ), 'plugin_slug' => (string) ( $row['plugin_slug'] ?? '' ), 'created_by' => (int) ( $row['created_by'] ?? 0 ), 'blueprint_id' => isset( $row['blueprint_id'] ) ? (int) $row['blueprint_id'] : 0, 'blueprint_name' => (string) ( $row['blueprint_name'] ?? '' ), 'blueprint_revision' => isset( $row['blueprint_revision'] ) ? (int) $row['blueprint_revision'] : 0, 'blueprint_builtin' => ! empty( $row['blueprint_builtin'] ), ); $existing_context = $row['apply_context'] ?? null; if ( is_string( $existing_context ) && '' !== $existing_context ) { $decoded_context = json_decode( $existing_context, true ); if ( is_array( $decoded_context ) ) { $opts['apply_context'] = $decoded_context; } } $force = rest_sanitize_boolean( $request->get_param( 'force' ) ); $expected_token = $request->get_param( 'expected_token' ); $expected_token = is_string( $expected_token ) ? $expected_token : ''; $conflict = self::reviewConflictGuard( $row, $expected_token, $force ); if ( $conflict instanceof WP_Error ) { return $conflict; } $expected_version = $request->get_param( 'expected_version' ); $expected_version = is_numeric( $expected_version ) ? (int) $expected_version : null; if ( ! $store->restagePending( $id, $sanitized, $opts, $expected_version ) ) { return new WP_Error( 'review_item_changed', __( 'This item changed since it was loaded. Please refresh and review the latest version.', 'ai-product-tools' ), array( 'status' => 409 ) ); } $updated = $store->get( $id ); return new WP_REST_Response( array( 'success' => true, 'data' => array( 'id' => $id, 'version' => (int) ( $updated['version'] ?? 0 ), ), ), 200 ); } /** * Sanitize an edited value exactly the way the staging path sanitizes * that tool's value for that field, so an edit can never store * something the original generation would not have stored. * * Only the Description tool's rows reach this method — edit() refuses * any other tool before calling it (title/seo_meta/faq already thread * an edited value into {@see ContentReviewStore::restagePending()} via * ReviewQueueDecision before their own approve calls, before this route * ever existed). The generic fallback below is defensive-in-depth only. * * @param string $value Raw submitted value. * @param string $tool The row's tool slug. * @param string $field_type The row's field_type slug. * @return string */ private static function sanitizeEditValue( string $value, string $tool, string $field_type ): string { if ( 'description' === $tool ) { return OutputValidator::sanitize( $value, $field_type ); } return sanitize_textarea_field( $value ); } /** * Reject a single review row — delete it. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function reject( $request ) { if ( ! self::isReviewEnabled() ) { return self::premiumRequiredError(); } $id = absint( $request->get_param( 'id' ) ); if ( $id <= 0 ) { return new WP_Error( 'invalid_params', __( 'A valid id is required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $store = static::store(); $row = $store->get( $id ); if ( null === $row ) { return new WP_Error( 'review_not_found', __( 'That review item could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } $product_id = (int) ( $row['product_id'] ?? 0 ); if ( $product_id > 0 && ! current_user_can( 'edit_post', $product_id ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to edit this product.', 'ai-product-tools' ), array( 'status' => 403 ) ); } $expected_version = $request->get_param( 'expected_version' ); $expected_version = is_numeric( $expected_version ) ? (int) $expected_version : null; if ( ! $store->reject( $id, $expected_version ) ) { $current = $store->get( $id ); if ( null !== $expected_version && null !== $current && 'pending' === (string) ( $current['status'] ?? '' ) && (int) ( $current['version'] ?? 0 ) !== $expected_version ) { return new WP_Error( 'review_item_changed', __( 'A newer version of this item was generated. Reload the list and review it again.', 'ai-product-tools' ), array( 'status' => 409 ) ); } return new WP_Error( 'reject_failed', __( 'Failed to reject the selected item.', 'ai-product-tools' ), array( 'status' => 500 ) ); } return new WP_REST_Response( array( 'success' => true, 'message' => __( 'Item discarded successfully.', 'ai-product-tools' ), 'data' => array( 'id' => $id ), ), 200 ); } /** * Bulk approve — apply multiple review rows. * * Returns a partial-outcome payload { applied: [...], skipped: [{id, reason}] }. * HTTP 200 on mixed or all-success outcomes; when EVERY item failed the * endpoint answers 409 with the same payload (nothing_applied), mirroring * SnapshotRestController::bulk_restore, so a 200 is never read as * "every row succeeded". * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function bulk_approve( $request ) { if ( ! self::isReviewEnabled() ) { return self::premiumRequiredError(); } $ids = self::sanitizeIds( $request->get_param( 'ids' ) ); if ( empty( $ids ) ) { return new WP_Error( 'invalid_params', __( 'At least one id is required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $versions = self::sanitizeVersions( $request->get_param( 'versions' ) ); $force = rest_sanitize_boolean( $request->get_param( 'force' ) ); $tokens = self::sanitizeTokens( $request->get_param( 'tokens' ) ); $store = static::store(); $rows_by_id = array(); $conflicted = array(); $expected_tokens = array(); foreach ( $ids as $id ) { $row = $store->get( $id ); $rows_by_id[ $id ] = $row; if ( null === $row ) { continue; } $pid = (int) ( $row['product_id'] ?? 0 ); if ( $pid > 0 && ! current_user_can( 'edit_post', $pid ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to edit this product.', 'ai-product-tools' ), array( 'status' => 403 ) ); } if ( self::reviewConflictGuard( $row, $tokens[ $id ] ?? '', $force ) instanceof WP_Error ) { $conflicted[ $id ] = true; continue; } $subject_id = SnapshotSubject::fromRow( $row )->postId(); if ( ! isset( $expected_tokens[ $subject_id ] ) ) { $expected_tokens[ $subject_id ] = self::currentTokenForRow( $row ); } } $applied = array(); $skipped = array(); foreach ( $ids as $id ) { $row = $rows_by_id[ $id ] ?? null; if ( null === $row ) { $skipped[] = array( 'id' => $id, 'reason' => 'not_found' ); continue; } if ( isset( $conflicted[ $id ] ) ) { $skipped[] = array( 'id' => $id, 'reason' => 'review_target_changed' ); continue; } $subject_id = SnapshotSubject::fromRow( $row )->postId(); if ( ! $force && isset( $expected_tokens[ $subject_id ] ) ) { $live_token = self::currentTokenForRow( $row ); if ( ! hash_equals( $live_token, $expected_tokens[ $subject_id ] ) ) { $skipped[] = array( 'id' => $id, 'reason' => 'review_target_changed' ); continue; } } $applier = static::applierFor( (string) ( $row['tool'] ?? '' ) ); $expected_version = $versions[ $id ] ?? null; $product_id = (int) ( $row['product_id'] ?? 0 ); $is_attachment = SnapshotSubject::fromRow( $row )->isAttachment(); $product_token_before = $is_attachment ? self::currentTokenForRow( array( 'product_id' => $product_id ) ) : ''; if ( ! $store->approve( $id, $applier, $expected_version ) ) { $current = $store->get( $id ); $refusal = $store->lastRefusal(); if ( null !== $refusal && '' !== $refusal['reason'] ) { $reason = $refusal['reason']; } elseif ( null !== $expected_version && null !== $current && 'pending' === (string) ( $current['status'] ?? '' ) ) { $reason = 'version_conflict'; } else { $reason = 'approve_failed'; } $skipped[] = array( 'id' => $id, 'reason' => $reason ); continue; } $expected_tokens[ $subject_id ] = self::currentTokenForRow( $row ); if ( $is_attachment && isset( $expected_tokens[ $product_id ] ) && hash_equals( $product_token_before, $expected_tokens[ $product_id ] ) ) { $product_token_after = self::currentTokenForRow( array( 'product_id' => $product_id ) ); if ( hash_equals( $product_token_before, $product_token_after ) || hash_equals( self::tokenAfterOneRevisionBump( $product_token_before ), $product_token_after ) ) { $expected_tokens[ $product_id ] = $product_token_after; } } $applied[] = $id; } if ( empty( $applied ) && ! empty( $skipped ) ) { return new WP_Error( 'nothing_applied', __( 'None of the selected items could be approved.', 'ai-product-tools' ), array( 'status' => 409, 'applied' => array(), 'skipped' => array_values( $skipped ), ) ); } return new WP_REST_Response( array( 'success' => true, 'data' => array( 'applied' => array_values( $applied ), 'skipped' => array_values( $skipped ), ), ), 200 ); } /** * Bulk reject — delete multiple review rows. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function bulk_reject( $request ) { if ( ! self::isReviewEnabled() ) { return self::premiumRequiredError(); } $ids = self::sanitizeIds( $request->get_param( 'ids' ) ); if ( empty( $ids ) ) { return new WP_Error( 'invalid_params', __( 'At least one id is required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $reject_versions = self::sanitizeVersions( $request->get_param( 'versions' ) ); $store = static::store(); $rows_by_id = array(); foreach ( $ids as $id ) { $row = $store->get( $id ); $rows_by_id[ $id ] = $row; if ( null === $row ) { continue; } $pid = (int) ( $row['product_id'] ?? 0 ); if ( $pid > 0 && ! current_user_can( 'edit_post', $pid ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to edit this product.', 'ai-product-tools' ), array( 'status' => 403 ) ); } } $applied = array(); $skipped = array(); foreach ( $ids as $id ) { $row = $rows_by_id[ $id ] ?? null; if ( null === $row ) { $skipped[] = array( 'id' => $id, 'reason' => 'not_found' ); continue; } $expected_version = $reject_versions[ $id ] ?? null; if ( ! $store->reject( $id, $expected_version ) ) { $current = $store->get( $id ); $reason = ( null !== $expected_version && null !== $current && 'pending' === (string) ( $current['status'] ?? '' ) && (int) ( $current['version'] ?? 0 ) !== $expected_version ) ? 'version_conflict' : 'reject_failed'; $skipped[] = array( 'id' => $id, 'reason' => $reason ); continue; } $applied[] = $id; } if ( empty( $applied ) && ! empty( $skipped ) ) { return new WP_Error( 'nothing_rejected', __( 'None of the selected items could be discarded.', 'ai-product-tools' ), array( 'status' => 409, 'applied' => array(), 'skipped' => array_values( $skipped ), ) ); } return new WP_REST_Response( array( 'success' => true, 'data' => array( 'applied' => array_values( $applied ), 'skipped' => array_values( $skipped ), ), ), 200 ); } /** * Bulk delete — delete multiple review rows (alias of bulk_reject at the store level). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function bulk_delete( $request ) { if ( ! self::isReviewEnabled() ) { return self::premiumRequiredError(); } $ids = self::sanitizeIds( $request->get_param( 'ids' ) ); if ( empty( $ids ) ) { return new WP_Error( 'invalid_params', __( 'At least one id is required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $store = static::store(); $rows_by_id = array(); foreach ( $ids as $id ) { $row = $store->get( $id ); $rows_by_id[ $id ] = $row; if ( null === $row ) { continue; } $pid = (int) ( $row['product_id'] ?? 0 ); if ( $pid > 0 && ! current_user_can( 'edit_post', $pid ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to edit this product.', 'ai-product-tools' ), array( 'status' => 403 ) ); } } $applied = array(); $skipped = array(); foreach ( $ids as $id ) { $row = $rows_by_id[ $id ] ?? null; if ( null === $row ) { $skipped[] = array( 'id' => $id, 'reason' => 'not_found' ); continue; } if ( 'in_progress' === (string) ( $row['status'] ?? '' ) && ( time() - (int) strtotime( (string) ( $row['updated_at'] ?? '' ) . ' UTC' ) ) < self::IN_PROGRESS_STALE_SECONDS ) { $skipped[] = array( 'id' => $id, 'reason' => 'active_claim' ); continue; } if ( ! $store->delete( $id ) ) { $skipped[] = array( 'id' => $id, 'reason' => 'delete_failed' ); continue; } $applied[] = $id; } if ( empty( $applied ) && ! empty( $skipped ) ) { return new WP_Error( 'nothing_deleted', __( 'None of the selected items could be deleted.', 'ai-product-tools' ), array( 'status' => 409, 'applied' => array(), 'skipped' => array_values( $skipped ), ) ); } return new WP_REST_Response( array( 'success' => true, 'data' => array( 'applied' => array_values( $applied ), 'skipped' => array_values( $skipped ), ), ), 200 ); } /** * Create a ContentReviewStore instance. * * @return ContentReviewStore */ protected static function store(): ContentReviewStore { return new ContentReviewStore(); } /** * Resolve the per-tool applier. * * Routes through {@see ContentReviewApplierFactory} rather than * instantiating the per-tool adapters (DescriptionApplier, TitleApplier, * ...) directly. Those adapters are all declared inside * ContentReviewApplier.php, one filename shared by six classes — a * standard, non-classmap-optimized Composer autoloader resolves PSR-4 * strictly by class-name-matches-filename and cannot find them on its * own. ContentReviewApplierFactory.php IS a 1:1 PSR-4 match for its own * class name, so autoloading it is guaranteed to work, and its file-level * `require_once __DIR__ . '/ContentReviewApplier.php'` loads all six * adapters as a side effect before this method's switch ever needs them. * Do not instantiate the adapters directly here again. * * @param string $tool Tool slug (description|title|faq|seo_meta|image_alt). * @return ContentReviewApplier */ protected static function applierFor( string $tool ): ContentReviewApplier { return ContentReviewApplierFactory::forTool( $tool ); } /** * List endpoint argument schema. * * @return array> */ private static function listArgs(): array { return array( 'tool' => array( 'sanitize_callback' => 'sanitize_key' ), 'product_id' => array( 'sanitize_callback' => 'absint' ), 'status' => array( 'sanitize_callback' => 'sanitize_key' ), 'cursor' => array( 'sanitize_callback' => array( __CLASS__, 'sanitizeCursor' ) ), 'limit' => array( 'default' => 25, 'sanitize_callback' => 'absint' ), ); } /** * Extract list filters from the request. * * @param WP_REST_Request $request Request object. * @return array */ private static function listFilters( $request ): array { $filters = array( 'tool' => sanitize_key( (string) $request->get_param( 'tool' ) ), 'product_id' => absint( $request->get_param( 'product_id' ) ), 'status' => sanitize_key( (string) $request->get_param( 'status' ) ), ); return array_filter( $filters, static function ( $value ): bool { return '' !== $value && 0 !== $value; } ); } /** * Sanitize the keyset cursor. * * @param mixed $value Raw array or JSON cursor. * @return array|null */ public static function sanitizeCursor( $value ): ?array { if ( is_string( $value ) ) { $value = json_decode( $value, true ); } if ( ! is_array( $value ) || empty( $value['created_at'] ) || empty( $value['id'] ) ) { return null; } return array( 'created_at' => sanitize_text_field( (string) $value['created_at'] ), 'id' => absint( $value['id'] ), ); } /** * Sanitize an array of ids. * * @param mixed $value Raw ids. * @return int[] */ private static function sanitizeIds( $value ): array { if ( ! is_array( $value ) ) { return array(); } $ids = array_map( 'absint', $value ); $ids = array_filter( $ids, static function ( $id ): bool { return $id > 0; } ); $ids = array_values( array_unique( $ids ) ); return array_slice( $ids, 0, self::MAX_BULK_IDS ); } /** * Sanitize an optional {id: version} map for bulk_approve()'s per-item * version binding. Non-numeric or non-positive-id entries are dropped * rather than rejecting the whole request — a malformed entry simply * loses version protection for that one id, falling back to the * pre-existing unversioned behavior for it alone. * * @param mixed $value Raw versions map (JSON object decodes to assoc array). * @return array Map of id => expected version. */ private static function sanitizeVersions( $value ): array { if ( ! is_array( $value ) ) { return array(); } $out = array(); foreach ( $value as $id => $version ) { $id = absint( $id ); if ( $id > 0 && is_numeric( $version ) ) { $out[ $id ] = (int) $version; } } return $out; } /** * Sanitize an optional {id: expected_token} map for bulk_approve()'s * per-item live-value conflict guard (R-review-conflict). Mirrors * sanitizeVersions() exactly: a malformed or non-string entry simply * loses the guard for that one id rather than rejecting the whole * request, matching this guard's own fail-open posture on a missing * token. * * @param mixed $value Raw tokens map (JSON object decodes to assoc array). * @return array Map of id => expected token. */ private static function sanitizeTokens( $value ): array { if ( ! is_array( $value ) ) { return array(); } $out = array(); foreach ( $value as $id => $token ) { $id = absint( $id ); if ( $id > 0 && is_string( $token ) && '' !== $token ) { $out[ $id ] = $token; } } return $out; } }