self::CHANGE_TYPE_SEO_TITLE, '_abds_seo_description' => self::CHANGE_TYPE_META_DESCRIPTION, '_abds_seo_focus_keyword' => self::CHANGE_TYPE_FOCUS_KEYWORD, ); /** * Pre-write snapshot of a tracked meta key's value, keyed by * "{post_id}:{meta_key}", captured by capture_before_update() and * consumed by log_update() once WordPress has committed the new value. * * @var array */ protected array $before_values = array(); /** * Registers this class's hooks with the plugin's hook loader. * * @param ABDS_SEO_Loader $loader Hook loader. */ public function register_hooks( ABDS_SEO_Loader $loader ): void { $loader->add_filter( 'update_post_metadata', $this, 'capture_before_update', 10, 3 ); $loader->add_action( 'updated_post_meta', $this, 'log_update', 10, 4 ); $loader->add_action( 'added_post_meta', $this, 'log_add', 10, 4 ); } /** * Snapshots a tracked meta key's current value immediately before * WordPress overwrites it (update_metadata() calls this filter first, * before touching the DB), so log_update() can log a real before/after * pair once the write has actually happened. Never intercepts the * update — always returns $check unmodified, and returns early without * reading anything for meta keys this class doesn't track. * * @param mixed $check Short-circuit value; passed through unchanged. * @param int $object_id Post ID. * @param string $meta_key Meta key about to be updated. * @return mixed $check, unmodified. */ public function capture_before_update( $check, $object_id, $meta_key ) { if ( ! isset( self::TRACKED_META_KEYS[ $meta_key ] ) ) { return $check; } $this->before_values[ $object_id . ':' . $meta_key ] = get_post_meta( $object_id, $meta_key, true ); return $check; } /** * Logs a change for a tracked meta key after WordPress has written a * new value over an already-existing meta row. * * @param int $meta_id Meta row ID (unused). * @param int $object_id Post ID. * @param string $meta_key Meta key that was updated. * @param mixed $meta_value New value. */ public function log_update( $meta_id, $object_id, $meta_key, $meta_value ): void { if ( ! isset( self::TRACKED_META_KEYS[ $meta_key ] ) ) { return; } $snapshot_key = $object_id . ':' . $meta_key; $before = $this->before_values[ $snapshot_key ] ?? ''; unset( $this->before_values[ $snapshot_key ] ); $change_type = $this->resolve_change_type( (int) $object_id, $meta_key, (string) $meta_value ); $this->insert_log_row( (int) $object_id, $change_type, (string) $before, (string) $meta_value ); } /** * Logs a change for a tracked meta key the first time it's ever set on * a post. WordPress routes to add_metadata() (and this action) rather * than the update path when no row exists yet for that key, so * before_value is always empty here. * * @param int $meta_id Meta row ID (unused). * @param int $object_id Post ID. * @param string $meta_key Meta key that was added. * @param mixed $meta_value New value. */ public function log_add( $meta_id, $object_id, $meta_key, $meta_value ): void { if ( ! isset( self::TRACKED_META_KEYS[ $meta_key ] ) ) { return; } // Gutenberg's save request sends every registered meta field, not // just the ones actually touched — untouched fields with no prior // row route through add_metadata() with an empty value, which // isn't a real change worth logging (before_value is always '' on // this path, so before === after here means "added nothing"). if ( '' === (string) $meta_value ) { return; } $change_type = $this->resolve_change_type( (int) $object_id, $meta_key, (string) $meta_value ); $this->insert_log_row( (int) $object_id, $change_type, '', (string) $meta_value ); } /** * The change_type for a write: the meta key's base type, prefixed with * AI_CHANGE_TYPE_PREFIX when this exact value was marked as an accepted * AI suggestion for this post (marker is consumed either way it's found). * * @param int $post_id Post ID. * @param string $meta_key Tracked meta key being written. * @param string $meta_value Value that was written. * @return string change_type for the log row. */ protected function resolve_change_type( int $post_id, string $meta_key, string $meta_value ): string { $change_type = self::TRACKED_META_KEYS[ $meta_key ]; if ( self::consume_ai_marker( $post_id, $meta_value ) ) { $change_type = self::AI_CHANGE_TYPE_PREFIX . $change_type; } return $change_type; } /** * Marks a value as an accepted AI suggestion for a post, so the save * that eventually commits it gets logged as ai_applied_* rather than a * manual edit. Called from the REST layer when the user clicks * "Вставити" on an AI suggestion for a tracked meta field. * * @param int $post_id Post ID. * @param string $value The suggestion exactly as it will be saved * (after the meta field's sanitize callback). */ public static function mark_ai_applied( int $post_id, string $value ): void { set_transient( self::ai_marker_key( $post_id, $value ), 1, self::AI_MARKER_TTL ); } /** * Checks-and-clears the AI-applied marker for a (post, value) pair. * * @param int $post_id Post ID. * @param string $value Value that was written. * @return bool Whether a marker existed (it is deleted either way). */ protected static function consume_ai_marker( int $post_id, string $value ): bool { $key = self::ai_marker_key( $post_id, $value ); $marked = false !== get_transient( $key ); if ( $marked ) { delete_transient( $key ); } return $marked; } /** * Transient name for one (post, value) AI-applied marker. The value is * hashed — transient names are length-limited and the value itself * doesn't belong in an option name. * * @param int $post_id Post ID. * @param string $value Suggestion value. * @return string Transient name. */ protected static function ai_marker_key( int $post_id, string $value ): string { return 'abds_seo_ai_applied_' . $post_id . '_' . md5( $value ); } /** * Inserts one row into wp_abds_seo_changes_log. * * @param int $post_id Post ID. * @param string $change_type One of the CHANGE_TYPE_* constants. * @param string $before_value Value before the change. * @param string $after_value Value after the change. */ protected function insert_log_row( int $post_id, string $change_type, string $before_value, string $after_value ): void { global $wpdb; $table = $wpdb->prefix . 'abds_seo_changes_log'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $table is built only from $wpdb->prefix plus a hardcoded literal, never user input; $wpdb->insert() safely escapes its values via the format array. Runs once per tracked meta-field save, not a cacheable read path. $wpdb->insert( $table, array( 'post_id' => $post_id, 'user_id' => get_current_user_id(), 'change_type' => $change_type, 'before_value' => $before_value, 'after_value' => $after_value, 'created_at' => current_time( 'mysql' ), ), array( '%d', '%d', '%s', '%s', '%s', '%s' ) ); } /** * Applied SEO changes for one post, oldest first — the timestamps the * rank chart overlays so a position move can be read against the action * that may have caused it. Only the change_type and when it happened are * returned; the before/after values aren't needed for the overlay and * would leak more than the chart should carry. * * @param int $post_id Post ID. * @param int $limit Max rows (newest kept when truncated). * @return array */ public function get_applied_changes( int $post_id, int $limit = 100 ): array { global $wpdb; $table = $wpdb->prefix . 'abds_seo_changes_log'; if ( $post_id <= 0 ) { return array(); } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is $wpdb->prefix plus a hardcoded literal, never user input; $post_id and $limit are passed through $wpdb->prepare(). Admin-only read behind the rank chart, run once per chart open. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT change_type, created_at FROM {$table} WHERE post_id = %d ORDER BY created_at ASC, id ASC LIMIT %d", $post_id, max( 1, $limit ) ), ARRAY_A ); // phpcs:enable return array_map( static fn( $row ) => array( 'change_type' => (string) $row['change_type'], 'created_at' => (string) $row['created_at'], ), (array) $rows ); } /** * Maps a change_type back to the post meta key it corresponds to — * used by the REST undo endpoint to know which meta key to write * before_value back into. An ai_applied_* variant maps to the same * meta key as its base type: undoing an AI-applied change is the exact * same operation as undoing a manual one. * * @param string $change_type One of the CHANGE_TYPE_* constants, with * or without the AI_CHANGE_TYPE_PREFIX. * @return string|null Meta key, or null if unrecognized. */ public static function meta_key_for_change_type( string $change_type ): ?string { if ( 0 === strpos( $change_type, self::AI_CHANGE_TYPE_PREFIX ) ) { $change_type = substr( $change_type, strlen( self::AI_CHANGE_TYPE_PREFIX ) ); } $meta_key = array_search( $change_type, self::TRACKED_META_KEYS, true ); return false !== $meta_key ? $meta_key : null; } }