From 84daf097a01b8a6c7e3ba34c6bd09eaecb5d44b7 Mon Sep 17 00:00:00 2001 From: Felix Arntz Date: Sat, 30 Sep 2017 04:09:11 +0000 Subject: [PATCH] Multisite: Fix `wp_get_users_with_no_role()` possibly including users with a role on a different site. Prior to this change, when passing another site than the current one to `wp_get_users_with_no_role()` through its `$site_id` parameter, the function still used the roles available on the current site, which would cause users with other roles that possibly exist on the other site to show up as users without a role. Switching the site before retrieving the available rules fixes the issue. Fixes #42015. git-svn-id: https://develop.svn.wordpress.org/trunk@41654 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/user.php | 11 +++++++++- .../tests/user/wpGetUsersWithNoRole.php | 20 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/user.php b/src/wp-includes/user.php index e74f87d5e7..6ca5fe32d9 100644 --- a/src/wp-includes/user.php +++ b/src/wp-includes/user.php @@ -2520,7 +2520,16 @@ function wp_get_users_with_no_role( $site_id = null ) { } $prefix = $wpdb->get_blog_prefix( $site_id ); - $regex = implode( '|', array_keys( wp_roles()->get_names() ) ); + + if ( is_multisite() && $site_id != get_current_blog_id() ) { + switch_to_blog( $site_id ); + $role_names = wp_roles()->get_names(); + restore_current_blog(); + } else { + $role_names = wp_roles()->get_names(); + } + + $regex = implode( '|', array_keys( $role_names ) ); $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex ); $users = $wpdb->get_col( $wpdb->prepare( " SELECT user_id diff --git a/tests/phpunit/tests/user/wpGetUsersWithNoRole.php b/tests/phpunit/tests/user/wpGetUsersWithNoRole.php index 10ecf2a565..dca19d2784 100644 --- a/tests/phpunit/tests/user/wpGetUsersWithNoRole.php +++ b/tests/phpunit/tests/user/wpGetUsersWithNoRole.php @@ -101,4 +101,24 @@ class Tests_User_GetUsersWithNoRole extends WP_UnitTestCase { $this->assertEmpty( $users ); } + /** + * @ticket 42015 + * @group multisite + * @group ms-required + */ + public function test_get_users_with_no_role_matches_on_role_name_different_site() { + $site_id = (int) self::factory()->blog->create(); + + switch_to_blog( $site_id ); + wp_roles()->add_role( 'somerole', 'Some role display name' ); + $user_id = self::factory()->user->create( array( + 'role' => 'somerole', + ) ); + restore_current_blog(); + + $users = wp_get_users_with_no_role( $site_id ); + + $this->assertEmpty( $users ); + } + }