From 761c45157e168ed6e1467806f8b5a00bb041c83a Mon Sep 17 00:00:00 2001 From: Felix Arntz Date: Sat, 30 Sep 2017 03:53:27 +0000 Subject: [PATCH] Multisite: Fix `count_users()` possibly querying incorrect roles when passed a different site ID. The `time` strategy in `count_users()` queries users by role. However, the roles queried for were not affected by passing another site than the current one through the `$site_id` parameter, causing users having roles that were not queried for to appear as users without a role. This changeset fixes the issue by switching the site before retrieving the roles to query for. Fixes #42014. git-svn-id: https://develop.svn.wordpress.org/trunk@41653 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/user.php | 8 +++++++- tests/phpunit/tests/user/countUsers.php | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/user.php b/src/wp-includes/user.php index 73a5fab469..e74f87d5e7 100644 --- a/src/wp-includes/user.php +++ b/src/wp-includes/user.php @@ -855,7 +855,13 @@ function count_users( $strategy = 'time', $site_id = null ) { $result = array(); if ( 'time' == $strategy ) { - $avail_roles = wp_roles()->get_names(); + if ( is_multisite() && $site_id != get_current_blog_id() ) { + switch_to_blog( $site_id ); + $avail_roles = wp_roles()->get_names(); + restore_current_blog(); + } else { + $avail_roles = wp_roles()->get_names(); + } // Build a CPU-intensive query that will return concise information. $select_count = array(); diff --git a/tests/phpunit/tests/user/countUsers.php b/tests/phpunit/tests/user/countUsers.php index 115b4baa73..ac4e5e1970 100644 --- a/tests/phpunit/tests/user/countUsers.php +++ b/tests/phpunit/tests/user/countUsers.php @@ -133,6 +133,30 @@ class Tests_User_CountUsers extends WP_UnitTestCase { } + /** + * @ticket 42014 + * @group multisite + * @group ms-required + * + * @dataProvider data_count_users_strategies + */ + public function test_count_users_multisite_queries_correct_roles( $strategy ) { + $site_id = (int) self::factory()->blog->create(); + + switch_to_blog( $site_id ); + wp_roles()->add_role( 'tester', 'Tester', array( 'test' => true ) ); + $user_id = self::factory()->user->create( array( + 'role' => 'tester', + ) ); + restore_current_blog(); + + $count = count_users( $strategy, $site_id ); + $this->assertEqualSetsWithIndex( array( + 'tester' => 1, + 'none' => 0, + ), $count['avail_roles'] ); + } + /** * @ticket 34495 *