Make WordPress Core


Ignore:
Timestamp:
03/04/2021 12:12:55 AM (3 years ago)
Author:
peterwilsoncc
Message:

Roles/Caps: Return same result from current_user_can and user_can().

Ensure current_user_can() and user_can() return the same results for logged out users. For core capabilities this changes user_can( 0, 'exist' ) to return true rather than false in line with current_user_can( 'exist' ) for logged out users.

Convert current_user_can() and current_user_can_for_blog() to wrapper functions ultimately calling user_can().

Add anonymous user to primitive capability checks as appropriate. Convert Tests_User_Capabilities::test_other_caps_for_all_roles() to use a data provider and add tests to check whether user exists in the database (WP_User::exists()) as that intentionally differs from the exist capability.

Props jjj, johnbillion, peterwilsoncc, SergeyBiryukov, TimothyBlynJacobs.
Fixes #52076.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/capabilities.php

    r50138 r50490  
    680680 * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
    681681 *              by adding it to the function signature.
     682 * @since 5.8.0 Converted to wrapper for the user_can() function.
    682683 *
    683684 * @see WP_User::has_cap()
     
    690691 */
    691692function current_user_can( $capability, ...$args ) {
    692     $current_user = wp_get_current_user();
    693 
    694     if ( empty( $current_user ) ) {
    695         return false;
    696     }
    697 
    698     return $current_user->has_cap( $capability, ...$args );
     693    return user_can( wp_get_current_user(), $capability, ...$args );
    699694}
    700695
     
    715710 * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
    716711 *              by adding it to the function signature.
     712 * @since 5.8.0 Wraps current_user_can() after switching to blog.
    717713 *
    718714 * @param int    $blog_id    Site ID.
     
    724720    $switched = is_multisite() ? switch_to_blog( $blog_id ) : false;
    725721
    726     $current_user = wp_get_current_user();
    727 
    728     if ( empty( $current_user ) ) {
    729         if ( $switched ) {
    730             restore_current_blog();
    731         }
    732         return false;
    733     }
    734 
    735     $can = $current_user->has_cap( $capability, ...$args );
     722    $can = current_user_can( $capability, ...$args );
    736723
    737724    if ( $switched ) {
     
    806793    }
    807794
    808     if ( ! $user || ! $user->exists() ) {
    809         return false;
     795    if ( empty( $user ) ) {
     796        // User is logged out, create anonymous user object.
     797        $user = new WP_User( 0 );
     798        $user->init( new stdClass );
    810799    }
    811800
Note: See TracChangeset for help on using the changeset viewer.