Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 119 additions & 15 deletions wordpress-plugin/gk-block-mcp/includes/class-block-writer.php
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,114 @@ private static function swap_is_conflict( $affected, $written, $expected ) {
* @return array|\WP_Error
*/
public function save_post_content( $post_id, $new_content, $expected = null ) {
global $wpdb;

// The guarded save is two writes: the swap, then wp_update_post. Another
// writer landing between them would pass its own compare-and-swap and then
// be overwritten by the second write, with both reporting success. The lock
// keeps those two writes together. SQLite has no GET_LOCK, so it goes unlocked.
$needs_lock = null !== $expected && ! empty( $wpdb->is_mysql );
if ( ! $needs_lock ) {
return $this->write_post_content( $post_id, $new_content, $expected );
}

if ( ! $this->save_lock_acquire( $post_id ) ) {
return new \WP_Error(
'edit_conflict',
__( 'Another save of this post is still running. Re-fetch the page and retry.', 'gk-block-mcp' ),
array( 'status' => 409 )
);
}

try {
return $this->write_post_content( $post_id, $new_content, $expected );
} finally {
$this->save_lock_release( $post_id );
}
}

/**
* Name of the per-post advisory lock that keeps a guarded save's writes together.
*
* @param int $post_id Post ID.
* @return string
*/
private function save_lock_name( $post_id ) {
global $wpdb;
$db = defined( 'DB_NAME' ) ? DB_NAME : '';
$prefix = isset( $wpdb->prefix ) ? $wpdb->prefix : '';
return 'gkbmsave_' . md5( $db . ':' . $prefix . ':' . (int) $post_id );
}

/**
* Take the per-post save lock. Waits at most 5 seconds so a slow save becomes
* a retryable conflict, never a hung request.
*
* @param int $post_id Post ID.
* @return bool True when the lock is held (and must be released).
*/
private function save_lock_acquire( $post_id ) {
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- server-side advisory lock, no API exists.
return 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, %d)', $this->save_lock_name( $post_id ), 5 ) );
}

/**
* Release the per-post save lock.
*
* @param int $post_id Post ID.
* @return void
*/
private function save_lock_release( $post_id ) {
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- releasing the advisory lock taken above.
$wpdb->query( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $this->save_lock_name( $post_id ) ) );
}

/**
* Restore the pre-swap content after a save that failed partway. The WHERE pins
* our own bytes so a writer that already moved the row on is not clobbered.
*
* @param int $post_id Post ID.
* @param string $expected Content before the swap.
* @param string $new_content Content the swap wrote.
* @return void
*/
private function roll_back_swap( $post_id, $expected, $new_content ) {
global $wpdb;

// Byte-exact: the WHERE below uses the column's collation, which would treat
// a case-only nested edit as the swap's own bytes and overwrite it.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$current = $wpdb->get_var( $wpdb->prepare( 'SELECT post_content FROM %i WHERE ID = %d', $wpdb->posts, $post_id ) );
if ( (string) $current !== (string) $new_content ) {
clean_post_cache( $post_id );
return;
}

// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$wpdb->query(
$wpdb->prepare(
'UPDATE %i SET post_content = %s WHERE ID = %d AND post_content = %s',
$wpdb->posts,
$expected,
$post_id,
$new_content
)
);
clean_post_cache( $post_id );
}

