From a1389117b223d18f0813ff13f3aaef430f3706c5 Mon Sep 17 00:00:00 2001 From: Boone Gorges Date: Thu, 8 Oct 2015 17:28:34 +0000 Subject: [PATCH] Allow a null `id` to do a `name` lookup in `wp_set_current_user()`. Previously, the `name` fallback was failing in the case where the current user was 0, due to a loose comparison between 0 (the current user) and `null` (the value that is used to trigger the `name` fallback). Props bobbingwide. Fixes #20845. git-svn-id: https://develop.svn.wordpress.org/trunk@34947 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/pluggable.php | 8 ++++- tests/phpunit/tests/user/wpSetCurrentUser.php | 36 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/pluggable.php b/src/wp-includes/pluggable.php index d58f18940b..98403b34ae 100644 --- a/src/wp-includes/pluggable.php +++ b/src/wp-includes/pluggable.php @@ -26,8 +26,14 @@ if ( !function_exists('wp_set_current_user') ) : function wp_set_current_user($id, $name = '') { global $current_user; - if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) ) + // If `$id` matches the user who's already current, there's nothing to do. + if ( isset( $current_user ) + && ( $current_user instanceof WP_User ) + && ( $id == $current_user->ID ) + && ( null !== $id ) + ) { return $current_user; + } $current_user = new WP_User( $id, $name ); diff --git a/tests/phpunit/tests/user/wpSetCurrentUser.php b/tests/phpunit/tests/user/wpSetCurrentUser.php index c47c22cc74..b3c8fce918 100644 --- a/tests/phpunit/tests/user/wpSetCurrentUser.php +++ b/tests/phpunit/tests/user/wpSetCurrentUser.php @@ -23,5 +23,41 @@ class Tests_User_WpSetCurrentUser extends WP_UnitTestCase { $this->assertEquals( $user, wp_get_current_user() ); $this->assertSame( $u, get_current_user_id() ); } + + public function test_should_set_by_name_if_id_is_null_and_current_user_is_nonempty() { + $u1 = $this->factory->user->create(); + wp_set_current_user( $u1 ); + $this->assertSame( $u1, get_current_user_id() ); + + $u2 = $this->factory->user->create( array( + 'user_login' => 'foo', + ) ); + + $user = wp_set_current_user( null, 'foo' ); + + $this->assertSame( $u2, $user->ID ); + $this->assertEquals( $user, wp_get_current_user() ); + $this->assertSame( $u2, get_current_user_id() ); + } + + /** + * Test that you can set the current user by the name parameter when the current user is 0. + * + * @ticket 20845 + */ + public function test_should_set_by_name_if_id_is_null() { + wp_set_current_user( 0 ); + $this->assertSame( 0, get_current_user_id() ); + + $u = $this->factory->user->create( array( + 'user_login' => 'foo', + ) ); + + $user = wp_set_current_user( null, 'foo' ); + + $this->assertSame( $u, $user->ID ); + $this->assertEquals( $user, wp_get_current_user() ); + $this->assertSame( $u, get_current_user_id() ); + } }