Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions projects/packages/stats/changelog/fix-stats-view-multi-role
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: fixed

Fix view_stats capability check for users with multiple roles by checking all roles instead of only the first.
7 changes: 3 additions & 4 deletions projects/packages/stats/src/class-main.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,11 @@ public static function map_meta_caps( $caps, $cap, $user_id ) {
$user = new WP_User( $user_id );
// WordPress 6.9 introduced lazy-loading of some WP_User properties, including `roles`.
// It also made said properties protected, so we can't modify keys directly.
$user_roles = $user->roles;
$user_role = array_shift( $user_roles ); // Work with the copy
$user_roles = (array) $user->roles;
$stats_roles = Options::get_option( 'roles' );

// Is the users role in the available stats roles?
if ( is_array( $stats_roles ) && in_array( $user_role, $stats_roles, true ) ) {
// Is any of the user's roles in the available stats roles?
if ( is_array( $stats_roles ) && ! empty( array_intersect( $user_roles, $stats_roles ) ) ) {
$caps = array( 'read' );
}
}
Expand Down
19 changes: 19 additions & 0 deletions projects/packages/stats/tests/php/Main_Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,25 @@ public function test_view_stats_meta_mapping() {
$this->assertTrue( user_can( $dummy_user_id, 'view_stats' ) );
}

/**
* Test Main::map_meta_caps with multi-role user where admin is not the first role.
*/
public function test_view_stats_meta_mapping_multi_role() {
$dummy_user_id = wp_insert_user(
array(
'user_login' => 'dummy_multirole',
'user_pass' => 'password',
'role' => 'subscriber',
)
);

// Add administrator as a second role.
$user = new \WP_User( $dummy_user_id );
$user->add_role( 'administrator' );

$this->assertTrue( user_can( $dummy_user_id, 'view_stats' ) );
}

/**
* Test Main::should_track
*/
Expand Down
Loading