From 64e114f233bf779a5b7bf5359790c1f69f7e216f Mon Sep 17 00:00:00 2001 From: Joe McGill Date: Thu, 24 Aug 2023 15:57:17 +0000 Subject: [PATCH] Rewrite Rules: Prevent stampedes when flush_rewrite_rules() is called This ensures that the `rewrite_rules` option is not emptied until the new value has been recalculated and the option is updated. The logic for refreshing the option value is moved to a new private method named `WP_Rewrite::refresh_rewrite_rules` which is used by both the `flush_rules` and `refresh_rewrite_rules` methods. Props iCaleb, joemcgill, flixos90, mukesh27. Fixes #58998. Built from https://develop.svn.wordpress.org/trunk@56448 git-svn-id: http://core.svn.wordpress.org/trunk@55960 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- wp-includes/class-wp-rewrite.php | 34 +++++++++++++++++++++++--------- wp-includes/version.php | 2 +- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/wp-includes/class-wp-rewrite.php b/wp-includes/class-wp-rewrite.php index 1f25b03ada..150eabcbd8 100644 --- a/wp-includes/class-wp-rewrite.php +++ b/wp-includes/class-wp-rewrite.php @@ -1490,18 +1490,35 @@ class WP_Rewrite { public function wp_rewrite_rules() { $this->rules = get_option( 'rewrite_rules' ); if ( empty( $this->rules ) ) { - $this->matches = 'matches'; - $this->rewrite_rules(); - if ( ! did_action( 'wp_loaded' ) ) { - add_action( 'wp_loaded', array( $this, 'flush_rules' ) ); - return $this->rules; - } - update_option( 'rewrite_rules', $this->rules ); + $this->refresh_rewrite_rules(); } return $this->rules; } + /** + * Refreshes the rewrite rules, saving the fresh value to the database. + * If the `wp_loaded` action has not occurred yet, will postpone saving to the database. + * + * @since 6.4.0 + */ + private function refresh_rewrite_rules() { + $this->rules = ''; + $this->matches = 'matches'; + + $this->rewrite_rules(); + + if ( ! did_action( 'wp_loaded' ) ) { + /* + * Is not safe to save the results right now, as the rules may be partial. + * Need to give all rules the chance to register. + */ + add_action( 'wp_loaded', array( $this, 'flush_rules' ) ); + } else { + update_option( 'rewrite_rules', $this->rules ); + } + } + /** * Retrieves mod_rewrite-formatted rewrite rules to write to .htaccess. * @@ -1864,8 +1881,7 @@ class WP_Rewrite { unset( $do_hard_later ); } - update_option( 'rewrite_rules', '' ); - $this->wp_rewrite_rules(); + $this->refresh_rewrite_rules(); /** * Filters whether a "hard" rewrite rule flush should be performed when requested. diff --git a/wp-includes/version.php b/wp-includes/version.php index f4f6b857dd..ed168a2b4f 100644 --- a/wp-includes/version.php +++ b/wp-includes/version.php @@ -16,7 +16,7 @@ * * @global string $wp_version */ -$wp_version = '6.4-alpha-56447'; +$wp_version = '6.4-alpha-56448'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.