post_content; $base_version = self::content_version( $persisted_content ); $content = '' !== $editor_content ? $editor_content : $persisted_content; $version = self::content_version( $content ); if ( $expected_version && ! hash_equals( $version, $expected_version ) ) { return new WP_Error( 'content_version_conflict', __( 'The editor content changed after it was read.', 'advanced-animation' ) ); } $legacy_active = self::staged_transaction_for_post( $post_id ); if ( $legacy_active ) { self::acquire_active( $post_id, (string) $legacy_active['id'] ); return self::active_error( array( 'transaction_id' => (string) $legacy_active['id'], 'content_version' => (string) ( $legacy_active['result_version'] ?? '' ), ) ); } $new_transaction_id = wp_generate_uuid4(); if ( ! self::acquire_active( $post_id, $new_transaction_id ) ) { return self::active_error( self::active_record( $post_id ) ); } $transaction = array( 'id' => $new_transaction_id, 'post_id' => $post_id, 'user_id' => get_current_user_id(), 'base_version' => $base_version, 'result_version' => $version, 'base_editor_content' => $content, 'candidate_content' => $content, 'status' => 'preflight', 'created_at' => time(), 'updated_at' => time(), 'mutations' => array(), ); return $transaction; } public static function stage( array $transaction, string $candidate_content, string $action, array $details = array() ) { $validation = self::validate_content( $candidate_content ); if ( ! $validation['valid'] ) { self::fail_preflight( $transaction ); return self::transaction_error( 'candidate_invalid', __( 'The staged block content failed validation and was not delivered to the editor.', 'advanced-animation' ), $transaction, false, array( 'inspect' ), true, $validation ); } $current_content = (string) ( $transaction['candidate_content'] ?? '' ); if ( hash_equals( self::content_version( $current_content ), self::content_version( $candidate_content ) ) ) { self::fail_preflight( $transaction ); return self::transaction_error( 'already_present', __( 'The requested content is already present. No additional mutation was staged.', 'advanced-animation' ), $transaction, false, array( 'inspect', 'commit', 'discard' ) ); } $inserted_content = (string) ( $details['inserted_content'] ?? '' ); if ( 'insert' === $action && empty( $details['allow_duplicate'] ) && '' !== $inserted_content && false !== strpos( $current_content, $inserted_content ) ) { self::fail_preflight( $transaction ); return self::transaction_error( 'already_present', __( 'An identical block insertion is already present. Set allow_duplicate only when the user explicitly requested duplicate generic content.', 'advanced-animation' ), $transaction, false, array( 'inspect', 'commit', 'discard' ) ); } $active = self::active_record( intval( $transaction['post_id'] ) ); if ( ! $active || (string) ( $active['transaction_id'] ?? '' ) !== (string) $transaction['id'] ) { return self::active_error( $active ); } $expected_editor_version = (string) ( $transaction['result_version'] ?? $transaction['base_version'] ?? '' ); $transaction['candidate_content'] = $candidate_content; $transaction['result_version'] = self::content_version( $candidate_content ); $transaction['updated_at'] = time(); $transaction['status'] = 'staged'; unset( $transaction['editor_ack'] ); $transaction['mutations'][] = array_merge( array( 'action' => $action, 'time' => time() ), $details ); self::put( $transaction ); self::touch_active( intval( $transaction['post_id'] ), (string) $transaction['id'] ); $selection = SelectionBridge::read_selection( 'gutenberg' ); $editor_session_id = ''; if ( $selection && SelectionBridge::is_fresh( $selection ) && intval( $selection['post_id'] ?? 0 ) === intval( $transaction['post_id'] ) ) { $editor_session_id = sanitize_text_field( $selection['editor_session_id'] ?? '' ); } SelectionBridge::store_result( array( 'editor' => 'gutenberg', 'action' => 'full_page_edit', 'mutation_action' => $action, 'transaction_id' => $transaction['id'], 'post_id' => $transaction['post_id'], 'post_content' => $candidate_content, 'content_version' => $transaction['result_version'], 'delivery_status' => 'pending', 'editor_session_id' => $editor_session_id, 'base_version' => $transaction['base_version'], 'expected_editor_version' => $expected_editor_version, 'indices' => array_values( array_map( 'intval', (array) ( $details['affected_indices'] ?? array() ) ) ), 'focus_index' => isset( $details['focus_index'] ) ? intval( $details['focus_index'] ) : null, ) ); return $transaction; } public static function discard( string $transaction_id ) { $transactions = self::transactions(); if ( ! isset( $transactions[ $transaction_id ] ) ) { return self::get( $transaction_id ); } $transaction = $transactions[ $transaction_id ]; if ( 'committed' === ( $transaction['status'] ?? '' ) ) { return self::transaction_error( 'already_committed', __( 'This transaction was already committed and cannot be discarded. No content was changed.', 'advanced-animation' ), $transaction, false, array( 'inspect' ) ); } unset( $transactions[ $transaction_id ] ); update_user_meta( get_current_user_id(), self::META_KEY, wp_slash( $transactions ) ); self::release_active( intval( $transaction['post_id'] ?? 0 ), $transaction_id ); self::add_tombstone( $transaction, 'discarded' ); SelectionBridge::clear_result( 'gutenberg', intval( $transaction['post_id'] ?? 0 ), $transaction_id ); return $transaction; } public static function acknowledge( string $transaction_id, array $data ) { $transaction = self::get( $transaction_id ); if ( is_wp_error( $transaction ) ) { return $transaction; } $content_version = sanitize_text_field( $data['content_version'] ?? '' ); if ( $content_version && ! hash_equals( $transaction['result_version'], $content_version ) ) { return new WP_Error( 'editor_version_mismatch', __( 'The editor applied a different content version.', 'advanced-animation' ) ); } $transaction['editor_ack'] = array( 'status' => sanitize_key( $data['status'] ?? 'applied' ), 'content_version' => $content_version, 'tailwind_css' => Security::sanitize_css( (string) ( $data['tailwind_css'] ?? '' ) ), 'validation' => is_array( $data['validation'] ?? null ) ? $data['validation'] : array(), 'acknowledged_at' => time(), ); $transaction['updated_at'] = time(); self::put( $transaction ); if ( 'staged' === ( $transaction['status'] ?? '' ) ) { self::touch_active( intval( $transaction['post_id'] ?? 0 ), $transaction_id ); } if ( 'committed' === ( $transaction['status'] ?? '' ) && ! empty( $transaction['editor_ack']['tailwind_css'] ) && hash_equals( $transaction['result_version'], (string) $transaction['editor_ack']['content_version'] ) ) { $post = get_post( intval( $transaction['post_id'] ) ); if ( $post && hash_equals( $transaction['result_version'], self::content_version( (string) $post->post_content ) ) ) { update_post_meta( $post->ID, '_tailwind_css', $transaction['editor_ack']['tailwind_css'] ); update_post_meta( $post->ID, '_tailwind_css_source_hash', $transaction['result_version'] ); } } return $transaction; } public static function commit( string $transaction_id, string $target = 'save', string $expected_version = '', bool $allow_runtime_fallback = false ) { $transaction = self::get( $transaction_id ); if ( is_wp_error( $transaction ) ) { return $transaction; } if ( 'committed' === ( $transaction['status'] ?? '' ) ) { $post = get_post( intval( $transaction['post_id'] ) ); if ( $post && hash_equals( $transaction['result_version'], self::content_version( (string) $post->post_content ) ) ) { return array( 'transaction' => $transaction, 'post' => $post, 'revision_id' => intval( $transaction['revision_id'] ?? 0 ), 'validation' => self::validate_content( (string) $post->post_content ), 'already_committed' => true ); } return self::transaction_error( 'persisted_content_conflict', __( 'The committed transaction no longer matches persisted content.', 'advanced-animation' ), $transaction, false, array( 'inspect' ) ); } if ( $expected_version && ! hash_equals( $transaction['result_version'], $expected_version ) ) { return self::transaction_error( 'content_version_conflict', __( 'The staged content changed after it was read.', 'advanced-animation' ), $transaction, false, array( 'inspect', 'commit', 'discard' ) ); } $post = get_post( intval( $transaction['post_id'] ) ); if ( ! $post ) { return new WP_Error( 'post_not_found', __( 'Post not found.', 'advanced-animation' ) ); } if ( ! Security::can_edit_post( intval( $post->ID ) ) ) { return new WP_Error( 'edit_forbidden', __( 'Sorry, you are not allowed to edit this post.', 'advanced-animation' ) ); } if ( ! hash_equals( $transaction['base_version'], self::content_version( (string) $post->post_content ) ) ) { $transaction['status'] = 'conflicted'; $transaction['updated_at'] = time(); self::put( $transaction ); self::release_active( intval( $transaction['post_id'] ), $transaction_id ); return self::transaction_error( 'persisted_content_conflict', __( 'The persisted page changed while this transaction was staged.', 'advanced-animation' ), $transaction, false, array( 'inspect', 'discard' ) ); } $validation = self::validate_content( $transaction['candidate_content'] ); if ( ! $validation['valid'] ) { $transaction['status'] = 'conflicted'; $transaction['updated_at'] = time(); self::put( $transaction ); self::release_active( intval( $transaction['post_id'] ), $transaction_id ); return self::transaction_error( 'candidate_invalid', __( 'The staged block content failed validation.', 'advanced-animation' ), $transaction, false, array( 'inspect', 'discard' ), true, $validation ); } $editor_ack = $transaction['editor_ack'] ?? array(); $tailwind_ready = ! empty( $editor_ack['tailwind_css'] ) && hash_equals( $transaction['result_version'], (string) ( $editor_ack['content_version'] ?? '' ) ); if ( self::contains_tailwind_blocks( $transaction['candidate_content'] ) && ! $tailwind_ready && ! $allow_runtime_fallback ) { self::touch_active( intval( $transaction['post_id'] ), $transaction_id ); return new WP_Error( 'tailwind_compile_pending', __( 'Tailwind CSS is not ready. Keep this transaction staged, poll get-page-content, and retry after the active editor acknowledges matching CSS. Use allow_runtime_fallback only when editor compilation is unavailable.', 'advanced-animation' ), array_merge( self::recovery_data( $transaction, true, array( 'commit', 'discard' ), true ), array( 'editor_acknowledged' => ! empty( $editor_ack ), 'tailwind_css_ready' => false, ) ) ); } $snapshot = array( 'post_content' => (string) $post->post_content, 'post_status' => $post->post_status, 'tailwind_css' => get_post_meta( $post->ID, '_tailwind_css', true ), 'tailwind_hash' => get_post_meta( $post->ID, '_tailwind_css_source_hash', true ), ); $revision_id = 0; if ( function_exists( '_wp_put_post_revision' ) && wp_revisions_enabled( $post ) ) { $revision_id = _wp_put_post_revision( $post ); if ( is_wp_error( $revision_id ) ) { return $revision_id; } } $update = array( 'ID' => $post->ID, 'post_content' => $transaction['candidate_content'] ); if ( 'publish' === $target ) { if ( ! current_user_can( 'publish_post', $post->ID ) ) { return new WP_Error( 'publish_forbidden', __( 'The current user cannot publish this post.', 'advanced-animation' ) ); } $update['post_status'] = 'publish'; } $updated = self::update_post_without_revisions( $update ); if ( is_wp_error( $updated ) ) { return $updated; } $persisted = get_post( $post->ID ); $post_validation = self::validate_content( (string) $persisted->post_content ); if ( ! $post_validation['valid'] || ! hash_equals( $transaction['result_version'], self::content_version( (string) $persisted->post_content ) ) ) { self::update_post_without_revisions( array( 'ID' => $post->ID, 'post_content' => $snapshot['post_content'], 'post_status' => $snapshot['post_status'] ) ); update_post_meta( $post->ID, '_tailwind_css', $snapshot['tailwind_css'] ); update_post_meta( $post->ID, '_tailwind_css_source_hash', $snapshot['tailwind_hash'] ); $transaction['status'] = 'conflicted'; $transaction['updated_at'] = time(); self::put( $transaction ); self::release_active( intval( $transaction['post_id'] ), $transaction_id ); return self::transaction_error( 'commit_rolled_back', __( 'Post-write validation failed; the previous page content was restored.', 'advanced-animation' ), $transaction, false, array( 'inspect', 'discard' ), true, $post_validation ); } if ( $tailwind_ready ) { update_post_meta( $post->ID, '_tailwind_css', Security::sanitize_css( (string) $editor_ack['tailwind_css'] ) ); update_post_meta( $post->ID, '_tailwind_css_source_hash', $transaction['result_version'] ); } else { delete_post_meta( $post->ID, '_tailwind_css_source_hash' ); } $transaction['status'] = 'committed'; $transaction['updated_at'] = time(); $transaction['revision_id'] = intval( $revision_id ); self::put( $transaction ); self::release_active( intval( $transaction['post_id'] ), $transaction_id ); return array( 'transaction' => $transaction, 'post' => $persisted, 'revision_id' => intval( $revision_id ), 'validation' => $post_validation ); } public static function fail_preflight( array $transaction ): void { if ( 'preflight' === ( $transaction['status'] ?? '' ) ) { self::release_active( intval( $transaction['post_id'] ?? 0 ), (string) ( $transaction['id'] ?? '' ) ); } } public static function recovery_data( array $transaction, bool $retryable, array $permitted_next_actions, bool $must_not_mutate ): array { return array( 'transaction_id' => (string) ( $transaction['id'] ?? $transaction['transaction_id'] ?? '' ), 'content_version' => (string) ( $transaction['result_version'] ?? $transaction['content_version'] ?? '' ), 'retryable' => $retryable, 'recovery_required' => ! $retryable, 'permitted_next_actions' => array_values( $permitted_next_actions ), 'must_not_mutate' => $must_not_mutate, ); } private static function transaction_error( string $code, string $message, array $transaction, bool $retryable, array $actions, bool $must_not_mutate = true, array $extra = array() ): WP_Error { return new WP_Error( $code, $message, array_merge( self::recovery_data( $transaction, $retryable, $actions, $must_not_mutate ), $extra ) ); } public static function contains_tailwind_blocks( string $content ): bool { foreach ( parse_blocks( $content ) as $block ) { if ( 'tailwind/html' === ( $block['blockName'] ?? '' ) ) { return true; } if ( ! empty( $block['innerBlocks'] ) && self::blocks_contain_tailwind( (array) $block['innerBlocks'] ) ) { return true; } } return false; } private static function blocks_contain_tailwind( array $blocks ): bool { foreach ( $blocks as $block ) { if ( 'tailwind/html' === ( $block['blockName'] ?? '' ) ) return true; if ( ! empty( $block['innerBlocks'] ) && self::blocks_contain_tailwind( (array) $block['innerBlocks'] ) ) return true; } return false; } public static function describe_content( string $content, ?array $selection = null, bool $render = true ): array { $parsed = parse_blocks( $content ); $items = array(); $visible = 0; foreach ( $parsed as $raw_index => $block ) { if ( empty( $block['blockName'] ) ) { continue; } $serialized = serialize_block( $block ); $client_id = null; if ( $selection && isset( $selection['indices'], $selection['clientIds'] ) ) { $position = array_search( $visible, (array) $selection['indices'], true ); if ( false !== $position ) { $client_id = $selection['clientIds'][ $position ] ?? null; } } $items[] = array( 'index' => $visible, 'raw_index' => $raw_index, 'name' => $block['blockName'], 'html_id' => self::root_html_id( $block ), 'client_id' => $client_id, 'attributes' => $block['attrs'] ?? array(), 'rendered_html' => $render && function_exists( 'render_block' ) ? render_block( $block ) : ( $block['innerHTML'] ?? '' ), 'serialized_markup' => $serialized, 'content_hash' => self::content_version( $serialized ), ); $visible++; } return $items; } private static function root_html_id( array $block ): string { $attrs = is_array( $block['attrs'] ?? null ) ? $block['attrs'] : array(); foreach ( array( $attrs['id'] ?? '', $attrs['anchor'] ?? '', $attrs['attrs']['id'] ?? '', ) as $candidate ) { $id = trim( (string) $candidate ); if ( $id ) return $id; } if ( preg_match( '/^\\s*<[^>]+\\sid=["\']([^"\']+)["\']/i', (string) ( $block['innerHTML'] ?? '' ), $match ) ) { return html_entity_decode( $match[1], ENT_QUOTES, 'UTF-8' ); } return ''; } public static function validate_content( string $content ): array { $parsed = parse_blocks( $content ); $described = self::describe_content( $content, null, false ); $errors = array(); $warnings = array(); $ids = array(); $attachment_ids = array(); foreach ( $described as $item ) { if ( class_exists( '\\WP_Block_Type_Registry' ) && ! \WP_Block_Type_Registry::get_instance()->is_registered( $item['name'] ) ) { $errors[] = array( 'code' => 'unregistered_block', 'block' => $item['name'], 'index' => $item['index'] ); } if ( preg_match_all( '/\sid=["\']([^"\']+)["\']/i', $item['serialized_markup'], $matches ) ) { foreach ( $matches[1] as $id ) { if ( isset( $ids[ $id ] ) ) { $errors[] = array( 'code' => 'duplicate_html_id', 'id' => $id ); } $ids[ $id ] = true; } } } if ( preg_match( '/(?:data:image\/|blob:)/i', $content ) ) { $errors[] = array( 'code' => 'unresolved_embedded_asset' ); } if ( function_exists( 'attachment_url_to_postid' ) && preg_match_all( '#https?://[^"\'\s)]+/wp-content/uploads/[^"\'\s)]+#i', $content, $asset_matches ) ) { foreach ( array_unique( $asset_matches[0] ) as $url ) { $attachment_id = intval( attachment_url_to_postid( html_entity_decode( $url, ENT_QUOTES, 'UTF-8' ) ) ); if ( ! $attachment_id || 'attachment' !== get_post_type( $attachment_id ) ) { $errors[] = array( 'code' => 'attachment_missing', 'url' => $url ); } else { $attachment_ids[] = $attachment_id; } } } $roundtrip = serialize_blocks( $parsed ); $second_roundtrip = serialize_blocks( parse_blocks( $roundtrip ) ); $roundtrip_stable = hash_equals( self::content_version( $roundtrip ), self::content_version( $second_roundtrip ) ); if ( ! $roundtrip_stable ) { $errors[] = array( 'code' => 'roundtrip_serialization_mismatch' ); } $roundtrip_blocks = array_values( array_filter( parse_blocks( $roundtrip ), function ( $block ) { return ! empty( $block['blockName'] ); } ) ); if ( count( $described ) !== count( $roundtrip_blocks ) ) { $errors[] = array( 'code' => 'roundtrip_block_count_mismatch' ); } return array( 'valid' => empty( $errors ), 'errors' => $errors, 'warnings' => $warnings, 'top_level_blocks' => count( $described ), 'roundtrip_stable' => $roundtrip_stable, 'duplicate_html_ids' => count( array_filter( $errors, function ( $error ) { return 'duplicate_html_id' === ( $error['code'] ?? '' ); } ) ), 'attachment_ids' => array_values( array_unique( $attachment_ids ) ), ); } private static function update_post_without_revisions( array $update ) { $disable_revisions = static function () { return 0; }; add_filter( 'wp_revisions_to_keep', $disable_revisions, PHP_INT_MAX, 2 ); try { // wp_update_post() passes caller-supplied fields to wp_insert_post(), // which unslashes them. Slash transaction markup exactly once so JSON // attributes and escaped block content survive byte-for-byte validation. return wp_update_post( wp_slash( $update ), true ); } finally { remove_filter( 'wp_revisions_to_keep', $disable_revisions, PHP_INT_MAX ); } } private static function transactions(): array { $user_id = get_current_user_id(); $transactions = get_user_meta( $user_id, self::META_KEY, true ); $transactions = is_array( $transactions ) ? $transactions : array(); $now = time(); $changed = false; foreach ( $transactions as $id => $transaction ) { if ( empty( $transaction['updated_at'] ) || $now - intval( $transaction['updated_at'] ) > self::TTL ) { unset( $transactions[ $id ] ); $changed = true; self::release_active( intval( $transaction['post_id'] ?? 0 ), (string) $id ); self::add_tombstone( $transaction, 'committed' === ( $transaction['status'] ?? '' ) ? 'committed' : 'expired' ); } } if ( $changed ) { update_user_meta( $user_id, self::META_KEY, wp_slash( $transactions ) ); } return $transactions; } private static function put( array $transaction ): void { $transactions = self::transactions(); $transactions[ $transaction['id'] ] = $transaction; // update_user_meta() unslashes recursively. Slash transaction snapshots // once so escaped Gutenberg JSON survives staging and later commit. update_user_meta( get_current_user_id(), self::META_KEY, wp_slash( $transactions ) ); } private static function active_key( int $post_id ): string { return self::ACTIVE_PREFIX . get_current_user_id() . '_' . max( 0, $post_id ); } private static function active_record( int $post_id ): array { if ( ! $post_id ) { return array(); } $key = self::active_key( $post_id ); $record = get_option( $key, array() ); if ( ! is_array( $record ) || empty( $record['transaction_id'] ) ) { return array(); } if ( empty( $record['updated_at'] ) || time() - intval( $record['updated_at'] ) > self::TTL ) { delete_option( $key ); self::add_tombstone( array( 'id' => (string) $record['transaction_id'], 'post_id' => $post_id, 'result_version' => (string) ( $record['content_version'] ?? '' ), ), 'expired' ); return array(); } return $record; } private static function acquire_active( int $post_id, string $transaction_id ): bool { $existing = self::active_record( $post_id ); if ( $existing ) { return hash_equals( (string) $existing['transaction_id'], $transaction_id ); } return (bool) add_option( self::active_key( $post_id ), array( 'transaction_id' => $transaction_id, 'post_id' => $post_id, 'created_at' => time(), 'updated_at' => time(), ), '', false ); } private static function touch_active( int $post_id, string $transaction_id ): void { $record = self::active_record( $post_id ); if ( $record && hash_equals( (string) $record['transaction_id'], $transaction_id ) ) { $record['updated_at'] = time(); $transaction = self::get_without_cleanup( $transaction_id ); $record['content_version'] = (string) ( $transaction['result_version'] ?? $record['content_version'] ?? '' ); update_option( self::active_key( $post_id ), $record, false ); } } private static function release_active( int $post_id, string $transaction_id ): void { if ( ! $post_id || ! $transaction_id ) { return; } $key = self::active_key( $post_id ); $record = get_option( $key, array() ); if ( is_array( $record ) && hash_equals( (string) ( $record['transaction_id'] ?? '' ), $transaction_id ) ) { delete_option( $key ); } } private static function active_error( array $active ): WP_Error { return new WP_Error( 'active_transaction_exists', __( 'Another Gutenberg transaction is already active for this post. Continue, commit, or discard that exact transaction; do not start a second mutation.', 'advanced-animation' ), self::recovery_data( array( 'id' => (string) ( $active['transaction_id'] ?? '' ), 'result_version' => (string) ( $active['content_version'] ?? '' ), ), false, array( 'inspect', 'commit', 'discard' ), true ) ); } private static function get_without_cleanup( string $transaction_id ): array { $transactions = get_user_meta( get_current_user_id(), self::META_KEY, true ); return is_array( $transactions ) && isset( $transactions[ $transaction_id ] ) ? (array) $transactions[ $transaction_id ] : array(); } private static function staged_transaction_for_post( int $post_id ): array { foreach ( self::transactions() as $transaction ) { if ( intval( $transaction['post_id'] ?? 0 ) === $post_id && 'staged' === ( $transaction['status'] ?? '' ) ) { return (array) $transaction; } } return array(); } private static function tombstones(): array { $user_id = get_current_user_id(); $tombstones = get_user_meta( $user_id, self::TOMBSTONE_KEY, true ); $tombstones = is_array( $tombstones ) ? $tombstones : array(); $changed = false; foreach ( $tombstones as $id => $tombstone ) { if ( empty( $tombstone['time'] ) || time() - intval( $tombstone['time'] ) > self::TOMBSTONE_TTL ) { unset( $tombstones[ $id ] ); $changed = true; } } if ( $changed ) { update_user_meta( $user_id, self::TOMBSTONE_KEY, $tombstones ); } return $tombstones; } private static function add_tombstone( array $transaction, string $reason ): void { $transaction_id = (string) ( $transaction['id'] ?? $transaction['transaction_id'] ?? '' ); if ( '' === $transaction_id ) { return; } $tombstones = self::tombstones(); $tombstones[ $transaction_id ] = array( 'id' => $transaction_id, 'post_id' => intval( $transaction['post_id'] ?? 0 ), 'result_version' => (string) ( $transaction['result_version'] ?? $transaction['content_version'] ?? '' ), 'reason' => $reason, 'time' => time(), ); update_user_meta( get_current_user_id(), self::TOMBSTONE_KEY, $tombstones ); } }