/**
* Write the content, with the compare-and-swap guard when a snapshot is given.
*
* @param int $post_id Post ID.
* @param string $new_content Serialized block markup to save.
* @param string|null $expected Snapshot the mutation was based on.
* @return array|\WP_Error
* @throws \Throwable When a hook throws during the save, after rolling back the swap.
*/
private function write_post_content( $post_id, $new_content, $expected ) {
// Optimistic-concurrency guard: when the caller passes the snapshot its
// mutation was based on, persist via a portable compare-and-swap so a
// concurrent edit is never silently clobbered.
Expand Down Expand Up @@ -523,6 +631,15 @@ public function save_post_content( $post_id, $new_content, $expected = null ) {
),
true
);
} catch ( \Throwable $error ) {
// A hook threw partway through the save. Without this the swapped content
// could stay with no revision and no completed save hooks. The rollback
// only applies while the row still holds the swap's own bytes, so a nested
// save, or a filtered save that already finished, is never undone.
if ( $did_cas_swap ) {
$this->roll_back_swap( $post_id, $expected, $new_content );
}
throw $error;
} finally {
// Restore content_save_pre via finally so a downstream throw inside
// wp_update_post (e.g. a save_post hook handler that errors) doesn't
Expand All @@ -538,21 +655,8 @@ public function save_post_content( $post_id, $new_content, $expected = null ) {
// The raw swap already wrote $new_content, but wp_update_post
// rejected the save (e.g. WP core refuses to empty a title-less
// post). Restore the pre-swap content so a failed save never
// destroys the post, and drop the primed cache so readers do not
// serve the rolled-back value. The WHERE pins our own bytes so a
// writer that already moved the row on is not clobbered.
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$wpdb->query(
$wpdb->prepare(
'UPDATE %i SET post_content = %s WHERE ID = %d AND post_content = %s',
$wpdb->posts,
$expected,
$post_id,
$new_content
)
);
clean_post_cache( $post_id );
// destroys the post.
$this->roll_back_swap( $post_id, $expected, $new_content );
}
return $result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1459,7 +1459,7 @@ public function gc_records( $force = false ) {
$wpdb->esc_like( $prefix ) . '%'
)
);
foreach ( (array) $names as $name ) {
foreach ( Connections::names_with_prefix( (array) $names, $prefix ) as $name ) {
$record = get_option( $name );
$expires = is_array( $record ) && isset( $record['expires_at'] ) ? (int) $record['expires_at'] : 0;
if ( ! is_array( $record ) || $now > $expires ) {
Expand Down
72 changes: 63 additions & 9 deletions wordpress-plugin/gk-block-mcp/includes/class-connections.php
Original file line number Diff line number Diff line change
Expand Up @@ -243,23 +243,45 @@ private static function meta_row_names() {
global $wpdb;
$like = $wpdb->esc_like( self::META_ROW_PREFIX ) . '%';
if ( is_multisite() ) {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- prefix scan of network options; no caching layer covers a LIKE.
return (array) $wpdb->get_col(
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- prefix scan of network options; no core API lists them.
$names = (array) $wpdb->get_col(
$wpdb->prepare(
'SELECT meta_key FROM %i WHERE site_id = %d AND meta_key LIKE %s',
$wpdb->sitemeta,
get_current_network_id(),
$like
)
);
} else {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- prefix scan of options; no core API lists them.
$names = (array) $wpdb->get_col(
$wpdb->prepare(
'SELECT option_name FROM %i WHERE option_name LIKE %s',
$wpdb->options,
$like
)
);
}
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- prefix scan of options; no caching layer covers a LIKE.
return (array) $wpdb->get_col(
$wpdb->prepare(
'SELECT option_name FROM %i WHERE option_name LIKE %s',
$wpdb->options,
$like
)

return array_values( self::names_with_prefix( $names, self::META_ROW_PREFIX ) );
}

/**
* Keep only names that really start with a prefix. Some database layers, such as
* the SQLite drop-in, still treat an escaped `_` in LIKE as a wildcard.
*
* @since $ver$
*
* @param array $names Names returned by a LIKE query.
* @param string $prefix Exact prefix.
* @return string[]
*/
public static function names_with_prefix( array $names, $prefix ) {
return array_filter(
array_map( 'strval', $names ),
static function ( $name ) use ( $prefix ) {
return 0 === strpos( $name, $prefix );
}
);
}

Expand Down Expand Up @@ -434,5 +456,37 @@ public static function purge_all_recorded() {
\WP_Application_Passwords::delete_application_password( $host, (string) $uuid );
}
}

foreach ( self::meta_row_names() as $name ) {
delete_network_option( null, (string) $name );
}
}

/**
* Delete every option whose name starts with one of the given prefixes.
*
* Uses delete_option() so a persistent object cache drops the row too, and
* escapes the prefix because `_` in a LIKE pattern matches any character.
*
* @since $ver$
*
* @param string[] $prefixes Option name prefixes.
* @return void
*/
public static function delete_options_by_prefix( array $prefixes ) {
global $wpdb;
foreach ( $prefixes as $prefix ) {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- no core API lists options by prefix.
$names = (array) $wpdb->get_col(
$wpdb->prepare(
'SELECT option_name FROM %i WHERE option_name LIKE %s',
$wpdb->options,
$wpdb->esc_like( $prefix ) . '%'
)
);
foreach ( self::names_with_prefix( $names, $prefix ) as $name ) {
delete_option( $name );
}
}
}
}
19 changes: 6 additions & 13 deletions wordpress-plugin/gk-block-mcp/includes/class-settings-page.php
Original file line number Diff line number Diff line change
Expand Up @@ -737,19 +737,12 @@ public function handle_reset() {

// Per-post rate-limit transients accumulate per write activity. Sweep
// them too so reset is a true clean slate.
global $wpdb;
$wpdb->query(
$wpdb->prepare(
'DELETE FROM %i
WHERE option_name LIKE %s
OR option_name LIKE %s
OR option_name LIKE %s
OR option_name LIKE %s',
$wpdb->options,
'_transient_gk_block_api_rate_%',
'_transient_timeout_gk_block_api_rate_%',
'_transient_gk_block_api_instr_rl_%',
'_transient_timeout_gk_block_api_instr_rl_%'
Connections::delete_options_by_prefix(
array(
'_transient_gk_block_api_rate_',
'_transient_timeout_gk_block_api_rate_',
'_transient_gk_block_api_instr_rl_',
'_transient_timeout_gk_block_api_instr_rl_',
)
);

Expand Down
3 changes: 3 additions & 0 deletions wordpress-plugin/gk-block-mcp/readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ Visit Settings → Block MCP. Set the score for a namespace to less than 10 to m

* Tool calls now return a clear error when a login gateway or security plugin answers in place of WordPress.
* WordPress credentials are no longer sent when a site redirects a request to another subdomain.
* Two saves of the same post at the same time no longer lose one of the edits.
* A plugin error during a save now restores the previous content.
* Uninstalling now removes the saved connection records, and uninstalling or resetting settings can no longer delete a similarly named option from another plugin.

#### 💻 Developer Updates

Expand Down
32 changes: 32 additions & 0 deletions wordpress-plugin/gk-block-mcp/tests/Connect/ConnectionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,38 @@ public function test_revoke_by_uuid_resolves_host_from_meta() {
$this->assertSame( array(), \WP_Application_Passwords::get_user_application_passwords( $human ) );
}

/**
* Uninstall removes the rows recording each connection, and keeps a name that
* only matches if `_` were a wildcard.
*/
public function test_purge_all_recorded_removes_connection_meta_rows() {
update_network_option( null, Connections::META_ROW_PREFIX . 'row-1', array( 'user_id' => 0 ) );
update_network_option( null, 'gkXblockXapiXconnXmetaXother', 'x' );

Connections::purge_all_recorded();

$this->assertNull( get_network_option( null, Connections::META_ROW_PREFIX . 'row-1', null ) );
$this->assertSame( 'x', get_network_option( null, 'gkXblockXapiXconnXmetaXother', null ) );
delete_network_option( null, 'gkXblockXapiXconnXmetaXother' );
}

/**
* A prefix delete removes every option under the prefix, and keeps a name that
* only matches if `_` were a wildcard.
*/
public function test_delete_options_by_prefix_treats_underscore_literally() {
update_option( 'gk_block_api_xchg_mine', 'x', false );
update_option( 'gkXblockXapi_xchg_other', 'x', false );
update_option( 'gk_block_api_xchgXother', 'x', false );
Connections::delete_options_by_prefix( array( 'gk_block_api_xchg_' ) );

$this->assertFalse( get_option( 'gk_block_api_xchg_mine' ) );
$this->assertSame( 'x', get_option( 'gkXblockXapi_xchg_other' ) );
$this->assertSame( 'x', get_option( 'gk_block_api_xchgXother' ) );
delete_option( 'gkXblockXapi_xchg_other' );
delete_option( 'gk_block_api_xchgXother' );
}

/**
* purge_all_recorded() deletes every credential the meta store knows about,
* from whichever user holds it — the uninstall path for own-account
Expand Down
Loading
Loading