prefix . 'aipt_content_review'; } /** * A monotonically-increasing (for practical purposes) version stamp for * a review proposal, in microseconds since the epoch. Replaces * second-resolution `updated_at` as the optimistic-concurrency binding * used by claim()/approve() — see stage()'s UPDATE branch below. * * @return int */ private static function newVersion(): int { return (int) round( microtime( true ) * 1000000 ); } /** * The live optimistic-concurrency token for a review target RIGHT NOW — * captured into the `staged_token` column whenever a proposal is (re)staged * for this target, so approve()'s conflict guard (CR-26, see * {@see \AIPT\Core\ContentReview\ContentReviewController::reviewConflictGuard()}) * can always compare the live token against what the target carried at * stage time, not only when the client happens to echo one back. * * Deliberately mirrors ContentReviewController::currentTokenForRow()'s own * attachment/product branching rather than calling into the controller — * the store must not depend upward on its own REST controller. Both defer * to the same {@see ProductEditorConcurrencyToken} primitive, so the two * call sites can never disagree on the token FORMAT. * * @param int $product_id Product id (or, for image_alt, the owning product's id). * @param string $field_type Field type slug. * @param int $subject_id Sub-target id (attachment id for image_alt, 0 otherwise). * @return string Empty string when the subject cannot be resolved (for example a deleted product). */ private static function currentToken( int $product_id, string $field_type, int $subject_id ): string { $subject = SnapshotSubject::fromRow( array( 'product_id' => $product_id, 'field_type' => $field_type, 'subject_id' => $subject_id, ) ); if ( $subject->isAttachment() ) { $post = \function_exists( 'get_post' ) ? \get_post( $subject->postId() ) : null; $post_modified = ( is_object( $post ) && isset( $post->post_modified ) ) ? (string) $post->post_modified : ''; return $subject->token( $post_modified ); } $product = \function_exists( 'wc_get_product' ) ? \wc_get_product( $subject->postId() ) : false; if ( ! $product ) { return ''; } try { return ProductEditorConcurrencyToken::for_product( $product ); } catch ( \Throwable $e ) { return ''; } } /** * Instance-callable live optimistic-concurrency token for a review * target — the exact value {@see currentToken()} computes, exposed so a * caller that only holds an injected store (not this class statically), * such as {@see \AIPT\Core\ContentReview\ReviewQueueDecision}'s approve() * conflict guard, reads the SAME single source of truth stage() and * restagePending() stamp onto `staged_token`, and a test can stub it * through the injected mock. * * @param int $product_id Product id (or, for image_alt, the owning product's id). * @param string $field_type Field type slug. * @param int $subject_id Sub-target id (attachment id for image_alt, 0 otherwise). * @return string Empty string when the subject cannot be resolved (for example a deleted product). */ public function currentLiveToken( int $product_id, string $field_type, int $subject_id ): string { return self::currentToken( $product_id, $field_type, $subject_id ); } /** * Stage a generated value for review. * * UPSERT on the unique key (product_id, tool, field_type, subject_id, variant_index). * Returns null when the existing row is in_progress or applied — every caller * must surface that as "a previous approval is still in flight". * * @param int $product_id Product ID. * @param string $tool Generator tool slug (description|title|faq|seo_meta|image_alt). * @param string $field_type Field type slug. * @param int $subject_id Sub-target id (attachment id for image_alt, 0 for product-level). * @param string $generated_value Generated content. * @param array $opts Apply options (write_mode, plugin_slug, etc.). * @return int|null Row id on success, null when refused. */ public function stage( int $product_id, string $tool, string $field_type, int $subject_id, string $generated_value, array $opts ): ?int { global $wpdb; $table = self::table(); $now = \current_time( 'mysql', true ); $existing = self::findRow( $product_id, $tool, $field_type, $subject_id, (int) ( $opts['variant_index'] ?? 0 ) ); if ( null !== $existing ) { if ( 'in_progress' === $existing['status'] || 'applied' === $existing['status'] ) { return null; } return $this->updatePendingRow( $existing['id'], $generated_value, $opts ); } $data = array( 'product_id' => $product_id, 'tool' => $tool, 'field_type' => $field_type, 'subject_id' => $subject_id, 'generated_value' => $generated_value, 'value_format' => (string) ( $opts['value_format'] ?? 'text' ), 'variant_index' => (int) ( $opts['variant_index'] ?? 0 ), 'plugin_slug' => (string) ( $opts['plugin_slug'] ?? '' ), 'apply_context' => self::encodedApplyContext( $opts ), 'status' => 'pending', 'created_by' => isset( $opts['created_by'] ) ? (int) $opts['created_by'] : (int) ( \function_exists( 'get_current_user_id' ) ? \get_current_user_id() : 0 ), 'created_at' => $now, 'updated_at' => $now, 'version' => self::newVersion(), 'staged_token' => self::currentToken( $product_id, $field_type, $subject_id ), ); $data = array_merge( $data, self::blueprintOpts( $opts ) ); $result = $wpdb->insert( $table, $data, array( '%d', '%s', '%s', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%d', '%s', '%s', '%d', '%s', '%d', '%s', '%d', '%d' ) ); return false !== $result ? (int) $wpdb->insert_id : null; } /** * The one existing row for an exact target+subject+variant, if any. * * Shared by stage() (to decide upsert vs refuse) and * {@see hasActiveReview()} (a direct-apply write path's "is a teammate * already reviewing this" guard), so both agree on the identical target * identity from a single query instead of two copies drifting apart. * * @param int $product_id Product ID. * @param string $tool Generator tool slug. * @param string $field_type Field type slug. * @param int $subject_id Sub-target id. * @param int $variant_index Variant index. * @return array{id:int,status:string}|null */ private static function findRow( int $product_id, string $tool, string $field_type, int $subject_id, int $variant_index ): ?array { global $wpdb; if ( ! isset( $wpdb ) ) { return null; } $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT id, status FROM {$table} WHERE product_id = %d AND tool = %s AND field_type = %s AND subject_id = %d AND variant_index = %d", $product_id, $tool, $field_type, $subject_id, $variant_index ), ARRAY_A ); if ( ! is_array( $row ) ) { return null; } return array( 'id' => (int) ( $row['id'] ?? 0 ), 'status' => (string) ( $row['status'] ?? '' ), ); } /** * Whether a target currently has an unresolved review proposal — * `pending` (awaiting a teammate) or `in_progress` (being approved right * now) — for one subject. * * A direct-apply write path for the same field * (for example {@see \AIPT\Api\BulkGenerator\ImageAlt\ImageAltController::bulk_apply()}) * calls this before writing live, so a result a teammate is already * reviewing is never silently superseded by the generating admin's own * direct apply — the review queue, not that route, owns writing it. An * `applied` row reads as resolved (not active): its own write already * landed, through the review queue's own applier, not this one. * * @param int $product_id Product ID. * @param string $tool Generator tool slug. * @param string $field_type Field type slug. * @param int $subject_id Sub-target id (attachment id for image_alt). * @return bool */ public function hasActiveReview( int $product_id, string $tool, string $field_type, int $subject_id ): bool { $row = self::findRow( $product_id, $tool, $field_type, $subject_id, 0 ); return null !== $row && in_array( $row['status'], array( 'pending', 'in_progress' ), true ); } /** * Build the four blueprint-attribution columns from a stage()/ * restagePending() `$opts` array. Denormalized onto every row that * knows its blueprint, so a later rename or delete of that blueprint * never blanks this row's history. Absent for a * custom-prompts write, which leaves every column at its DB default. * * @since 2.8.0 * @param array $opts stage()/restagePending() opts. * @return array{blueprint_id:int,blueprint_name:string,blueprint_revision:int,blueprint_builtin:int} */ private static function blueprintOpts( array $opts ): array { return array( 'blueprint_id' => isset( $opts['blueprint_id'] ) ? (int) $opts['blueprint_id'] : 0, 'blueprint_name' => isset( $opts['blueprint_name'] ) ? (string) $opts['blueprint_name'] : '', 'blueprint_revision' => isset( $opts['blueprint_revision'] ) ? (int) $opts['blueprint_revision'] : 0, 'blueprint_builtin' => ! empty( $opts['blueprint_builtin'] ) ? 1 : 0, ); } /** * Replace the generated value of a proposal that is still pending. * * Unlike stage(), it never inserts: a row Content Bank already approved, * rejected or is approving is refused, so a decided proposal cannot be * resurrected. The replaced proposal gets a new version, so a reviewer * holding the old one gets a version conflict instead of applying it. * * When $expectedVersion is supplied, the replace ALSO requires the row's * CURRENT version to still match it — the same optimistic-concurrency * binding claim()/reject() already support (see claim()'s own docblock), * applied here so an edit built on a proposal that moved since the * caller last saw it (a regenerate, or another edit, landed first) is * refused instead of silently overwriting it. Omitting it preserves the * pre-existing unversioned behavior. * * @param int $id Row id. * @param string $generated_value New generated content. * @param array $opts Apply options (plugin_slug, apply_context, ...), as for stage(). * @param int|null $expectedVersion Optional expected `version` to bind the replace to. * @return bool True when the row is pending (and, if supplied, still at $expectedVersion) with the new value. */ public function restagePending( int $id, string $generated_value, array $opts, ?int $expectedVersion = null ): bool { return null !== $this->updatePendingRow( $id, $generated_value, $opts, $expectedVersion ); } /** * Update a pending row with a new proposal. * * @param int $existing_id Row id. * @param string $generated_value New generated content. * @param array $opts Apply options. * @param int|null $expectedVersion Optional expected `version` to bind the update to. * @return int|null Row id, or null when the row is not pending (or, when supplied, not at $expectedVersion). */ private function updatePendingRow( int $existing_id, string $generated_value, array $opts, ?int $expectedVersion = null ): ?int { global $wpdb; $table = self::table(); $now = \current_time( 'mysql', true ); $identity = $wpdb->get_row( $wpdb->prepare( "SELECT product_id, field_type, subject_id FROM {$table} WHERE id = %d", $existing_id ) ); if ( is_array( $identity ) ) { $identity_row = $identity; } elseif ( is_object( $identity ) ) { $identity_row = (array) $identity; } else { $identity_row = null; } $staged_token = null !== $identity_row ? self::currentToken( (int) ( $identity_row['product_id'] ?? 0 ), (string) ( $identity_row['field_type'] ?? '' ), (int) ( $identity_row['subject_id'] ?? 0 ) ) : ''; $where = array( 'id' => $existing_id, 'status' => 'pending', ); $where_format = array( '%d', '%s' ); if ( null !== $expectedVersion ) { $where['version'] = $expectedVersion; $where_format[] = '%d'; } $data = array( 'generated_value' => $generated_value, 'value_format' => (string) ( $opts['value_format'] ?? 'text' ), 'plugin_slug' => (string) ( $opts['plugin_slug'] ?? '' ), 'apply_context' => self::encodedApplyContext( $opts ), 'status' => 'pending', 'created_by' => isset( $opts['created_by'] ) ? (int) $opts['created_by'] : (int) ( \function_exists( 'get_current_user_id' ) ? \get_current_user_id() : 0 ), 'created_at' => $now, 'updated_at' => $now, 'version' => self::newVersion(), 'staged_token' => $staged_token, ); $format = array( '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%d', '%s' ); if ( array_key_exists( 'blueprint_id', $opts ) || array_key_exists( 'blueprint_name', $opts ) || array_key_exists( 'blueprint_revision', $opts ) || array_key_exists( 'blueprint_builtin', $opts ) ) { $data = array_merge( $data, self::blueprintOpts( $opts ) ); $format = array_merge( $format, array( '%d', '%s', '%d', '%d' ) ); } $result = $wpdb->update( $table, $data, $where, $format, $where_format ); if ( false === $result ) { return null; } if ( (int) $result >= 1 ) { return $existing_id; } if ( null !== $expectedVersion ) { $still_pending = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE id = %d AND status = 'pending' AND version = %d", $existing_id, $expectedVersion ) ); } else { $still_pending = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE id = %d AND status = 'pending'", $existing_id ) ); } return null !== $still_pending ? $existing_id : null; } /** * Atomically claim a pending row: pending → in_progress. * * Uses a conditional UPDATE so two concurrent claims cannot both succeed. * Mirrors DraftContentManager::approveDraftContent() claim shape. * * When $expectedVersion is supplied, the claim ALSO requires the row's * version to still match it (a version/optimistic-concurrency check). * This closes a race where a reviewer has proposal A open, a second * generation for the same target finishes and stage() overwrites the * pending row's content with proposal B (same id, new version) before * the reviewer clicks Approve — without the check, the server would * claim and apply B even though the reviewer saw and approved A. A * caller that omits it (the pre-existing contract) gets the unversioned * behavior unchanged. Bound to the microsecond-epoch `version` column, * not `updated_at` — two regenerates landing in the same MySQL second * share an identical updated_at and would defeat this exact check. * * @param int $id Row id. * @param int|null $expectedVersion Optional expected `version` to bind the claim to. * @return bool True if claimed, false if already claimed, not pending, or the version no longer matches. */ public function claim( int $id, ?int $expectedVersion = null ): bool { global $wpdb; $table = self::table(); $now = \current_time( 'mysql', true ); $where = array( 'id' => $id, 'status' => 'pending' ); $where_format = array( '%d', '%s' ); if ( null !== $expectedVersion ) { $where['version'] = $expectedVersion; $where_format[] = '%d'; } $result = $wpdb->update( $table, array( 'status' => 'in_progress', 'updated_at' => $now, ), $where, array( '%s', '%s' ), $where_format ); return false !== $result && (int) $result >= 1; } /** * Release an in_progress row back to pending. * * Used ONLY for pre-applier failures. Never auto-requeue after the * applier was invoked — a live write may already have landed. * * @param int $id Row id. * @return void */ public function release( int $id ): void { global $wpdb; $table = self::table(); $now = \current_time( 'mysql', true ); $wpdb->update( $table, array( 'status' => 'pending', 'updated_at' => $now, ), array( 'id' => $id, 'status' => 'in_progress', ), array( '%s', '%s' ), array( '%d', '%s' ) ); } /** * Approve a review row: claim → apply → commit → delete. * * The Store owns EVERY status transition and the row deletion; the applier * NEVER touches status or deletes. * * Failure split: * - Before applier (claim failed, missing row): release not needed (never claimed). * - After applier returned false: leave in_progress, NEVER auto-requeue. * * @param int $id Row id. * @param ContentReviewApplier $applier The per-tool applier. * @param int|null $expectedVersion Optional version binding — see claim(). * @return bool True on successful apply and delete. */ public function approve( int $id, ContentReviewApplier $applier, ?int $expectedVersion = null ): bool { global $wpdb; $table = self::table(); $now = \current_time( 'mysql', true ); $this->last_refusal = null; if ( ! $this->claim( $id, $expectedVersion ) ) { return false; } $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d AND status = 'in_progress'", $id ), ARRAY_A ); if ( ! is_array( $row ) ) { return false; } $product_token_before = SnapshotSubject::fromRow( $row )->isAttachment() ? self::currentToken( (int) ( $row['product_id'] ?? 0 ), '', 0 ) : ''; try { $applied = $applier->apply( $row ); } catch ( ContentReviewApplyRefusedException $refused ) { $this->release( $id ); $this->last_refusal = array( 'message' => $refused->getMessage(), 'reason' => $refused->reason(), ); return false; } catch ( \Throwable $t ) { \AIPT\Core\ContentSnapshots\SnapshotStore::finalizeStaged( (int) ( $row['product_id'] ?? 0 ), true ); return false; } if ( ! $applied ) { return false; } $final = $wpdb->update( $table, array( 'status' => 'applied', 'updated_at' => $now, ), array( 'id' => $id, 'status' => 'in_progress', ), array( '%s', '%s' ), array( '%d', '%s' ) ); if ( false === $final || (int) $final < 1 ) { return false; } $wpdb->delete( $table, array( 'id' => $id ), array( '%d' ) ); $this->rebasePendingSiblingTokens( $row, $id ); if ( '' !== $product_token_before ) { $this->rebaseProductSiblingTokens( (int) ( $row['product_id'] ?? 0 ), $product_token_before, $id ); } return true; } /** * Advance the staged_token of rows still pending for the same subject. * * Called only after a verified-clean approve() of `$applied_row`, so the * new token reflects our own write and nothing else. Rows for other * subjects, and rows in any status other than `pending`, are untouched. * * @param array $applied_row The row that was just applied. * @param int $applied_id Its id, excluded from the update. * @return void */ private function rebasePendingSiblingTokens( array $applied_row, int $applied_id ): void { $product_id = (int) ( $applied_row['product_id'] ?? 0 ); if ( $product_id <= 0 ) { return; } $subject_id = (int) ( $applied_row['subject_id'] ?? 0 ); $baseline_token = (string) ( $applied_row['staged_token'] ?? '' ); if ( '' === $baseline_token ) { return; } $new_token = self::currentToken( $product_id, (string) ( $applied_row['field_type'] ?? '' ), $subject_id ); $this->advanceStagedToken( $product_id, $subject_id, $baseline_token, $new_token, $applied_id ); } /** * Advance the staged_token of the product-level rows still pending after an * attachment (image-alt) write. * * ImageAltApplier bumps the owning product's revision as well as the * attachment's, so product-level rows (subject_id 0) staged against the * pre-write product token would otherwise 409 as review_target_changed * although nobody edited the product. * * @param int $product_id Owning product id. * @param string $product_token_before Live product token read before the write. * @param int $applied_id Id of the row that was just applied. * @return void */ private function rebaseProductSiblingTokens( int $product_id, string $product_token_before, int $applied_id ): void { if ( $product_id <= 0 ) { return; } $new_token = self::currentToken( $product_id, '', 0 ); $this->advanceStagedToken( $product_id, 0, $product_token_before, $new_token, $applied_id ); } /** * Move pending rows of one subject from a baseline token to a new one. * * @param int $product_id Product id. * @param int $subject_id Row subject (0 for product-level rows). * @param string $baseline_token Token the rows must currently hold. * @param string $new_token Token to store. * @param int $applied_id Id excluded from the update. * @return void */ private function advanceStagedToken( int $product_id, int $subject_id, string $baseline_token, string $new_token, int $applied_id ): void { global $wpdb; if ( '' === $baseline_token || '' === $new_token || $new_token === $baseline_token ) { return; } $table = self::table(); $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET staged_token = %s WHERE product_id = %d AND subject_id = %d AND status = 'pending' AND id <> %d AND staged_token = %s", $new_token, $product_id, $subject_id, $applied_id, $baseline_token ) ); } /** * Why the applier refused the row in the most recent approve() call. * * Null when that call did not end in an applier refusal. * * @return array{message:string,reason:string}|null */ public function lastRefusal(): ?array { return $this->last_refusal; } /** * Every row of one product-level review target, in any status. * * A target is (product_id, tool, field_type) at subject_id 0; rows can * differ by variant_index. A generator page uses this to tell a pending * proposal from one that Content Bank is approving or already decided. * * @param int $product_id Product ID. * @param string $tool Generator tool slug. * @param string $field_type Field type slug. * @return array */ public function findTargetRows( int $product_id, string $tool, string $field_type ): array { global $wpdb; $table = self::table(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, status, variant_index FROM {$table} WHERE product_id = %d AND tool = %s AND field_type = %s AND subject_id = %d ORDER BY variant_index ASC, id ASC", $product_id, $tool, $field_type, 0 ), ARRAY_A ); if ( ! is_array( $rows ) ) { return array(); } return array_values( array_map( static function ( $row ): array { $row = (array) $row; return array( 'id' => (int) ( $row['id'] ?? 0 ), 'status' => (string) ( $row['status'] ?? '' ), 'variant_index' => (int) ( $row['variant_index'] ?? 0 ), ); }, $rows ) ); } /** * Reject a review row — delete it. * * Conditional on status='pending' in the SAME delete statement: a row * another request has already atomically claimed as in_progress (via * {@see claim()}) must never be removed out from under an approve() that * may still write it live. An unconditional check-then-delete would be a * TOCTOU race — this makes the claim itself the guard. A stuck * in_progress row is cleared through the separate bulk-delete path, not * through reject(). * * When $expected_version is supplied it is bound into the SAME delete, so * a proposal that was regenerated after the reviewer loaded the list (a * `stage()` bumps `version`) is NOT discarded by a click aimed at the * older content. Mirrors approve()'s optimistic-concurrency guard; passing * null keeps the pre-existing unconditional behavior for callers that * cannot know the version. * * @param int $id Row id. * @param int|null $expected_version Version the caller last displayed. * @return bool True if a pending row at that version was deleted. */ public function reject( int $id, ?int $expected_version = null ): bool { global $wpdb; $table = self::table(); $where = array( 'id' => $id, 'status' => 'pending', ); $where_format = array( '%d', '%s' ); if ( null !== $expected_version ) { $where['version'] = $expected_version; $where_format[] = '%d'; } $result = $wpdb->delete( $table, $where, $where_format ); return false !== $result && (int) $result >= 1; } /** * Update the generated value of a pending review row. * * @param int $id Row id. * @param string $generated_value New generated content. * @return bool True if updated. */ public function regenerate( int $id, string $generated_value ): bool { global $wpdb; $table = self::table(); $now = \current_time( 'mysql', true ); $result = $wpdb->update( $table, array( 'generated_value' => $generated_value, 'status' => 'pending', 'created_at' => $now, 'updated_at' => $now, ), array( 'id' => $id, 'status' => 'pending', ), array( '%s', '%s', '%s', '%s' ), array( '%d', '%s' ) ); return false !== $result && (int) $result >= 1; } /** * Delete a review row by id. * * @param int $id Row id. * @return bool True if deleted. */ public function delete( int $id ): bool { global $wpdb; $table = self::table(); $result = $wpdb->delete( $table, array( 'id' => $id ), array( '%d' ) ); return false !== $result && (int) $result >= 1; } /** * Read a single review row by id. * * @param int $id Row id. * @return array|null Row data or null if absent. */ public function get( int $id ): ?array { global $wpdb; $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ), ARRAY_A ); return is_array( $row ) ? $this->mapRow( $row ) : null; } /** * List review rows with keyset pagination and optional filters. * * Keyset cursor is (created_at, id). The `has_more` flag is computed by * fetching one extra row (the "look-ahead" fix from round 5): when exactly * `limit` rows are returned, a 101st row is fetched to determine whether * there are more pages. This prevents the phantom empty page when the last * page is exactly full. * * @param array $filters Exact-match filters (tool, product_id, status). * @param array|null $cursor Last-seen (created_at, id) or null for first page. * @param int $limit Requested page size (max 100). * @return array{rows: array>, has_more: bool, next_cursor: array|null} */ public function list( array $filters, ?array $cursor, int $limit ): array { global $wpdb; $table = self::table(); $limit = $limit > 0 ? min( self::MAX_LIST_LIMIT, $limit ) : self::DEFAULT_LIST_LIMIT; $fetch_limit = $limit + 1; $where = $this->buildListWhere( $filters ); if ( is_array( $cursor ) && ! empty( $cursor['created_at'] ) && ! empty( $cursor['id'] ) ) { $where[] = $wpdb->prepare( '(created_at, id) < (%s, %d)', (string) $cursor['created_at'], (int) $cursor['id'] ); } $where_sql = empty( $where ) ? '' : ' WHERE ' . implode( ' AND ', $where ); $rows = $wpdb->get_results( "SELECT * FROM {$table}{$where_sql} ORDER BY created_at DESC, id DESC LIMIT {$fetch_limit}", ARRAY_A ); $has_more = false; $next_cursor = null; if ( is_array( $rows ) && count( $rows ) > $limit ) { $has_more = true; array_pop( $rows ); $last = end( $rows ); if ( is_array( $last ) ) { $next_cursor = array( 'created_at' => (string) ( $last['created_at'] ?? '' ), 'id' => (int) ( $last['id'] ?? 0 ), ); } } elseif ( is_array( $rows ) && count( $rows ) === $limit ) { $last = end( $rows ); if ( is_array( $last ) ) { $next_cursor = array( 'created_at' => (string) ( $last['created_at'] ?? '' ), 'id' => (int) ( $last['id'] ?? 0 ), ); } } if ( ! is_array( $rows ) ) { $rows = array(); } $mapped = array_map( array( $this, 'mapRow' ), $rows ); return array( 'rows' => $mapped, 'has_more' => $has_more, 'next_cursor' => $has_more ? $next_cursor : null, ); } /** * Count matching rows for the supplied filters. * * @param array $filters Exact-match filters. * @return int Total matching row count. */ public function count( array $filters ): int { global $wpdb; $table = self::table(); $where = $this->buildListWhere( $filters ); $where_sql = empty( $where ) ? '' : ' WHERE ' . implode( ' AND ', $where ); return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}{$where_sql}" ); } /** * Batched prune of applied rows. * * Scans applied rows in keyset-advancing windows ordered by id, so every * row is eventually reached. Capped by {@see MAX_DELETIONS_PER_TICK} so a * single tick never runs unbounded. Leftovers are cleaned on subsequent ticks. * * This is called by the ContentReviewCleaner cron (todo 2). The Store does * NOT own its own cron — retention is owned by ContentReviewCleaner. * * @return int Number of rows deleted. */ public function prune(): int { global $wpdb; $table = self::table(); $window = $this->pruneReadLimit(); $budget = $this->pruneDeletionBudget(); $delete_ids = array(); $cursor_id = 0; while ( count( $delete_ids ) < $budget ) { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id FROM {$table} WHERE status = 'applied' AND id > %d ORDER BY id ASC LIMIT %d", $cursor_id, $window ) ); if ( empty( $rows ) || ! is_array( $rows ) ) { break; } foreach ( $rows as $row ) { $row_id = is_array( $row ) ? (int) ( $row['id'] ?? 0 ) : (int) $row->id; $delete_ids[] = $row_id; if ( count( $delete_ids ) >= $budget ) { break; } } $last = end( $rows ); if ( $last ) { $cursor_id = is_array( $last ) ? (int) ( $last['id'] ?? 0 ) : (int) $last->id; } if ( count( $rows ) < $window ) { break; } } if ( empty( $delete_ids ) ) { return 0; } $ids_in = implode( ',', array_map( 'intval', $delete_ids ) ); $deleted = $wpdb->query( "DELETE FROM {$table} WHERE id IN ($ids_in)" ); return is_numeric( $deleted ) ? (int) $deleted : 0; } /** * Build WHERE clauses for list() and count(). * * @param array $filters Read filters. * @return array */ private function buildListWhere( array $filters ): array { global $wpdb; $where = array(); $visibility = \AIPT\Core\ContentBank\ProductVisibilityScope::whereFragment( 'product_id' ); if ( null !== $visibility ) { $where[] = $visibility; } if ( ! empty( $filters['tool'] ) ) { $where[] = $wpdb->prepare( 'tool = %s', (string) $filters['tool'] ); } if ( ! empty( $filters['product_id'] ) ) { $where[] = $wpdb->prepare( 'product_id = %d', (int) $filters['product_id'] ); } if ( ! empty( $filters['status'] ) ) { $where[] = $wpdb->prepare( 'status = %s', (string) $filters['status'] ); } if ( ! empty( $filters['field_type'] ) ) { $where[] = $wpdb->prepare( 'field_type = %s', (string) $filters['field_type'] ); } return $where; } /** * Map a raw database row to the canonical response shape. * * @param array $row Database row. * @return array */ private function mapRow( array $row ): array { return array( 'id' => (int) ( $row['id'] ?? 0 ), 'product_id' => (int) ( $row['product_id'] ?? 0 ), 'tool' => (string) ( $row['tool'] ?? '' ), 'field_type' => (string) ( $row['field_type'] ?? '' ), 'subject_id' => (int) ( $row['subject_id'] ?? 0 ), 'generated_value' => (string) ( $row['generated_value'] ?? '' ), 'value_format' => (string) ( $row['value_format'] ?? 'text' ), 'variant_index' => (int) ( $row['variant_index'] ?? 0 ), 'plugin_slug' => (string) ( $row['plugin_slug'] ?? '' ), 'apply_context' => isset( $row['apply_context'] ) ? $row['apply_context'] : null, 'status' => (string) ( $row['status'] ?? 'pending' ), 'created_by' => (int) ( $row['created_by'] ?? 0 ), 'created_at' => (string) ( $row['created_at'] ?? '' ), 'updated_at' => (string) ( $row['updated_at'] ?? '' ), 'version' => (int) ( $row['version'] ?? 0 ), 'staged_token' => (string) ( $row['staged_token'] ?? '' ), 'section_notices' => self::decodedSectionNotices( $row['apply_context'] ?? null ), ) + self::blueprintReadShape( $row ); } /** * The stored apply_context: the caller's own apply options, plus any * section notices under `sectionNotices`. The notices ride in this * existing column so a new release needs no schema change before it can * stage a row; every applier reads apply_context by key and ignores * `sectionNotices`. The key is only written when there is a notice, so a * row without one keeps exactly the caller's own JSON. * * @param array $opts Stage or restage options. * @return string|null JSON, or null when there is nothing to store. */ private static function encodedApplyContext( array $opts ): ?string { $notices = isset( $opts['section_notices'] ) && is_array( $opts['section_notices'] ) ? array_values( array_filter( $opts['section_notices'], 'is_array' ) ) : array(); $context = $opts['apply_context'] ?? null; if ( array() === $notices || ( null !== $context && ! is_array( $context ) ) ) { return null !== $context ? \wp_json_encode( $context ) : null; } $context = $context ?? array(); $context['sectionNotices'] = $notices; return \wp_json_encode( $context ); } /** * @param mixed $raw Raw `apply_context` column value (a JSON string, or null). * @return array */ private static function decodedSectionNotices( $raw ): array { if ( ! is_string( $raw ) || '' === $raw ) { return array(); } $decoded = json_decode( $raw, true ); $notices = is_array( $decoded ) && isset( $decoded['sectionNotices'] ) && is_array( $decoded['sectionNotices'] ) ? $decoded['sectionNotices'] : array(); return array_values( array_filter( $notices, 'is_array' ) ); } /** * The denormalized blueprint-attribution read shape shared by every * Content Bank row (History, Review, Drafts): `blueprint_id` and * `blueprint_revision` read 0 as null (0 is never a real id or * revision), `blueprint_name` is always a string, and `blueprint_builtin` * is always a bool. A row with nothing recorded (the pre-existing * default for every column) surfaces as "no blueprint recorded" rather * than a fabricated id of 0. * * @since 2.8.0 * @param array $row Database row. * @return array{blueprint_id:int|null,blueprint_name:string,blueprint_revision:int|null,blueprint_builtin:bool} */ private static function blueprintReadShape( array $row ): array { $blueprint_id = isset( $row['blueprint_id'] ) ? (int) $row['blueprint_id'] : 0; $blueprint_revision = isset( $row['blueprint_revision'] ) ? (int) $row['blueprint_revision'] : 0; return array( 'blueprint_id' => $blueprint_id > 0 ? $blueprint_id : null, 'blueprint_name' => (string) ( $row['blueprint_name'] ?? '' ), 'blueprint_revision' => $blueprint_revision > 0 ? $blueprint_revision : null, 'blueprint_builtin' => ! empty( $row['blueprint_builtin'] ), ); } /** * Rows a single prune read pulls into PHP. * * Isolated for test override. * * @return int */ protected function pruneReadLimit(): int { return self::PRUNE_READ_LIMIT; } /** * Rows a single prune tick may delete. * * Isolated for test override. * * @return int */ protected function pruneDeletionBudget(): int { return self::MAX_DELETIONS_PER_TICK; } }