Subject: [PATCH] 57967 with unit tests
---
Index: tests/phpunit/tests/user.php
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/tests/phpunit/tests/user.php b/tests/phpunit/tests/user.php
--- a/tests/phpunit/tests/user.php	(revision d0f1816c36e7715c76e663b2459e191003def2bc)
+++ b/tests/phpunit/tests/user.php	(date 1679439032653)
@@ -915,6 +915,69 @@
 		$this->assertSame( 'existing_user_email_as_login', $user_id->get_error_code() );
 	}
 
+	/**
+	 * @ticket 57967
+	 */
+	public function test_wp_update_user_should_allow_user_login_with_same_user_email() {
+		$user_email = str_repeat( 'a', 5 ) . '@example.com';
+
+		$user_id = wp_insert_user(
+			array(
+				'user_login'    => $user_email,
+				'user_email'    => $user_email,
+				'user_pass'     => 'whatever',
+				'user_nicename' => 'whatever',
+			)
+		);
+
+		$existing_id = wp_update_user(
+			array(
+				'ID'         => $user_id,
+				'first_name' => 'Bob',
+			)
+		);
+
+		$this->assertNotWPError( $existing_id );
+		$this->assertSame( $existing_id, $user_id );
+	}
+
+	/**
+	 * @ticket 57967
+	 */
+	public function test_wp_update_user_should_reject_user_login_that_matches_existing_user_email() {
+		$user_email_a = str_repeat( 'a', 5 ) . '@example.com';
+
+		$user_id_a = wp_insert_user(
+			array(
+				'user_login'    => $user_email_a,
+				'user_email'    => $user_email_a,
+				'user_pass'     => 'whatever',
+				'user_nicename' => 'whatever',
+			)
+		);
+
+		$user_email_b = str_repeat( 'b', 5 ) . '@example.com';
+
+		$user_id_b = wp_insert_user(
+			array(
+				'user_login'    => $user_email_b,
+				'user_email'    => $user_email_b,
+				'user_pass'     => 'whatever',
+				'user_nicename' => 'whatever',
+			)
+		);
+
+		$existing_id_b = wp_update_user(
+			array(
+				'ID'         => $user_id_b,
+				'user_login' => $user_email_a,
+			)
+		);
+
+		$this->assertWPError( $existing_id_b );
+		$this->assertSame( 'existing_user_email_as_login', $existing_id_b->get_error_code() );
+	}
+
 	/**
 	 * @ticket 33793
 	 */
Index: src/wp-includes/user.php
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/src/wp-includes/user.php b/src/wp-includes/user.php
--- a/src/wp-includes/user.php	(revision d0f1816c36e7715c76e663b2459e191003def2bc)
+++ b/src/wp-includes/user.php	(date 1679439101862)
@@ -2129,7 +2129,8 @@
 	}
 
 	// Username must not match an existing user email.
-	if ( email_exists( $user_login ) ) {
+	$existing_user_id = email_exists( $user_login );
+	if ( $existing_user_id && ( ! $update || ( isset( $user_id ) && $existing_user_id !== $user_id ) ) ) {
 		return new WP_Error( 'existing_user_email_as_login', __( 'Sorry, that username is not available.' ) );
 	}
 
