prefix}aipt_content_snapshots * table, so every plan retains readable content history. * * Design (see docs/unified-rollback-design.md, chosen in T0.1): * - Capped ring-buffer per (product_id × field_type × subject_id): the CAP * most-recent non-original snapshots are kept. * - Pin-the-original: the FIRST pre-AI snapshot for each group is stored with * is_original = 1 and is NEVER pruned. * - Cron-batched pruning: enforcing the cap runs ONLY from a dedicated WP-Cron * hook ({@see CRON_HOOK}); it NEVER runs inline inside an apply request. * * Capture, reads and pruning are always shipped and never plan-gated. Restore * writers remain in the Business-only premium subclass. * * Out of scope (deliberately): product variations (rejected upstream in * ContentGenerator), taxonomy terms, and ProductEditor client-side undo. * * @package AIPT\Core\ContentSnapshots * @since 2.7.2 */ namespace AIPT\Core\ContentSnapshots; use AIPT\Api\BulkGenerator\SeoMeta\Core\SeoPluginDetector; use AIPT\Utils\UtcTimestamp; defined( 'ABSPATH' ) || exit; /** * Writes pre-AI snapshots, serves history and prunes the ring buffer. */ class SnapshotStore { /** * WP-Cron hook that runs the cron-batched pruning. Pruning NEVER runs inline * in an apply request — only from this scheduled event. */ public const CRON_HOOK = 'aipt_prune_content_snapshots'; /** * Restorable non-original snapshots kept per (product × field × subject). * The pinned original (is_original = 1) is additional and never counted here. * * @deprecated 2.7.2 Use {@see self::retentionCap()} instead — the cap is now * configurable via the `aipt_content_history_retention` option. */ public const CAP = 10; /** * Resolve the per-group retention cap from the site option. * * Clamped to 1..10. Defaults to the legacy {@see self::CAP} (10) when the * option has never been set, so an upgrade from a pre-2.7.2 install never * prunes snapshots the site already relied on keeping. Sites that * explicitly configure the option (including re-saving the default 5 * from the settings UI) get that value instead. The pinned original * (is_original = 1) is additional and NEVER pruned regardless of this cap. * * @since 2.7.2 * @return int Clamped retention cap. */ public static function retentionCap(): int { $value = (int) get_option( 'aipt_content_history_retention', self::CAP ); return max( 1, min( 10, $value ) ); } /** * Max rows a single prune read pulls into PHP. Bounds memory on large stores; * groups whose tail is cut are simply caught up on the next cron tick. */ public const PRUNE_READ_LIMIT = 5000; /** * Max rows deleted in one prune tick. Caps worst-case runtime; leftovers are * cleaned on subsequent ticks. */ public const MAX_DELETIONS_PER_TICK = 1000; /** * Whether init() has already registered hooks. * * @var bool */ private static bool $initialized = false; /** * Snapshot row ids staged (status='pending') by handle_before_apply(), * bucketed by product_id, awaiting a matching finalizeStaged() call. * * Each entry records BOTH the row id and the field_type it was staged for, * so a multi-field apply can finalize per-field ({@see finalizeStagedByField()}) * — committing the snapshots whose field write landed and rolling back the * rest, instead of an all-or-nothing decision keyed on one boolean. * * do_action('aipt_before_apply_result'|'aipt_before_content_apply', ...) * has no return channel, so the ids a staging pass inserts cannot be handed * back to the caller directly. Every apply path fires a companion "after" * event once the real write's success/failure is known * ({@see \AIPT\Api\Rollback\ContentApplyDispatcher::after()} for generators, * `aipt_after_apply_result` for automation); handle_after_apply() drains * this buffer for that product_id and commits or rolls back exactly the * rows THIS request staged — never another concurrent request's, since * this is per-PHP-process static state. * * @var array> */ private static array $pendingStagedIds = array(); /** * Snapshot row ids staged (status='pending') by handle_before_term_apply(), * bucketed by a "{taxonomy}:{term_id}" key — never by the bare numeric * term id, and never sharing {@see $pendingStagedIds}'s product-keyed * buffer. A term id could numerically collide with an unrelated product * id staged in the same request, and applyDescriptions() applies to * MULTIPLE terms per request, so a shared or zero-keyed bucket would let * one term's failed write roll back (or wrongly commit) a different * term's staged snapshot. * * @since 2.8.0 * @var array> */ private static array $pendingStagedTermIds = array(); /** * Register universal snapshot capture and pruning hooks. * * @return void */ public static function init(): void { if ( self::$initialized ) { return; } add_action( 'aipt_before_apply_result', array( __CLASS__, 'handle_before_apply' ), 5, 3 ); add_action( 'aipt_before_content_apply', array( __CLASS__, 'handle_before_apply' ), 5, 1 ); add_action( 'aipt_after_content_apply', array( __CLASS__, 'handle_after_apply' ), 5, 2 ); add_action( 'aipt_after_apply_result', array( __CLASS__, 'handle_after_apply' ), 5, 2 ); add_action( 'aipt_before_term_apply', array( __CLASS__, 'handle_before_term_apply' ), 5, 1 ); add_action( 'aipt_after_term_apply', array( __CLASS__, 'handle_after_term_apply' ), 5, 3 ); add_action( self::CRON_HOOK, array( __CLASS__, 'cron_callback' ) ); self::schedule(); self::$initialized = true; } /** * Schedule the daily pruning cron if not already scheduled. * * @return void */ public static function schedule(): void { if ( ! \wp_next_scheduled( self::CRON_HOOK ) ) { \wp_schedule_event( time(), 'daily', self::CRON_HOOK ); } } /** * Unschedule the pruning cron on plugin deactivation. * * @return void */ public static function unschedule(): void { \wp_clear_scheduled_hook( self::CRON_HOOK ); } /** * Cron callback — runs the cron-batched pruning. Never throws. * * @return void */ public static function cron_callback(): void { try { ( new self() )->prune(); ( new self() )->reapStalePending(); } catch ( \Throwable $e ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { } } } /** * Capture pre-AI snapshots for the fields an automation apply will overwrite. * * Fired on `aipt_before_apply_result`, BEFORE the product is mutated, so every * captured value is the genuine pre-apply original. Only fields present in the * result (i.e. actually about to change) are snapshotted. Pruning is NOT run * here — that is exclusively the job of the cron callback. * * @param mixed $result Normalized per-product result payload. * @param mixed $draft_manager Draft content manager (unused; hook parity). * @param mixed $logger Job logger (unused; hook parity). * @param mixed $backup Whether legacy draft-backup was requested (unused). * @return void */ public static function handle_before_apply( $result, $draft_manager = null, $logger = null, $backup = false ): void { if ( ! is_array( $result ) ) { return; } $product_id = isset( $result['product_id'] ) ? (int) $result['product_id'] : 0; if ( $product_id <= 0 ) { return; } $product = function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : null; if ( ! $product ) { return; } $store = new self(); $source = self::normalizeSource( isset( $result['source'] ) ? (string) $result['source'] : 'automation' ); $applied_by = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0; $origin = array( 'source' => $source, 'applied_by' => $applied_by, ); if ( ! empty( $result['plugin_slug'] ) ) { $origin['plugin_slug'] = (string) $result['plugin_slug']; } if ( isset( $result['blueprint_id'] ) || isset( $result['blueprint_name'] ) || isset( $result['blueprint_revision'] ) || isset( $result['blueprint_builtin'] ) ) { $origin['blueprint_id'] = isset( $result['blueprint_id'] ) ? (int) $result['blueprint_id'] : 0; $origin['blueprint_name'] = isset( $result['blueprint_name'] ) ? (string) $result['blueprint_name'] : ''; $origin['blueprint_revision'] = isset( $result['blueprint_revision'] ) ? (int) $result['blueprint_revision'] : 0; $origin['blueprint_builtin'] = ! empty( $result['blueprint_builtin'] ); } $title_snapshot_id = null; if ( isset( $result['title'] ) ) { $title_snapshot_id = $store->stageTracked( $product_id, 'title', (string) $product->get_name(), array_merge( $origin, array( 'value_format' => 'text' ), self::generatedValueOpt( $result['title'] ) ) ); } if ( isset( $result['slug'] ) ) { $slug_snapshot_id = $store->stageTracked( $product_id, 'slug', (string) $product->get_slug(), array_merge( $origin, array( 'value_format' => 'text' ) ) ); if ( null !== $title_snapshot_id && null !== $slug_snapshot_id ) { $store->linkSnapshots( $title_snapshot_id, $slug_snapshot_id ); } } if ( isset( $result['description'] ) ) { $store->stageTracked( $product_id, 'description', (string) $product->get_description(), array_merge( $origin, array( 'value_format' => 'html' ), self::generatedValueOpt( $result['description'] ) ) ); } if ( isset( $result['short_desc'] ) ) { $store->stageTracked( $product_id, 'short_description', (string) $product->get_short_description(), array_merge( $origin, array( 'value_format' => 'html' ), self::generatedValueOpt( $result['short_desc'] ) ) ); } if ( ! empty( $result['tags'] ) && is_array( $result['tags'] ) ) { $names = array(); if ( function_exists( 'wp_get_post_terms' ) ) { $terms = wp_get_post_terms( $product_id, 'product_tag', array( 'fields' => 'names' ) ); if ( is_array( $terms ) ) { $names = array_values( array_filter( array_map( 'strval', $terms ) ) ); } } $store->stageTracked( $product_id, 'tags', (string) wp_json_encode( $names ), array_merge( $origin, array( 'value_format' => 'json' ) ) ); } if ( ! empty( $result['faq'] ) && is_array( $result['faq'] ) ) { $current_faq = get_post_meta( $product_id, '_aipt_faq_data', true ); $store->stageTracked( $product_id, 'faq', is_string( $current_faq ) ? $current_faq : '', array_merge( $origin, array( 'value_format' => 'json' ) ) ); } if ( ! empty( $result['seo_meta'] ) && is_array( $result['seo_meta'] ) ) { $store->captureSeoMeta( $product_id, $result['seo_meta'], $origin ); } if ( ! empty( $result['image_alt'] ) && is_array( $result['image_alt'] ) ) { foreach ( $result['image_alt'] as $item ) { if ( ! is_array( $item ) ) { continue; } $attachment_id = isset( $item['attachment_id'] ) ? (int) $item['attachment_id'] : 0; if ( $attachment_id <= 0 ) { continue; } $current_alt = (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); $store->stageTracked( $product_id, 'image_alt', $current_alt, array_merge( $origin, array( 'value_format' => 'text', 'subject_id' => $attachment_id, ) ) ); } } } /** * "After" companion to handle_before_apply() — commits or rolls back every * snapshot staged for $product_id by the most recent handle_before_apply() * call, once the caller has confirmed whether the real field write landed. * * Fired by `aipt_after_content_apply` (single-product generator applies, * {@see \AIPT\Api\Rollback\ContentApplyDispatcher::after()}) and * `aipt_after_apply_result` (automation). Idempotent: a product_id with * nothing pending (never staged, or already finalized) is a silent no-op. * * @param mixed $product_id Product id whose staged snapshots to finalize. * @param mixed $success Whether the write succeeded. * @return void */ public static function handle_after_apply( $product_id, $success = false ): void { self::finalizeStaged( (int) $product_id, (bool) $success ); } /** * Capture the pre-write snapshot for a term-description write. * * Fired on `aipt_before_term_apply` ({@see \AIPT\Api\Rollback\ContentApplyDispatcher::beforeTerm()}), * BEFORE the term is mutated, so the captured value is the genuine * pre-write current description. Mirrors {@see handle_before_apply()}'s * shape for the term domain: the CURRENT live value is read here (never * trusted from the payload), and `$fields['term_description']` carries * the value ABOUT to be written (the generated_value half of the * before/after preview). * * @since 2.8.0 * @param mixed $fields Normalized term payload: term_id, taxonomy, * term_description, source, and optional * blueprint_id/blueprint_name/blueprint_revision/blueprint_builtin. * @return void */ public static function handle_before_term_apply( $fields ): void { if ( ! is_array( $fields ) ) { return; } $term_id = isset( $fields['term_id'] ) ? (int) $fields['term_id'] : 0; $taxonomy = isset( $fields['taxonomy'] ) ? (string) $fields['taxonomy'] : ''; if ( $term_id <= 0 || '' === $taxonomy || ! isset( $fields['term_description'] ) ) { return; } $term = function_exists( 'get_term' ) ? get_term( $term_id, $taxonomy ) : null; if ( ! $term || ( function_exists( 'is_wp_error' ) && is_wp_error( $term ) ) ) { return; } $store = new self(); $source = self::normalizeSource( isset( $fields['source'] ) ? (string) $fields['source'] : 'taxonomy' ); $applied_by = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0; $origin = array( 'source' => $source, 'applied_by' => $applied_by, 'subject_type' => 'term', 'subject_id' => $term_id, 'taxonomy' => $taxonomy, 'value_format' => 'html', ); if ( isset( $fields['blueprint_id'] ) || isset( $fields['blueprint_name'] ) || isset( $fields['blueprint_revision'] ) || isset( $fields['blueprint_builtin'] ) ) { $origin['blueprint_id'] = isset( $fields['blueprint_id'] ) ? (int) $fields['blueprint_id'] : 0; $origin['blueprint_name'] = isset( $fields['blueprint_name'] ) ? (string) $fields['blueprint_name'] : ''; $origin['blueprint_revision'] = isset( $fields['blueprint_revision'] ) ? (int) $fields['blueprint_revision'] : 0; $origin['blueprint_builtin'] = ! empty( $fields['blueprint_builtin'] ); } $current_description = isset( $term->description ) ? (string) $term->description : ''; $store->stageTermTracked( $term_id, $taxonomy, $current_description, array_merge( $origin, self::generatedValueOpt( $fields['term_description'] ) ) ); } /** * "After" companion to handle_before_term_apply() — commits or rolls back * every snapshot staged for this exact (taxonomy, term_id) pair by the * most recent handle_before_term_apply() call. * * Fired by `aipt_after_term_apply` * ({@see \AIPT\Api\Rollback\ContentApplyDispatcher::afterTerm()}). * Idempotent: a subject with nothing pending (never staged, or already * finalized) is a silent no-op. * * @since 2.8.0 * @param mixed $term_id Term id whose staged snapshot to finalize. * @param mixed $taxonomy Taxonomy the term belongs to. * @param mixed $success Whether the write succeeded. * @return void */ public static function handle_after_term_apply( $term_id, $taxonomy = '', $success = false ): void { self::finalizeStagedTerm( (int) $term_id, (string) $taxonomy, (bool) $success ); } /** * Commit or roll back every snapshot this PHP process staged for one * (taxonomy, term_id) subject. * * @since 2.8.0 * @param int $term_id Term id. * @param string $taxonomy Taxonomy the term belongs to. * @param bool $success True commits (pending -> available); false deletes * the staged row (the write never happened). * @return void */ public static function finalizeStagedTerm( int $term_id, string $taxonomy, bool $success ): void { $key = self::termBucketKey( $term_id, $taxonomy ); if ( $term_id <= 0 || '' === $taxonomy || empty( self::$pendingStagedTermIds[ $key ] ) ) { return; } $entries = self::$pendingStagedTermIds[ $key ]; unset( self::$pendingStagedTermIds[ $key ] ); $store = new self(); foreach ( $entries as $entry ) { $id = (int) $entry['id']; if ( $success ) { $store->commit( $id ); } else { $store->rollback( $id ); } } } /** * Domain-qualified staging-buffer key for a term subject — never the bare * numeric term id, so a term can never share a bucket with an unrelated * product of the same numeric id, and a term in one taxonomy can never * share a bucket with a (legacy, pre-term-split) term of the same id in * another taxonomy. * * @since 2.8.0 * @param int $term_id Term id. * @param string $taxonomy Taxonomy the term belongs to. * @return string */ private static function termBucketKey( int $term_id, string $taxonomy ): string { return $taxonomy . ':' . $term_id; } /** * Commit or roll back every snapshot this PHP process staged for a product. * * All-or-nothing finalization: every staged row shares one outcome. Callers * that write SEVERAL fields with independent success/failure must use * {@see finalizeStagedByField()} instead, so a field whose write landed keeps * its history while a field whose write failed loses only ITS staged row. * * @param int $product_id Product id. * @param bool $success True commits (pending → available); false deletes * the staged rows (the write never happened). * @return void */ public static function finalizeStaged( int $product_id, bool $success ): void { if ( $product_id <= 0 || empty( self::$pendingStagedIds[ $product_id ] ) ) { return; } $entries = self::$pendingStagedIds[ $product_id ]; unset( self::$pendingStagedIds[ $product_id ] ); $store = new self(); foreach ( $entries as $entry ) { $id = (int) $entry['id']; if ( $success ) { $store->commit( $id ); } else { $store->rollback( $id ); } } } /** * Commit or roll back staged snapshots PER FIELD, driven by the actual * write outcome of each field. * * $field_results maps the snapshot field_type (title, description, * short_description, tags, faq, seo_meta_title, seo_meta_description, * image_alt) to EITHER a boolean write outcome (single-subject fields) OR * a per-subject outcomes map keyed by subject_id (multi-subject fields: * image_alt stages one row per attachment). A staged row is committed only * when its own outcome is present and truthy — for a map value, the row's * subject_id must be present and truthy in the map. Every other staged row * (missing key or falsy) is rolled back — a field whose write outcome is * unknown or failed must never be recorded as changed. This is the * field-level finalization the stage/commit/rollback protocol requires for * multi-field applies: a field that was written keeps its history even when * a sibling field's write fails, and vice versa. * * @param int $product_id Product id. * @param array> $field_results Per-field write * outcomes keyed by snapshot field_type; a map * value resolves per staged subject_id. * @return void */ public static function finalizeStagedByField( int $product_id, array $field_results ): void { if ( $product_id <= 0 || empty( self::$pendingStagedIds[ $product_id ] ) ) { return; } $entries = self::$pendingStagedIds[ $product_id ]; unset( self::$pendingStagedIds[ $product_id ] ); $store = new self(); foreach ( $entries as $entry ) { $id = (int) $entry['id']; $field_type = (string) $entry['field_type']; $outcome = $field_results[ $field_type ] ?? null; if ( is_array( $outcome ) ) { $subject_id = isset( $entry['subject_id'] ) ? (int) $entry['subject_id'] : 0; if ( ! empty( $outcome[ $subject_id ] ) ) { $store->commit( $id ); } else { $store->rollback( $id ); } } elseif ( ! empty( $outcome ) ) { $store->commit( $id ); } else { $store->rollback( $id ); } } } /** * Commit or roll back EVERY snapshot this PHP process staged, across all * products. * * The exception-path finalizer: when a request dies after staging, the * whole staged set shares one failed outcome. Request-level catch blocks * call this so no staged row is left pending for the stale-pending cron * reap while the process still knows the answer. * * @param bool $success True commits everything; false rolls everything back. * @return void */ public static function finalizeAllStaged( bool $success ): void { if ( ! empty( self::$pendingStagedIds ) ) { foreach ( array_keys( self::$pendingStagedIds ) as $product_id ) { self::finalizeStaged( (int) $product_id, $success ); } } if ( ! empty( self::$pendingStagedTermIds ) ) { foreach ( array_keys( self::$pendingStagedTermIds ) as $key ) { $parts = explode( ':', (string) $key, 2 ); $taxonomy = (string) ( $parts[0] ?? '' ); $term_id = isset( $parts[1] ) ? (int) $parts[1] : 0; self::finalizeStagedTerm( $term_id, $taxonomy, $success ); } } } /** * Stage a snapshot AND remember its id against $product_id so a later * finalizeStaged() call can commit or roll it back. * * Used exclusively by handle_before_apply()/captureSeoMeta() — the * do_action() hook boundary they run inside has no return channel of its * own to hand staged ids back to the caller. * * @param int $product_id Product id. * @param string $field_type Field type key. * @param string|null $snapshot_value Pre-write value to stage. * @param array $opts Same options as {@see stage()}. * @return int|null New row id, or null when nothing was staged. */ private function stageTracked( int $product_id, string $field_type, ?string $snapshot_value, array $opts = array() ): ?int { $id = $this->stage( $product_id, $field_type, $snapshot_value, $opts ); if ( null !== $id ) { self::$pendingStagedIds[ $product_id ][] = array( 'id' => $id, 'field_type' => $field_type, 'subject_id' => isset( $opts['subject_id'] ) ? (int) $opts['subject_id'] : null, ); } return $id; } /** * Stage a term-description snapshot (always field_type='term_description', * product_id=0) AND remember its id in the term-domain buffer, keyed by * {@see termBucketKey()} so a later {@see finalizeStagedTerm()} call * commits or rolls back exactly this term's row — never a different * term's, or an unrelated product's of the same numeric id. * * @since 2.8.0 * @param int $term_id Term id. * @param string $taxonomy Taxonomy the term belongs to. * @param string|null $snapshot_value Pre-write value to stage. * @param array $opts Same options as {@see stage()}; must carry * subject_type='term' and subject_id=$term_id. * @return int|null New row id, or null when nothing was staged. */ private function stageTermTracked( int $term_id, string $taxonomy, ?string $snapshot_value, array $opts = array() ): ?int { $id = $this->stage( 0, 'term_description', $snapshot_value, $opts ); if ( null !== $id ) { self::$pendingStagedTermIds[ self::termBucketKey( $term_id, $taxonomy ) ][] = array( 'id' => $id ); } return $id; } /** * Build the optional `generated_value` capture option for a text field. * * The apply payload is heterogeneous by contract: the automation * ResultProcessor and the Title generator pass the real value about to be * written, while {@see \AIPT\Api\Rollback\ContentApplyDispatcher} callers * that only need presence semantics pass `true` (see that class's docblock * — "the payload values here act purely as presence flags"). Recording a * boolean would persist "1" as the applied value and render a nonsense * before→after row preview, so only a genuine non-empty string is carried * through; every other shape simply leaves generated_value NULL, exactly as * before. * * @param mixed $value Raw payload value for the field about to change. * @return array A generated_value option, or an empty array. */ private static function generatedValueOpt( $value ): array { if ( ! is_string( $value ) || '' === $value ) { return array(); } return array( 'generated_value' => $value ); } /** * Capture the current SEO title/description before an apply overwrites them. * * @param int $product_id Product id. * @param array $seo_meta Incoming SEO fields (meta_title / meta_description). * @return void */ private function captureSeoMeta( int $product_id, array $seo_meta, array $origin ): void { if ( ! class_exists( SeoPluginDetector::class ) ) { return; } $requested_slug = isset( $origin['plugin_slug'] ) ? (string) $origin['plugin_slug'] : ''; $plugin_config = null; if ( '' !== $requested_slug ) { $meta_keys = SeoPluginDetector::get_meta_keys( $requested_slug ); if ( null !== $meta_keys ) { $plugin_config = array( 'plugin_slug' => $requested_slug, 'plugin_name' => $requested_slug, 'meta_keys' => $meta_keys, ); } } if ( null === $plugin_config ) { $plugin_config = SeoPluginDetector::detect(); } if ( null === $plugin_config || empty( $plugin_config['plugin_slug'] ) ) { return; } $plugin_slug = (string) $plugin_config['plugin_slug']; $info = SeoPluginDetector::get_seo_info( $product_id, $plugin_config, false ); if ( array_key_exists( 'meta_title', $seo_meta ) ) { $current = isset( $info['meta_title'] ) ? (string) $info['meta_title'] : ''; $this->stageTracked( $product_id, 'seo_meta_title', $current, array_merge( $origin, array( 'value_format' => 'text', 'plugin_slug' => $plugin_slug, ) ) ); } if ( array_key_exists( 'meta_description', $seo_meta ) ) { $current = isset( $info['meta_description'] ) ? (string) $info['meta_description'] : ''; $this->stageTracked( $product_id, 'seo_meta_description', $current, array_merge( $origin, array( 'value_format' => 'text', 'plugin_slug' => $plugin_slug, ) ) ); } } /** * Read the current live value for a canonical snapshot field type. * * @param int $product_id Product id. Ignored for field_type='term_description' (terms have no owning product). * @param string $field_type Canonical snapshot field type. * @param int|null $subject_id Attachment id for image_alt, or term id for term_description. * @param string|null $plugin_slug SEO plugin slug, or null/empty to detect the active plugin. * @param string $taxonomy Taxonomy slug, required for field_type='term_description'. * @return string|null Current value, or null when the field cannot be read. * @throws \RuntimeException When WordPress reports an explicit tag-read failure. */ public function readCurrentFieldValue( int $product_id, string $field_type, ?int $subject_id = null, ?string $plugin_slug = null, string $taxonomy = '' ): ?string { if ( 'term_description' === $field_type ) { if ( null === $subject_id || $subject_id <= 0 || '' === $taxonomy ) { return null; } $term = function_exists( 'get_term' ) ? get_term( $subject_id, $taxonomy ) : null; if ( ! $term || ( function_exists( 'is_wp_error' ) && is_wp_error( $term ) ) ) { return null; } return isset( $term->description ) ? (string) $term->description : ''; } if ( $product_id <= 0 ) { return null; } switch ( $field_type ) { case 'title': case 'slug': case 'description': case 'short_description': $product = function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : null; if ( ! $product ) { return null; } if ( 'title' === $field_type ) { return (string) $product->get_name(); } if ( 'slug' === $field_type ) { return (string) $product->get_slug(); } if ( 'description' === $field_type ) { return (string) $product->get_description(); } return (string) $product->get_short_description(); case 'tags': if ( ! function_exists( 'wp_get_post_terms' ) ) { return null; } $terms = wp_get_post_terms( $product_id, 'product_tag', array( 'fields' => 'names' ) ); if ( function_exists( 'is_wp_error' ) && is_wp_error( $terms ) ) { throw new \RuntimeException( 'Unable to read the current product tags.' ); } if ( ! is_array( $terms ) ) { return null; } $names = array_values( array_filter( array_map( 'strval', $terms ) ) ); return (string) wp_json_encode( $names ); case 'faq': $faq = get_post_meta( $product_id, '_aipt_faq_data', true ); return is_string( $faq ) ? $faq : ''; case 'seo_meta_title': case 'seo_meta_description': case 'seo_meta_focus_keyword': case 'seo_focus_keyword': if ( ! class_exists( SeoPluginDetector::class ) ) { return null; } if ( null === $plugin_slug ) { $plugin_config = SeoPluginDetector::detect(); if ( null === $plugin_config || empty( $plugin_config['plugin_slug'] ) ) { return null; } } elseif ( '' === $plugin_slug || 'standalone' === $plugin_slug ) { return null; } else { $meta_keys = SeoPluginDetector::get_meta_keys( $plugin_slug ); if ( null === $meta_keys ) { return null; } $plugin_config = array( 'plugin_slug' => $plugin_slug, 'plugin_name' => null, 'meta_keys' => $meta_keys, ); } $info = SeoPluginDetector::get_seo_info( $product_id, $plugin_config, false ); if ( ! is_array( $info ) ) { return null; } if ( in_array( $field_type, array( 'seo_meta_focus_keyword', 'seo_focus_keyword' ), true ) ) { $focus = $info['focus_keyword'] ?? ''; if ( is_array( $focus ) ) { $focus = implode( ', ', array_map( 'strval', $focus ) ); } return is_scalar( $focus ) ? (string) $focus : ''; } $key = 'seo_meta_title' === $field_type ? 'meta_title' : 'meta_description'; return isset( $info[ $key ] ) ? (string) $info[ $key ] : ''; case 'image_alt': if ( null === $subject_id || $subject_id <= 0 ) { return null; } return (string) get_post_meta( $subject_id, '_wp_attachment_image_alt', true ); default: return null; } } /** * Whether the Content History enable/disable toggle currently permits new * captures. Protected (not inlined into capture()) so Premium\Rollback\ * SnapshotStore's pre-restore capture can check it independently — a * disabled toggle and a genuine DB write failure both surface as * capture() returning null, but a restore caller must tell them apart: * one is an intentional skip that should let the restore continue, the * other is a fail-closed reason to abort it. * * @return bool */ protected function captureEnabled(): bool { return self::historyCaptureEnabled(); } /** * The Content History toggle, for a reader outside this class that must * tell "never written" apart from "History is off, so nothing could be * recorded" (the generator pages' "changed since its last run" line). * * @since 2.8.0 * @return bool */ public static function historyCaptureEnabled(): bool { return (bool) rest_sanitize_boolean( get_option( 'aipt_content_history_enabled', true ) ); } /** * Insert one pre-AI snapshot row. * * The first snapshot for a (product_id, field_type, subject_id) group is * pinned as the original (is_original = 1) and is never pruned. An empty * pre-AI value is skipped — there is nothing to restore to. * * @param int $product_id Product id. * @param string $field_type Field type key (e.g. description, tags). * @param string|null $snapshot_value Pre-AI value to restore to. * @param array $opts subject_id, value_format, plugin_slug, variant_index, generated_value. * @return int|null New row id, or null when nothing was captured. */ public function capture( int $product_id, string $field_type, ?string $snapshot_value, array $opts = array() ): ?int { return $this->insertRow( $product_id, $field_type, $snapshot_value, $opts, 'available', false ); } /** * Stage a pre-write snapshot as status='pending'. * * Identical contract to {@see capture()} except the row is invisible to * every read path (history(), list(), stack(), summary(), count(), * get_snapshot()) until a caller commits it. Pairs with {@see commit()} * (write succeeded) and {@see rollback()} (write failed) so a failed apply * can never leave a committed history entry behind, while the pre-write * read + is_original decision still happens at the same point in time * capture() always did — immediately before the write, not after — * keeping chronological ordering correct under concurrent writers. * * @param int $product_id Product id. * @param string $field_type Field type key. * @param string|null $snapshot_value Pre-write value to stage. * @param array $opts Same options as {@see capture()}. * @return int|null New row id, or null when nothing was staged. */ public function stage( int $product_id, string $field_type, ?string $snapshot_value, array $opts = array() ): ?int { return $this->insertRow( $product_id, $field_type, $snapshot_value, $opts, 'pending', false ); } /** * Stage a pre-write snapshot as status='pending', IGNORING the Content * History enable/disable toggle. * * Reserved for the restore path, whose pre-restore capture is a SAFETY * mechanism (it is what keeps a restore undoable), not ordinary AI-history * tracking. A site that opted out of new capture must still get a reversible * restore — otherwise the restore confirmation's "the value it replaces is * kept as a new snapshot" promise would be false whenever the toggle is off. * Every other caller must use {@see stage()} and honor the toggle. * * @param int $product_id Product id. * @param string $field_type Field type key. * @param string|null $snapshot_value Pre-write value to stage. * @param array $opts Same options as {@see capture()}. * @return int|null New row id, or null when nothing was staged. */ protected function stageIgnoringToggle( int $product_id, string $field_type, ?string $snapshot_value, array $opts = array() ): ?int { return $this->insertRow( $product_id, $field_type, $snapshot_value, $opts, 'pending', true ); } /** * Commit a staged snapshot: pending → available. * * Call once the write it precedes is CONFIRMED to have landed. A no-op * (returns false) when the row is not pending — already committed, already * rolled back, or never existed — so a duplicate/late call can never * resurrect a deleted row. * * @param int $id Snapshot row id. * @return bool True when the row was pending and is now available. */ public function commit( int $id ): bool { if ( $id <= 0 ) { return false; } global $wpdb; $updated = $wpdb->update( self::table(), array( 'status' => 'available', 'updated_at' => current_time( 'mysql', true ), ), array( 'id' => $id, 'status' => 'pending', ), array( '%s', '%s' ), array( '%d', '%s' ) ); return false !== $updated && (int) $updated >= 1; } /** * Roll back a staged snapshot that must never be recorded because the * write it preceded failed. * * Deletes ONLY when the row is still pending — a row already committed to * 'available' (a genuine confirmed history entry) is structurally * impossible for this to remove, regardless of a stale/duplicate call. * * @param int $id Snapshot row id. * @return bool True when a pending row was deleted. */ public function rollback( int $id ): bool { if ( $id <= 0 ) { return false; } global $wpdb; $deleted = $wpdb->delete( self::table(), array( 'id' => $id, 'status' => 'pending', ), array( '%d', '%s' ) ); return false !== $deleted && (int) $deleted >= 1; } /** * Record that two freshly staged snapshot rows belong to the SAME apply * — currently only a title row and the companion slug row staged * alongside it in {@see handle_before_apply()}. Written on both rows so * either can resolve its sibling, even though only a title restore * reads it today — the Business-only restore writer that extends this * class reads this column, kept free of any reference to it here so * this file survives the free-build strip. * * @since 2.8.1 * @param int $from_id One staged row id. * @param int $to_id The other staged row id. * @return void */ public function linkSnapshots( int $from_id, int $to_id ): void { if ( $from_id <= 0 || $to_id <= 0 ) { return; } global $wpdb; $table = self::table(); $wpdb->update( $table, array( 'linked_snapshot_id' => $to_id ), array( 'id' => $from_id ), array( '%d' ), array( '%d' ) ); $wpdb->update( $table, array( 'linked_snapshot_id' => $from_id ), array( 'id' => $to_id ), array( '%d' ), array( '%d' ) ); } /** * Insert one pre-AI snapshot row at the given status. * * The first snapshot for a (product_id, field_type, subject_id) group is * pinned as the original (is_original = 1) and is never pruned. An empty * pre-AI value is skipped — there is nothing to restore to. The is_original decision * considers rows of EITHER status (pending or available): a still-pending * sibling capture from a concurrent apply already claimed the original slot * for its group, and that claim is not undone if its write later fails and * the row is rolled back — the NEXT capture for that group simply * re-claims it, matching the review requirement that a rolled-back capture * can never permanently occupy the original slot. * * @param int $product_id Product id. * @param string $field_type Field type key (e.g. description, tags). * @param string|null $snapshot_value Pre-AI value to restore to. * @param array $opts subject_id, value_format, plugin_slug, variant_index, generated_value. * @param string $status 'available' (capture()) or 'pending' (stage()). * @return int|null New row id, or null when nothing was captured. */ private function insertRow( int $product_id, string $field_type, ?string $snapshot_value, array $opts, string $status, bool $ignore_capture_toggle = false ): ?int { $subject_type = isset( $opts['subject_type'] ) ? (string) $opts['subject_type'] : 'product'; $is_term = 'term' === $subject_type; if ( '' === $field_type ) { return null; } if ( $is_term ) { if ( ! isset( $opts['subject_id'] ) || (int) $opts['subject_id'] <= 0 ) { return null; } } elseif ( $product_id <= 0 ) { return null; } if ( null === $snapshot_value ) { return null; } if ( ! $ignore_capture_toggle && ! $this->captureEnabled() ) { return null; } global $wpdb; $subject_id = isset( $opts['subject_id'] ) ? (int) $opts['subject_id'] : null; $original_plugin_slug = isset( $opts['plugin_slug'] ) ? (string) $opts['plugin_slug'] : ''; $lock_name = 'aipt_snap_orig_' . sha1( $product_id . ':' . $field_type . ':' . ( $subject_id ?? 0 ) . ':' . $original_plugin_slug ); $lock_acquired = '1' === (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, %d)', $lock_name, 2 ) ); try { $is_original = $this->hasOriginal( $product_id, $field_type, $subject_id, $original_plugin_slug ) ? 0 : 1; $now = current_time( 'mysql', true ); $data = array( 'product_id' => $product_id, 'field_type' => $field_type, 'snapshot_value' => $snapshot_value, 'value_format' => isset( $opts['value_format'] ) ? (string) $opts['value_format'] : 'text', 'status' => $status, 'is_original' => $is_original, 'plugin_slug' => isset( $opts['plugin_slug'] ) ? (string) $opts['plugin_slug'] : '', 'variant_index' => isset( $opts['variant_index'] ) ? (int) $opts['variant_index'] : 0, 'source' => self::normalizeSource( isset( $opts['source'] ) ? (string) $opts['source'] : '' ), 'applied_by' => isset( $opts['applied_by'] ) ? max( 0, (int) $opts['applied_by'] ) : 0, '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, 'created_at' => $now, 'updated_at' => $now, ); $formats = array( '%d', '%s', '%s', '%s', '%s', '%d', '%s', '%d', '%s', '%d', '%d', '%s', '%d', '%d', '%s', '%s' ); if ( null !== $subject_id ) { $data['subject_id'] = $subject_id; $formats[] = '%d'; } if ( $is_term ) { $data['subject_type'] = 'term'; $data['taxonomy'] = isset( $opts['taxonomy'] ) ? (string) $opts['taxonomy'] : ''; $formats[] = '%s'; $formats[] = '%s'; } if ( isset( $opts['generated_value'] ) && is_string( $opts['generated_value'] ) ) { $data['generated_value'] = $opts['generated_value']; $formats[] = '%s'; } $inserted = $wpdb->insert( self::table(), $data, $formats ); } finally { if ( $lock_acquired ) { $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock_name ) ); } } if ( false === $inserted ) { return null; } return $wpdb->insert_id ? (int) $wpdb->insert_id : null; } /** * Whether a pinned original already exists for this group. * * The group identity includes plugin_slug when one is supplied (SEO fields): * a Yoast original must not suppress a RankMath original, so each SEO plugin * pins its own first-captured value. Non-SEO fields pass an empty slug and * keep the original (product_id, field_type, subject_id) identity. * * @param int $product_id Product id. * @param string $field_type Field type. * @param int|null $subject_id Subject id (NULL for product-level fields). * @param string $plugin_slug SEO plugin slug ('' for non-SEO fields). * @return bool */ private function hasOriginal( int $product_id, string $field_type, ?int $subject_id, string $plugin_slug = '' ): bool { global $wpdb; $table = self::table(); $plugin_sql = '' !== $plugin_slug ? ' AND plugin_slug = %s' : ''; $plugin_args = '' !== $plugin_slug ? array( $plugin_slug ) : array(); if ( null === $subject_id ) { $existing = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE product_id = %d AND field_type = %s AND subject_id IS NULL AND is_original = 1{$plugin_sql} LIMIT 1", array_merge( array( $product_id, $field_type ), $plugin_args ) ) ); } else { $existing = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE product_id = %d AND field_type = %s AND subject_id = %d AND is_original = 1{$plugin_sql} LIMIT 1", array_merge( array( $product_id, $field_type, $subject_id ), $plugin_args ) ) ); } return null !== $existing; } /** * Cron-batched pruning: enforce the per-group cap of {@see CAP} non-original * snapshots, newest-first, NEVER deleting a pinned original. * * Scans the non-original rows in KEYSET-ADVANCING windows ordered by * (product_id, field_type, subject_id), so every group is eventually reached. * The pre-fix scan read a single global LIMIT window with no cursor: once the * leading groups were already at/under CAP the window never changed, and any * over-cap group beyond that window was NEVER pruned. Advancing the cursor * across windows fixes that — a run keeps scanning past already-capped groups * until it either reaches a delete budget ({@see MAX_DELETIONS_PER_TICK}) or * exhausts the table. * * MUST only ever be reached from the cron callback — never from an apply. * * @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_pid = 0; $cursor_ft = ''; $cursor_sid = -1; while ( count( $delete_ids ) < $budget ) { $rows = $this->readPruneWindow( $cursor_pid, $cursor_ft, $cursor_sid, $window ); if ( empty( $rows ) ) { break; } $groups = array(); foreach ( $rows as $row ) { $sid = ( isset( $row->subject_id ) && null !== $row->subject_id ) ? (int) $row->subject_id : 0; $key = (int) $row->product_id . '|' . (string) $row->field_type . '|' . $sid; $groups[ $key ][] = $row; } $group_keys = array_keys( $groups ); $full = count( $rows ) >= $window; $defer_last = $full && count( $group_keys ) > 1; $process = $defer_last ? array_slice( $group_keys, 0, -1 ) : $group_keys; foreach ( $process as $key ) { $group_rows = $groups[ $key ]; usort( $group_rows, static function ( $a, $b ) { $cmp = strcmp( (string) $b->created_at, (string) $a->created_at ); if ( 0 !== $cmp ) { return $cmp; } return (int) $b->id <=> (int) $a->id; } ); $cap = self::retentionCap(); if ( count( $group_rows ) > $cap ) { foreach ( array_slice( $group_rows, $cap ) as $row ) { $delete_ids[] = (int) $row->id; if ( count( $delete_ids ) >= $budget ) { break; } } } if ( count( $delete_ids ) >= $budget ) { break; } } if ( ! $full ) { break; } $advance_key = end( $process ); if ( false === $advance_key ) { break; } list( $cursor_pid, $cursor_ft, $cursor_sid ) = self::parseGroupKey( (string) $advance_key ); } if ( empty( $delete_ids ) ) { return 0; } $ids_in = implode( ',', array_map( 'intval', $delete_ids ) ); $deleted = $wpdb->query( "DELETE FROM {$table} WHERE is_original = 0 AND status != 'pending' AND id IN ($ids_in)" ); return is_numeric( $deleted ) ? (int) $deleted : 0; } /** * Read one keyset window of non-original rows STRICTLY AFTER the group cursor * (product_id, field_type, subject_id), newest-first within each group. * NULL subject_id is normalised to 0 for a total order. * * @param int $cursor_pid Cursor product_id. * @param string $cursor_ft Cursor field_type. * @param int $cursor_sid Cursor subject_id (0 for the NULL group; -1 seeds). * @param int $window Max rows to read. * @return array Ordered rows for this window. */ private function readPruneWindow( int $cursor_pid, string $cursor_ft, int $cursor_sid, int $window ): array { global $wpdb; $table = self::table(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, product_id, field_type, subject_id, created_at FROM {$table} WHERE is_original = 0 AND status != 'pending' AND ( product_id > %d OR ( product_id = %d AND field_type > %s ) OR ( product_id = %d AND field_type = %s AND COALESCE(subject_id, 0) > %d ) ) ORDER BY product_id ASC, field_type ASC, COALESCE(subject_id, 0) ASC, created_at DESC, id DESC LIMIT %d", $cursor_pid, $cursor_pid, $cursor_ft, $cursor_pid, $cursor_ft, $cursor_sid, $window ) ); return is_array( $rows ) ? $rows : array(); } /** * Split a "product_id|field_type|subject_id" group key back into its parts. * field_type never contains a pipe (it is a fixed field-type slug), so an * explode is exact. * * @param string $key Group key. * @return array{0:int,1:string,2:int} [ product_id, field_type, subject_id ]. */ private static function parseGroupKey( string $key ): array { $parts = explode( '|', $key ); return array( isset( $parts[0] ) ? (int) $parts[0] : 0, isset( $parts[1] ) ? (string) $parts[1] : '', isset( $parts[2] ) ? (int) $parts[2] : 0, ); } /** * Rows a single prune window reads. Isolated behind a method so tests can * shrink the window and exercise the multi-window keyset advance without * seeding {@see PRUNE_READ_LIMIT} rows. * * @return int */ protected function pruneReadLimit(): int { return self::PRUNE_READ_LIMIT; } /** * Rows a single prune tick may delete. Isolated behind a method so tests can * shrink the budget and exercise the multi-tick "eventually prunes every * group" guarantee without seeding {@see MAX_DELETIONS_PER_TICK} rows. * * @return int */ protected function pruneDeletionBudget(): int { return self::MAX_DELETIONS_PER_TICK; } /** * Age (seconds) after which a still-pending staged snapshot is considered * abandoned. A pending row is staged immediately before a write and * committed/rolled back immediately after — a row still pending beyond this * window means the PHP process died, timed out, or fatal'd between staging * and finalization, and its owning apply never landed. * * @var int */ public const STALE_PENDING_AGE_SECONDS = 900; /** * Delete pending snapshots abandoned by a crashed/timed-out apply process. * * A pending row is invisible to every read path, but while it lives it still * participates in the is_original decision ({@see hasOriginal()} considers * rows of EITHER status) — an abandoned pending row that claimed * is_original=1 would permanently block the NEXT genuine capture for that * group from pinning the original slot. Reaping stale pending rows frees * the slot so the next capture re-claims it. This runs ONLY from the cron * callback ({@see cron_callback()}), never inline in an apply request. * * MUST only ever be reached from the cron callback — never from an apply. * * @return int Number of stale pending rows deleted. */ public function reapStalePending(): int { global $wpdb; $table = self::table(); $cutoff = gmdate( 'Y-m-d H:i:s', time() - self::STALE_PENDING_AGE_SECONDS ); $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE status = 'pending' AND created_at < %s LIMIT %d", $cutoff, self::MAX_DELETIONS_PER_TICK ) ); return is_numeric( $deleted ) ? (int) $deleted : 0; } /** * List the captured snapshots for a product, grouped-friendly and newest-first * within each field. * * Powers the item-13 rollback history panel for every plan. Returns a view-model * per row (NEVER the full stored value): a bounded plain-text preview plus the * metadata the UI needs to group + label rows and decide whether a row is * restorable. Restore routing itself always re-reads the canonical row in * {@see restore()} — this list is display-only. * * @param int $product_id Product id. * @return array> Snapshot view-models. */ public function history( int $product_id ): array { if ( $product_id <= 0 ) { return array(); } global $wpdb; $table = self::table(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, field_type, subject_id, snapshot_value, generated_value, value_format, is_original, plugin_slug, variant_index, source, applied_by, blueprint_id, blueprint_name, blueprint_revision, blueprint_builtin, created_at FROM {$table} WHERE product_id = %d AND status != 'pending' ORDER BY field_type ASC, is_original DESC, created_at DESC, id DESC", $product_id ), ARRAY_A ); if ( empty( $rows ) || ! is_array( $rows ) ) { return array(); } return array_map( function ( array $row ): array { return $this->mapRow( $row, false ); }, $rows ); } /** * List snapshots across products using the timeline keyset. * * Conflict status is structural on this read surface: rows do not contain a * live product token, so each row reports has_conflict=false and the optional * has_conflict filter is intentionally not applied server-side. * * @param array $filters Exact and date-range filters. * @param array|null $cursor Last-seen created_at and id. * @param int $limit Requested page size. * @return array> */ public function list( array $filters, ?array $cursor, int $limit ): array { global $wpdb; $table = self::table(); $limit = $limit > 0 ? min( 101, $limit ) : 25; $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 id, product_id, field_type, subject_id, subject_type, taxonomy, snapshot_value, generated_value, value_format, is_original, plugin_slug, variant_index, source, applied_by, blueprint_id, blueprint_name, blueprint_revision, blueprint_builtin, created_at FROM {$table}{$where_sql} ORDER BY created_at DESC, id DESC LIMIT {$limit}", ARRAY_A ); if ( empty( $rows ) || ! is_array( $rows ) ) { return array(); } return array_map( function ( array $row ): array { return $this->mapRow( $row, true ); }, $rows ); } /** * Count matching rows for the supplied filters without pagination. * * @param array $filters Exact and date-range 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}" ); } /** * Aggregate the history summary for the supplied filters. * * The conflict count is structural and remains zero until snapshots persist a * comparable live-value token. Restorable counts include empty-string values. * `products_touched` counts PRODUCT rows only — a term row's product_id is * always 0 (terms have no owning product) and must never be counted as a * phantom "product #0". * * @param array $filters Exact and date-range filters. * @return array */ public function summary( array $filters ): array { global $wpdb; $table = self::table(); $where = $this->buildListWhere( $filters ); $boundaries = UtcTimestamp::siteDayStartsUtc( (int) current_time( 'timestamp', true ), wp_timezone_string() ); $today = $boundaries['today']; $week_start = $boundaries['week']; $not_restorable_seo = "( field_type IN ( 'seo_meta_title', 'seo_meta_description' ) AND ( plugin_slug = '' OR plugin_slug = 'standalone' ) )"; $where_sql = empty( $where ) ? '' : ' WHERE ' . implode( ' AND ', $where ); $today_predicate = $wpdb->prepare( 'created_at >= %s', $today ); $week_predicate = $wpdb->prepare( 'created_at >= %s', $week_start ); $row = $wpdb->get_row( "SELECT SUM( CASE WHEN {$today_predicate} THEN 1 ELSE 0 END ) AS today_count, SUM( CASE WHEN {$week_predicate} THEN 1 ELSE 0 END ) AS week_count, COUNT( DISTINCT CASE WHEN subject_type = 'term' THEN NULL ELSE product_id END ) AS products_touched, SUM( CASE WHEN snapshot_value IS NOT NULL AND NOT {$not_restorable_seo} THEN 1 ELSE 0 END ) AS restorable_count FROM {$table}{$where_sql}", ARRAY_A ); $row = is_array( $row ) ? $row : array(); return array( 'today' => (int) ( $row['today_count'] ?? 0 ), 'this_week' => (int) ( $row['week_count'] ?? 0 ), 'products_touched' => (int) ( $row['products_touched'] ?? 0 ), 'restorable_count' => (int) ( $row['restorable_count'] ?? 0 ), 'conflict_count' => 0, ); } /** * Return the ten newest intermediate snapshots plus the pinned original. * * @param int $product_id Product id. Ignored for a term subject (always 0 in the row anyway). * @param string $field_type Snapshot field type. * @param int|null $subject_id Optional attachment id, or the term id for a term subject. * @param string $taxonomy Taxonomy slug — non-empty selects the term-domain stack for $subject_id instead of the product-domain one. * @return array> */ public function stack( int $product_id, string $field_type, ?int $subject_id, string $taxonomy = '' ): array { if ( '' === $field_type ) { return array(); } $is_term = '' !== $taxonomy; if ( $is_term ) { if ( null === $subject_id || $subject_id <= 0 ) { return array(); } } elseif ( $product_id <= 0 ) { return array(); } global $wpdb; $table = self::table(); if ( $is_term ) { $base = $wpdb->prepare( "subject_type = 'term' AND taxonomy = %s AND field_type = %s AND subject_id = %d", $taxonomy, $field_type, $subject_id ); } else { $subject = null === $subject_id ? 'subject_id IS NULL' : $wpdb->prepare( 'subject_id = %d', $subject_id ); $base = $wpdb->prepare( 'product_id = %d AND field_type = %s', $product_id, $field_type ) . ' AND ' . $subject; } $recent = $wpdb->get_results( "SELECT id, product_id, field_type, subject_id, subject_type, taxonomy, snapshot_value, generated_value, value_format, is_original, plugin_slug, variant_index, source, applied_by, blueprint_id, blueprint_name, blueprint_revision, blueprint_builtin, created_at FROM {$table} WHERE {$base} AND is_original = 0 AND status != 'pending' ORDER BY created_at DESC, id DESC LIMIT 10", ARRAY_A ); $original = $wpdb->get_results( "SELECT id, product_id, field_type, subject_id, subject_type, taxonomy, snapshot_value, generated_value, value_format, is_original, plugin_slug, variant_index, source, applied_by, blueprint_id, blueprint_name, blueprint_revision, blueprint_builtin, created_at FROM {$table} WHERE {$base} AND is_original = 1 AND status != 'pending' ORDER BY created_at ASC, id ASC LIMIT 1", ARRAY_A ); $rows = array_merge( is_array( $recent ) ? $recent : array(), is_array( $original ) ? $original : array() ); return array_map( function ( array $row ): array { return $this->mapRow( $row, true, true ); }, $rows ); } /** * Read the minimal routing metadata for a single snapshot. * * Used by the premium restore controller for authorization and conflict checks. * * @param int $snapshot_id Snapshot row id. * @return array|null { product_id, field_type, subject_id, restorable } or null when absent. */ public function get_snapshot( int $snapshot_id ): ?array { if ( $snapshot_id <= 0 ) { return null; } global $wpdb; $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT id, product_id, field_type, subject_id, subject_type, taxonomy, snapshot_value, plugin_slug FROM {$table} WHERE id = %d AND status != 'pending'", $snapshot_id ), ARRAY_A ); if ( ! is_array( $row ) ) { return null; } $field_type = isset( $row['field_type'] ) ? (string) $row['field_type'] : ''; $plugin_slug = isset( $row['plugin_slug'] ) ? (string) $row['plugin_slug'] : ''; $restorable = array_key_exists( 'snapshot_value', $row ) && null !== $row['snapshot_value']; if ( $restorable && in_array( $field_type, array( 'seo_meta_title', 'seo_meta_description' ), true ) && ( '' === $plugin_slug || 'standalone' === $plugin_slug ) ) { $restorable = false; } return array( 'product_id' => isset( $row['product_id'] ) ? (int) $row['product_id'] : 0, 'field_type' => $field_type, 'subject_id' => ( isset( $row['subject_id'] ) && null !== $row['subject_id'] ) ? (int) $row['subject_id'] : null, 'subject_type' => isset( $row['subject_type'] ) ? (string) $row['subject_type'] : 'product', 'taxonomy' => isset( $row['taxonomy'] ) ? (string) $row['taxonomy'] : '', 'restorable' => $restorable, ); } /** * 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 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'] ), ); } /** * Build a short, safe plain-text preview of a snapshot value for the UI list. * * Strips HTML and collapses whitespace so an HTML description renders as a * compact, escapable one-liner, and reads a `json` value (tags, FAQ) as the * text it holds rather than its JSON syntax. Never returns the full value. * * @param string $value Raw stored value (may be HTML or a JSON blob). * @param string $format The row's `value_format`: 'text' or 'json'. * @param string $field_type The row's field type. Tags and FAQ are JSON * lists whatever their `value_format` says: * older rows stored an empty tag list as text. * @return string Bounded plain-text preview. */ private function buildPreview( string $value, string $format = 'text', string $field_type = '' ): string { if ( '' === $value ) { return ''; } if ( 'json' === $format || in_array( $field_type, array( 'tags', 'faq' ), true ) ) { $value = $this->jsonPreviewText( $value ); } $text = function_exists( 'wp_strip_all_tags' ) ? (string) wp_strip_all_tags( $value ) : (string) preg_replace( '/<[^>]*>/', '', $value ); $text = trim( (string) preg_replace( '/\s+/', ' ', $text ) ); $limit = 160; if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' ) ) { return mb_strlen( $text ) > $limit ? mb_substr( $text, 0, $limit ) . '…' : $text; } return strlen( $text ) > $limit ? substr( $text, 0, $limit ) . '…' : $text; } /** * The words a `json` value holds: an FAQ's questions joined with " · ", * a tag list's names joined with commas, nothing for an empty list. * History lists showed the raw JSON (`[{"question":...`), which reads as * corrupted data. A value that is not JSON, or a shape this does not * know, comes back unchanged rather than hidden. * * @param string $value Stored JSON value. * @return string Plain text. */ private function jsonPreviewText( string $value ): string { $decoded = json_decode( $value, true ); if ( ! is_array( $decoded ) || ( array() !== $decoded && array_keys( $decoded ) !== range( 0, count( $decoded ) - 1 ) ) ) { return $value; } $parts = array(); $is_faq = false; foreach ( $decoded as $item ) { if ( is_array( $item ) && isset( $item['question'] ) && is_string( $item['question'] ) ) { $is_faq = true; $parts[] = trim( $item['question'] ); } elseif ( is_array( $item ) && isset( $item['name'] ) && is_string( $item['name'] ) ) { $parts[] = trim( $item['name'] ); } elseif ( is_string( $item ) || is_int( $item ) || is_float( $item ) ) { $parts[] = trim( (string) $item ); } } $parts = array_values( array_filter( $parts, static function ( string $part ): bool { return '' !== $part; } ) ); if ( empty( $parts ) && ! empty( $decoded ) ) { return $value; } return implode( $is_faq ? ' · ' : ', ', $parts ); } /** * @param array $filters Read filters. * @return array */ private function buildListWhere( array $filters ): array { global $wpdb; $where = array(); $where[] = "status != 'pending'"; $visibility = \AIPT\Core\ContentBank\ProductVisibilityScope::whereFragment( 'product_id' ); if ( null !== $visibility ) { $where[] = current_user_can( 'manage_product_terms' ) ? "( {$visibility} OR subject_type = 'term' )" : $visibility; } if ( ! empty( $filters['source'] ) ) { $where[] = $wpdb->prepare( 'source = %s', (string) $filters['source'] ); } if ( ! empty( $filters['field_type'] ) ) { $where[] = $wpdb->prepare( 'field_type = %s', (string) $filters['field_type'] ); } if ( ! empty( $filters['product_id'] ) ) { $where[] = $wpdb->prepare( 'product_id = %d', (int) $filters['product_id'] ); } if ( ! empty( $filters['term_id'] ) ) { $where[] = $wpdb->prepare( "subject_type = 'term' AND subject_id = %d", (int) $filters['term_id'] ); if ( ! empty( $filters['taxonomy'] ) ) { $where[] = $wpdb->prepare( 'taxonomy = %s', (string) $filters['taxonomy'] ); } } if ( 'manual' === ( $filters['actor'] ?? '' ) ) { $where[] = 'applied_by > 0'; } elseif ( 'automation' === ( $filters['actor'] ?? '' ) ) { $where[] = 'applied_by = 0'; } if ( ! empty( $filters['date_from'] ) ) { $where[] = $wpdb->prepare( 'created_at >= %s', (string) $filters['date_from'] ); } if ( ! empty( $filters['date_to'] ) ) { $where[] = $wpdb->prepare( 'created_at <= %s', (string) $filters['date_to'] ); } if ( ! empty( $filters['status'] ) ) { $where[] = $wpdb->prepare( 'status = %s', (string) $filters['status'] ); } if ( ! empty( $filters['search'] ) ) { $where[] = $wpdb->prepare( 'snapshot_value LIKE %s', '%' . $wpdb->esc_like( (string) $filters['search'] ) . '%' ); } return $where; } /** * @param array $row Database row. * @param bool $include_product_id Include the plugin-wide dimension. * @param bool $include_value Include the full, untruncated captured * value alongside the bounded preview. Only * the single-stack read passes true — the * plugin-wide list stays preview-only so its * payload does not carry every full-length * description on every page. * @return array */ private function mapRow( array $row, bool $include_product_id, bool $include_value = false ): array { $snapshot_value = array_key_exists( 'snapshot_value', $row ) ? $row['snapshot_value'] : null; $field_type = isset( $row['field_type'] ) ? (string) $row['field_type'] : ''; $plugin_slug = isset( $row['plugin_slug'] ) ? (string) $row['plugin_slug'] : ''; $restorable = null !== $snapshot_value; if ( $restorable && in_array( $field_type, array( 'seo_meta_title', 'seo_meta_description' ), true ) && ( '' === $plugin_slug || 'standalone' === $plugin_slug ) ) { $restorable = false; } $generated_value = (string) ( $row['generated_value'] ?? '' ); $preview_source = ( null !== $snapshot_value ) ? (string) $snapshot_value : $generated_value; $subject_type = isset( $row['subject_type'] ) ? (string) $row['subject_type'] : 'product'; $value_format = isset( $row['value_format'] ) ? (string) $row['value_format'] : 'text'; $mapped = array( 'id' => isset( $row['id'] ) ? (int) $row['id'] : 0, 'field_type' => isset( $row['field_type'] ) ? (string) $row['field_type'] : '', 'subject_id' => ( isset( $row['subject_id'] ) && null !== $row['subject_id'] ) ? (int) $row['subject_id'] : null, 'subject_type' => $subject_type, 'value_format' => $value_format, 'is_original' => 1 === (int) ( $row['is_original'] ?? 0 ), 'plugin_slug' => isset( $row['plugin_slug'] ) ? (string) $row['plugin_slug'] : '', 'source' => isset( $row['source'] ) ? (string) $row['source'] : '', 'applied_by' => isset( $row['applied_by'] ) ? (int) $row['applied_by'] : 0, 'created_at' => isset( $row['created_at'] ) ? (string) $row['created_at'] : '', 'restorable' => $restorable, 'has_conflict' => false, 'preview' => $this->buildPreview( $preview_source, $value_format, $field_type ), ) + $this->blueprintReadShape( $row ); if ( 'term' === $subject_type ) { $mapped['taxonomy'] = isset( $row['taxonomy'] ) ? (string) $row['taxonomy'] : ''; } if ( '' !== $generated_value && null !== $snapshot_value ) { $mapped['after_preview'] = $this->buildPreview( $generated_value, $value_format, $field_type ); } if ( $include_product_id ) { $mapped['product_id'] = isset( $row['product_id'] ) ? (int) $row['product_id'] : 0; } if ( $include_value ) { $mapped['value'] = $preview_source; } return $mapped; } /** * Normalize a capture origin to the canonical source vocabulary. * * @param string $source Candidate source. * @return string Canonical source or an empty value for migrated/unknown rows. */ private static function normalizeSource( string $source ): string { $canonical = array( 'description', 'title', 'faq', 'seo_meta', 'image_alt', 'tags', 'automation', 'product_editor', 'restore', 'taxonomy', 'csv_import' ); return in_array( $source, $canonical, true ) ? $source : ''; } /** * Newest committed (non-pending, non-restore-sourced) snapshot row per * (product_id, field_type), across many products and field types at * once — the batched read behind the Blueprint check's provenance * column (@since 2.8.0). * * A restore write is excluded because it only ever copies an EARLIER * value back onto the live field; it never represents new authorship * and would otherwise mask the real last writer. One SQL pass orders * every candidate row newest-first within its (product_id, field_type) * group (the `product_field_created` index supports the product_id + * field_type equality and the created_at ordering); the first row this * method sees per group is kept and every later one for that same * group is discarded, mirroring {@see readPruneWindow()}'s own * group-after-order approach instead of a second query per group. * * @since 2.8.0 * @param int[] $product_ids Product ids to read (deduped by the caller). * @param string[] $field_types Canonical snapshot field_type values to read. * @return array * Keyed by "{product_id}:{field_type}"; a group with no * qualifying row is simply absent from the result. */ public function newestCommittedFieldRows( array $product_ids, array $field_types ): array { if ( empty( $product_ids ) || empty( $field_types ) ) { return array(); } global $wpdb; $table = self::table(); $id_list = array_map( 'intval', $product_ids ); $field_list = array_map( 'strval', $field_types ); $id_placeholders = implode( ',', array_fill( 0, count( $id_list ), '%d' ) ); $field_placeholders = implode( ',', array_fill( 0, count( $field_list ), '%s' ) ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT product_id, field_type, blueprint_id, blueprint_name, blueprint_revision, blueprint_builtin, created_at, id FROM {$table} WHERE status != 'pending' AND source != 'restore' AND product_id IN ({$id_placeholders}) AND field_type IN ({$field_placeholders}) ORDER BY product_id ASC, field_type ASC, created_at DESC, id DESC", array_merge( $id_list, $field_list ) ), ARRAY_A ); $newest = array(); foreach ( (array) $rows as $row ) { if ( ! is_array( $row ) ) { continue; } $key = $row['product_id'] . ':' . $row['field_type']; if ( isset( $newest[ $key ] ) ) { continue; } $newest[ $key ] = array( 'blueprintId' => (int) ( $row['blueprint_id'] ?? 0 ), 'blueprintName' => (string) ( $row['blueprint_name'] ?? '' ), 'blueprintRevision' => (int) ( $row['blueprint_revision'] ?? 0 ), 'blueprintBuiltin' => ! empty( $row['blueprint_builtin'] ), ); } return $newest; } /** * The highest Blueprint revision recorded on a committed (non-pending, * non-restore-sourced) History row for each of the given Blueprint ids — * the batched read behind a generator's "changed since its last run" * line, so a store with hundreds of products never costs more than one * query regardless of how many Blueprints the current page's selection * touches. * * One SQL pass aggregates `MAX(blueprint_revision)` per `blueprint_id` * rather than resolving each Blueprint id with its own query, mirroring * {@see newestCommittedFieldRows()}'s own batched-read shape. A * Blueprint id with no qualifying row (never written, or only ever * restored to) is simply absent from the result — `blueprint_revision` * is stored `0` by default (see {@see insertRow()}), which is excluded * here the same way {@see blueprintReadShape()} treats it as "no * revision recorded" rather than a fabricated version 0. * * @since 2.8.0 * @param int[] $blueprint_ids Blueprint ids to read; deduped and * filtered to positive ints here, so the * caller can pass a raw list straight * through. * @return array Highest written revision per blueprint id. */ public function highestWrittenRevisions( array $blueprint_ids ): array { $blueprint_ids = array_values( array_unique( array_map( 'intval', array_filter( $blueprint_ids, static function ( $id ): bool { return (int) $id > 0; } ) ) ) ); if ( empty( $blueprint_ids ) ) { return array(); } global $wpdb; $table = self::table(); $placeholders = implode( ',', array_fill( 0, count( $blueprint_ids ), '%d' ) ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT blueprint_id, MAX(blueprint_revision) AS max_revision FROM {$table} WHERE status != 'pending' AND source != 'restore' AND blueprint_id IN ({$placeholders}) GROUP BY blueprint_id HAVING MAX(blueprint_revision) > 0", $blueprint_ids ), ARRAY_A ); $revisions = array(); foreach ( (array) $rows as $row ) { if ( ! is_array( $row ) ) { continue; } $blueprint_id = (int) ( $row['blueprint_id'] ?? 0 ); if ( $blueprint_id <= 0 ) { continue; } $revisions[ $blueprint_id ] = (int) ( $row['max_revision'] ?? 0 ); } return $revisions; } /** * Fully-qualified snapshot table name for reads and premium restore writes. * * @return string */ protected static function table(): string { global $wpdb; return $wpdb->prefix . 'aipt_content_snapshots'; } }