Commit b33f716d2c4 for woocommerce

commit b33f716d2c48ebd28bc5dfec4e95b00f1ee4e3d8
Author: Luigi Teschio <gigitux@gmail.com>
Date:   Fri Nov 20 16:52:12 2026 +0100

    Scope order review lookups to the order instead of the billing email (#71231)

    (cherry picked from commit a3578450a62854359df5b2a6e7bceaf8009ea5ea)

    Co-authored-by: Taha Paksu <3295+tpaksu@users.noreply.github.com>

diff --git a/plugins/woocommerce/src/Internal/OrderReviews/ItemEligibility.php b/plugins/woocommerce/src/Internal/OrderReviews/ItemEligibility.php
index d3b63f6352c..ab3be59dfd9 100644
--- a/plugins/woocommerce/src/Internal/OrderReviews/ItemEligibility.php
+++ b/plugins/woocommerce/src/Internal/OrderReviews/ItemEligibility.php
@@ -77,8 +77,8 @@ class ItemEligibility {
 	public const VARIATION_SUMMARY_META_KEY = '_review_variation_summary';

 	/**
-	 * Per-request cache for the "did this email review this product (and this
-	 * variation) on this order" lookup, keyed by
+	 * Per-request cache for the "does this order already have a review for this
+	 * product (and this variation)" lookup, keyed by
 	 * `order_id|product_id|variation_id|email`. Value is a `WP_Comment` when
 	 * one matches, or `null` when the slot has been checked and nothing
 	 * matches (so a second call doesn't re-query).
@@ -158,7 +158,7 @@ class ItemEligibility {
 	public static function preload_for_items( iterable $items, WC_Order $order ): void {
 		$email    = $order->get_billing_email();
 		$order_id = $order->get_id();
-		if ( '' === $email || $order_id <= 0 ) {
+		if ( $order_id <= 0 ) {
 			return;
 		}

@@ -195,14 +195,12 @@ class ItemEligibility {
 		// product on a later order shouldn't see their old review here.
 		$comments = get_comments(
 			array(
-				'post__in'           => array_values( $product_ids ),
-				'author_email'       => $email,
-				'type'               => 'review',
-				'status'             => 'approve',
-				'include_unapproved' => array( $email ),
-				'orderby'            => 'comment_date_gmt',
-				'order'              => 'DESC',
-				'meta_query'         => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post__in + author_email.
+				'post__in'   => array_values( $product_ids ),
+				'type'       => 'review',
+				'status'     => array( 'approve', 'hold' ),
+				'orderby'    => 'comment_date_gmt',
+				'order'      => 'DESC',
+				'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post__in + the order meta.
 					array(
 						'key'   => self::ORDER_META_KEY,
 						'value' => (string) $order_id,
@@ -486,7 +484,7 @@ class ItemEligibility {
 	private static function find_existing_review( int $product_id, int $variation_id, WC_Order $order ): ?WP_Comment {
 		$email    = $order->get_billing_email();
 		$order_id = (int) $order->get_id();
-		if ( '' === $email || $order_id <= 0 || $product_id <= 0 ) {
+		if ( $order_id <= 0 || $product_id <= 0 ) {
 			return null;
 		}

@@ -497,15 +495,13 @@ class ItemEligibility {

 		$comments = get_comments(
 			array(
-				'post_id'            => $product_id,
-				'author_email'       => $email,
-				'type'               => 'review',
-				'status'             => 'approve',
-				'include_unapproved' => array( $email ),
-				'number'             => 1,
-				'orderby'            => 'comment_date_gmt',
-				'order'              => 'DESC',
-				'meta_query'         => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post_id + author_email.
+				'post_id'    => $product_id,
+				'type'       => 'review',
+				'status'     => array( 'approve', 'hold' ),
+				'number'     => 1,
+				'orderby'    => 'comment_date_gmt',
+				'order'      => 'DESC',
+				'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post_id + the order meta.
 					'relation' => 'AND',
 					array(
 						'key'   => self::ORDER_META_KEY,
diff --git a/plugins/woocommerce/src/Internal/OrderReviews/SubmissionHandler.php b/plugins/woocommerce/src/Internal/OrderReviews/SubmissionHandler.php
index d365d2e236d..8fe24a180ea 100644
--- a/plugins/woocommerce/src/Internal/OrderReviews/SubmissionHandler.php
+++ b/plugins/woocommerce/src/Internal/OrderReviews/SubmissionHandler.php
@@ -452,16 +452,35 @@ class SubmissionHandler {
 			? $existing->comment_approved
 			: self::moderate_edited_review( $existing, $content, $ip, $agent );

-		$update_ok = wp_update_comment(
-			wp_slash(
-				array(
-					'comment_ID'      => $existing_id,
-					'comment_content' => $content,
-					// Stored by core before it recounts the product's ratings.
-					'comment_meta'    => array( 'rating' => $rating ),
+		// Core re-filters the stored address on every update and encodes `&`, drifting it one
+		// step per write. Put it back for this row only, since callbacks inside
+		// wp_update_comment() can update other comments. No sanitize_email() as the insert path
+		// uses: that strips the `;` from an address an earlier write already encoded. No
+		// wp_slash() either: wp_update_comment_data receives unslashed data.
+		$stored_email   = (string) $existing->comment_author_email;
+		$keep_raw_email = function ( $data, $comment ) use ( $existing_id, $stored_email ) {
+			// A callback may short-circuit the update by returning WP_Error instead of data.
+			if ( is_array( $data ) && (int) ( $comment['comment_ID'] ?? 0 ) === $existing_id ) {
+				$data['comment_author_email'] = $stored_email;
+			}
+
+			return $data;
+		};
+		add_filter( 'wp_update_comment_data', $keep_raw_email, PHP_INT_MAX, 2 );
+		try {
+			$update_ok = wp_update_comment(
+				wp_slash(
+					array(
+						'comment_ID'      => $existing_id,
+						'comment_content' => $content,
+						// Stored by core before it recounts the product's ratings.
+						'comment_meta'    => array( 'rating' => $rating ),
+					)
 				)
-			)
-		);
+			);
+		} finally {
+			remove_filter( 'wp_update_comment_data', $keep_raw_email, PHP_INT_MAX );
+		}
 		if ( false === $update_ok || is_wp_error( $update_ok ) ) {
 			return array( 'error' => 'update_failed' );
 		}
@@ -559,8 +578,8 @@ class SubmissionHandler {
 	 */
 	private static function insert_review( array $comment_data ) {
 		// Sanitize the address as core's pre_comment_author_email chain would, but
-		// keep it un-encoded (sanitize_email preserves `&`) so the eligibility
-		// lookups still match the order's billing email.
+		// keep it un-encoded (sanitize_email preserves `&`): WordPress matches this
+		// column exactly elsewhere, the privacy exporter and eraser included.
 		$raw_email      = wp_slash( sanitize_email( (string) $comment_data['comment_author_email'] ) );
 		$keep_raw_email = function () use ( $raw_email ) {
 			return $raw_email;
@@ -599,19 +618,13 @@ class SubmissionHandler {
 	 * @return bool
 	 */
 	private static function has_rejected_review( WC_Order $order, int $product_id, int $variation_id ): bool {
-		$email = $order->get_billing_email();
-		if ( '' === $email ) {
-			return false;
-		}
-
 		$comments = get_comments(
 			array(
-				'post_id'      => $product_id,
-				'author_email' => $email,
-				'type'         => 'review',
-				'status'       => array( 'spam', 'trash' ),
-				'number'       => 1,
-				'meta_query'   => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post_id + author_email.
+				'post_id'    => $product_id,
+				'type'       => 'review',
+				'status'     => array( 'spam', 'trash' ),
+				'number'     => 1,
+				'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post_id + the order meta.
 					'relation' => 'AND',
 					array(
 						'key'   => ItemEligibility::ORDER_META_KEY,
@@ -652,21 +665,15 @@ class SubmissionHandler {
 	 * @return \WP_Comment|null
 	 */
 	private static function find_auto_rejected_review( WC_Order $order, int $product_id, int $variation_id ): ?\WP_Comment {
-		$email = $order->get_billing_email();
-		if ( '' === $email ) {
-			return null;
-		}
-
 		$comments = get_comments(
 			array(
-				'post_id'      => $product_id,
-				'author_email' => $email,
-				'type'         => 'review',
-				'status'       => array( 'spam', 'trash' ),
-				'number'       => 1,
-				'orderby'      => 'comment_date_gmt',
-				'order'        => 'DESC',
-				'meta_query'   => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post_id + author_email.
+				'post_id'    => $product_id,
+				'type'       => 'review',
+				'status'     => array( 'spam', 'trash' ),
+				'number'     => 1,
+				'orderby'    => 'comment_date_gmt',
+				'order'      => 'DESC',
+				'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post_id + the order meta.
 					'relation' => 'AND',
 					array(
 						'key'   => ItemEligibility::ORDER_META_KEY,
@@ -712,11 +719,6 @@ class SubmissionHandler {
 			return;
 		}

-		$customer_email = $order->get_billing_email();
-		if ( '' === $customer_email ) {
-			return;
-		}
-
 		// Build the same eligible-row set the page uses, then collect the
 		// distinct (parent product, variation) slots that need a review.
 		// Counting by slot rather than per-line-item means a double-submit of
@@ -754,12 +756,11 @@ class SubmissionHandler {
 		// reviewable items.
 		$comments = get_comments(
 			array(
-				'post__in'     => array_values( $product_ids ),
-				'author_email' => $customer_email,
-				'type'         => 'review',
-				'status'       => array( 'approve', 'hold' ),
-				'number'       => 0,
-				'meta_query'   => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post__in + author_email.
+				'post__in'   => array_values( $product_ids ),
+				'type'       => 'review',
+				'status'     => array( 'approve', 'hold' ),
+				'number'     => 0,
+				'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- bounded by post__in + the order meta.
 					array(
 						'key'   => ItemEligibility::ORDER_META_KEY,
 						'value' => (string) $order->get_id(),
diff --git a/plugins/woocommerce/tests/php/src/Internal/OrderReviews/ItemEligibilityTest.php b/plugins/woocommerce/tests/php/src/Internal/OrderReviews/ItemEligibilityTest.php
index 1248df6a89f..a7c149eb55f 100644
--- a/plugins/woocommerce/tests/php/src/Internal/OrderReviews/ItemEligibilityTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/OrderReviews/ItemEligibilityTest.php
@@ -151,6 +151,47 @@ class ItemEligibilityTest extends WC_Unit_Test_Case {
 		$this->assertNull( $decision['comment'], 'Reviews from a different order must not pre-fill the current row.' );
 	}

+	/**
+	 * @testdox decide() finds the order's review even when the billing email has since changed.
+	 */
+	public function test_decide_finds_review_whose_author_email_differs(): void {
+		$built = $this->make_order( 'new-contact@example.test' );
+		// Written while the order still carried a different billing address.
+		$comment_id = $this->insert_review(
+			$built['product_id'],
+			'old-contact@example.test',
+			'Before the address changed.',
+			4,
+			(int) $built['order']->get_id()
+		);
+
+		$decision = ItemEligibility::decide( $built['item'], $built['order'] );
+
+		$this->assertNotNull( $decision['comment'], 'The order is the scope, not the address.' );
+		$this->assertSame( $comment_id, (int) $decision['comment']->comment_ID );
+	}
+
+	/**
+	 * @testdox decide() finds a review the moderation checks are still holding.
+	 */
+	public function test_decide_finds_a_held_review(): void {
+		$built      = $this->make_order( 'jane@example.test' );
+		$comment_id = $this->insert_review(
+			$built['product_id'],
+			'jane@example.test',
+			'Waiting on moderation.',
+			4,
+			(int) $built['order']->get_id(),
+			0,
+			0
+		);
+
+		$decision = ItemEligibility::decide( $built['item'], $built['order'] );
+
+		$this->assertNotNull( $decision['comment'], 'A held review still occupies the slot.' );
+		$this->assertSame( $comment_id, (int) $decision['comment']->comment_ID );
+	}
+
 	/**
 	 * @testdox exclude_fully_refunded_items drops items whose full quantity has been refunded.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Internal/OrderReviews/SubmissionHandlerTest.php b/plugins/woocommerce/tests/php/src/Internal/OrderReviews/SubmissionHandlerTest.php
index afb5532e736..c168107346f 100644
--- a/plugins/woocommerce/tests/php/src/Internal/OrderReviews/SubmissionHandlerTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/OrderReviews/SubmissionHandlerTest.php
@@ -139,6 +139,20 @@ class SubmissionHandlerTest extends WC_Unit_Test_Case {
 		);
 	}

+	/**
+	 * Build a completed order with one product and the given billing email.
+	 *
+	 * @param string $email Billing email.
+	 * @return array{order:WC_Order, product_ids:int[], item_ids:int[]}
+	 */
+	private function make_order_with_email( string $email ): array {
+		$built = $this->make_order( 1 );
+		$built['order']->set_billing_email( $email );
+		$built['order']->save();
+
+		return $built;
+	}
+
 	/**
 	 * Invoke the handler and capture the JSON it would have sent.
 	 *
@@ -1364,6 +1378,207 @@ class SubmissionHandlerTest extends WC_Unit_Test_Case {
 		$this->assertSame( $comment_id, (int) $second_row['comment_id'], 'Resubmit must reuse the same comment.' );
 	}

+	/**
+	 * @testdox A moderator's trash verdict still blocks resubmission after the shopper has edited the review.
+	 * @testWith ["a+b@example.test"]
+	 *           ["a&b@example.test"]
+	 *           ["o'neil&b@example.test"]
+	 *
+	 * @param string $email Billing email to run the flow with.
+	 */
+	public function test_trash_verdict_survives_an_edit( string $email ): void {
+		$built   = $this->make_order_with_email( $email );
+		$order   = $built['order'];
+		$product = $built['product_ids'][0];
+		$item    = $built['item_ids'][0];
+
+		$first = $this->submit_review( $order, $product, $item, 4, 'First take.' );
+
+		// The edit is the step that used to re-encode the stored address.
+		$second = $this->submit_review( $order, $product, $item, 5, 'Second take.' );
+		$this->assertSame( (int) $first['comment_id'], (int) $second['comment_id'], 'The edit must reuse the row.' );
+
+		wp_trash_comment( (int) $first['comment_id'] );
+
+		$third = $this->submit_review( $order, $product, $item, 5, 'Third take.' );
+
+		$this->assertSame( 'error', $third['status'], 'A trashed review must block resubmission.' );
+		$this->assertSame( 'update_failed', $third['error'] );
+		$this->assertCount(
+			1,
+			get_comments(
+				array(
+					'post_id' => $product,
+					'type'    => 'review',
+					'status'  => 'any',
+				)
+			),
+			'The refusal must not leave a second review behind.'
+		);
+	}
+
+	/**
+	 * @testdox Editing a review leaves an ampersand in the stored author email unencoded.
+	 */
+	public function test_edit_does_not_encode_the_stored_author_email(): void {
+		$built   = $this->make_order_with_email( 'a&b@example.test' );
+		$order   = $built['order'];
+		$product = $built['product_ids'][0];
+		$item    = $built['item_ids'][0];
+
+		$first = $this->submit_review( $order, $product, $item, 4, 'First take.' );
+		$this->submit_review( $order, $product, $item, 5, 'Second take.' );
+
+		$comment = get_comment( (int) $first['comment_id'] );
+
+		$this->assertSame( 'a&b@example.test', $comment->comment_author_email );
+	}
+
+	/**
+	 * @testdox A trashed review is found whatever the stored author email says.
+	 */
+	public function test_trash_verdict_is_found_whatever_the_stored_email(): void {
+		global $wpdb;
+
+		$stored = 'drifted-past-recognition@example.test';
+
+		$built   = $this->make_order_with_email( 'a&b@example.test' );
+		$order   = $built['order'];
+		$product = $built['product_ids'][0];
+		$item    = $built['item_ids'][0];
+
+		$first      = $this->submit_review( $order, $product, $item, 4, 'First take.' );
+		$comment_id = (int) $first['comment_id'];
+
+		// Stand in for a row another wp_update_comment() caller has drifted. Each write adds
+		// another step, so the lookups key on the order instead of chasing the address.
+		$wpdb->update(
+			$wpdb->comments,
+			array( 'comment_author_email' => $stored ),
+			array( 'comment_ID' => $comment_id )
+		);
+		clean_comment_cache( $comment_id );
+		$this->assertSame(
+			$stored,
+			get_comment( $comment_id )->comment_author_email,
+			'The simulated drifted row must actually be encoded, or this proves nothing.'
+		);
+
+		wp_trash_comment( $comment_id );
+
+		$second = $this->submit_review( $order, $product, $item, 5, 'Second take.' );
+
+		$this->assertSame( 'error', $second['status'], 'A drifted row must still be found.' );
+		$this->assertSame( 'update_failed', $second['error'] );
+		$this->assertCount(
+			1,
+			get_comments(
+				array(
+					'post_id' => $product,
+					'type'    => 'review',
+					'status'  => 'any',
+				)
+			),
+			'The refusal must not leave a second review behind.'
+		);
+	}
+
+	/**
+	 * @testdox A trashed review still blocks resubmission on an order with no billing email.
+	 */
+	public function test_trash_verdict_holds_for_an_order_without_a_billing_email(): void {
+		// Built without an address rather than by clearing one: WC_Order keeps the stored
+		// value when an existing billing email is set back to an empty string.
+		$order = new WC_Order();
+		$order->set_billing_first_name( 'Phone' );
+		$order->set_billing_last_name( 'Order' );
+		$order->set_status( OrderStatus::COMPLETED );
+		$order->save();
+
+		$wc_product = WC_Helper_Product::create_simple_product();
+		$order->add_product( $wc_product, 1 );
+		$order->save();
+
+		$items   = array_values( $order->get_items() );
+		$product = $wc_product->get_id();
+		$item    = $items[0]->get_id();
+
+		$this->assertSame(
+			'',
+			wc_get_order( $order->get_id() )->get_billing_email(),
+			'The order must really have no billing email, or this proves nothing.'
+		);
+
+		$first = $this->submit_review( $order, $product, $item, 4, 'First take.' );
+		wp_trash_comment( (int) $first['comment_id'] );
+
+		$second = $this->submit_review( $order, $product, $item, 5, 'Second take.' );
+
+		$this->assertSame( 'error', $second['status'], 'The guard must not depend on a billing email.' );
+		$this->assertSame( 'update_failed', $second['error'] );
+		$this->assertCount(
+			1,
+			get_comments(
+				array(
+					'post_id' => $product,
+					'type'    => 'review',
+					'status'  => 'any',
+				)
+			),
+			'The refusal must not leave a second review behind.'
+		);
+	}
+
+	/**
+	 * @testdox Editing a review leaves another comment's author email alone.
+	 */
+	public function test_edit_does_not_rewrite_another_comments_author_email(): void {
+		$built   = $this->make_order_with_email( 'a&b@example.test' );
+		$order   = $built['order'];
+		$product = $built['product_ids'][0];
+		$item    = $built['item_ids'][0];
+
+		$this->submit_review( $order, $product, $item, 4, 'First take.' );
+
+		$bystander_id = (int) self::factory()->comment->create(
+			array(
+				'comment_post_ID'      => $product,
+				'comment_author_email' => 'bystander@example.test',
+			)
+		);
+
+		// Stand in for a plugin that updates a different comment from inside this update.
+		$meddle = function ( $data, $comment ) use ( $bystander_id ) {
+			if ( (int) $comment['comment_ID'] !== $bystander_id ) {
+				wp_update_comment(
+					array(
+						'comment_ID'      => $bystander_id,
+						'comment_content' => 'Touched.',
+					)
+				);
+			}
+
+			return $data;
+		};
+		add_filter( 'wp_update_comment_data', $meddle, 10, 2 );
+		try {
+			$this->submit_review( $order, $product, $item, 5, 'Second take.' );
+		} finally {
+			remove_filter( 'wp_update_comment_data', $meddle, 10 );
+		}
+
+		$this->assertSame(
+			'Touched.',
+			get_comment( $bystander_id )->comment_content,
+			'The nested update must actually have run, or this proves nothing.'
+		);
+		$this->assertSame(
+			'bystander@example.test',
+			get_comment( $bystander_id )->comment_author_email,
+			'The override must apply to the review being edited, not to every comment update.'
+		);
+	}
+
 	/**
 	 * @testdox A logged-in admin who owns the order resubmitting disallowed markup gets it stripped on update too.
 	 */