Skip to content

Commit

Permalink
Role/Capability: Add support for capability queries in WP_User_Query.
Browse files Browse the repository at this point in the history
Similar to the existing `role`/`role__in`/`role__not_in` query arguments, this adds support for three new query arguments in `WP_User_Query`:

* `capability` 
* `capability__in`
* `capability__not_in`

These can be used to fetch users with (or without) a specific set of capabilities, for example to get all users
with the capability to edit a certain post type.

Under the hood, this will check all existing roles on the site and perform a `LIKE` query against the `capabilities` user meta field to find:

* all users with a role that has this capability
* all users with the capability being assigned directly

Note: In WordPress, not all capabilities are stored in the database. Capabilities can also be modified using filters like `map_meta_cap`. These new query arguments do NOT work for such capabilities.

The prime use case for capability queries is to get all "authors", i.e. users with the capability to edit a certain post type.

Until now, `'who' => 'authors'` was used for this, which relies on user levels. However, user levels were deprecated a long time ago and thus never added to custom roles. This led to constant frustration due to users with custom roles missing from places like author dropdowns.

This updates any usage of `'who' => 'authors'` in core to use capability queries instead.

Subsequently, `'who' => 'authors'` queries are being **deprecated** in favor of these new query arguments.

Also adds a new `capabilities` parameter (mapping to `capability__in` in `WP_User_Query`) to the REST API users controller.

Also updates `twentyfourteen_list_authors()` in Twenty Fourteen to make use of this new functionality, adding a new `twentyfourteen_list_authors_query_args` filter to make it easier to override this behavior.

Props scribu, lgladdly, boonebgorges, spacedmonkey, peterwilsoncc, SergeyBiryukov, swissspidy.
Fixes #16841.

Built from https://develop.svn.wordpress.org/trunk@51943


git-svn-id: http://core.svn.wordpress.org/trunk@51532 1a063a9b-81f0-0310-95a4-ce76da25c4cd
  • Loading branch information
swissspidy committed Oct 27, 2021
1 parent 311cf99 commit a225165
Show file tree
Hide file tree
Showing 7 changed files with 200 additions and 18 deletions.
2 changes: 1 addition & 1 deletion wp-admin/includes/class-wp-posts-list-table.php
Original file line number Diff line number Diff line change
Expand Up @@ -1660,7 +1660,7 @@ public function inline_edit() {
if ( current_user_can( $post_type_object->cap->edit_others_posts ) ) {
$users_opt = array(
'hide_if_only_one_author' => false,
'who' => 'authors',
'capability' => array( $post_type_object->cap->edit_posts ),
'name' => 'post_author',
'class' => 'authors',
'multi' => 1,
Expand Down
4 changes: 3 additions & 1 deletion wp-admin/includes/meta-boxes.php
Original file line number Diff line number Diff line change
Expand Up @@ -903,12 +903,14 @@ function post_slug_meta_box( $post ) {
*/
function post_author_meta_box( $post ) {
global $user_ID;

$post_type_object = get_post_type_object( $post->post_type );
?>
<label class="screen-reader-text" for="post_author_override"><?php _e( 'Author' ); ?></label>
<?php
wp_dropdown_users(
array(
'who' => 'authors',
'capability' => array( $post_type_object->cap->edit_posts ),
'name' => 'post_author_override',
'selected' => empty( $post->ID ) ? $user_ID : $post->post_author,
'include_selected' => true,
Expand Down
23 changes: 16 additions & 7 deletions wp-content/themes/twentyfourteen/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -491,15 +491,24 @@ function twentyfourteen_the_attached_image() {
* @since Twenty Fourteen 1.0
*/
function twentyfourteen_list_authors() {
$contributor_ids = get_users(
array(
'fields' => 'ID',
'orderby' => 'post_count',
'order' => 'DESC',
'who' => 'authors',
)
$args = array(
'fields' => 'ID',
'orderby' => 'post_count',
'order' => 'DESC',
'capability' => array( 'edit_posts' ),
);

/**
* Filters query arguments for listing authors.
*
* @since 3.3
*
* @param array $args Query arguments.
*/
$args = apply_filters( 'twentyfourteen_list_authors_query_args', $args );

$contributor_ids = get_users( $args );

foreach ( $contributor_ids as $contributor_id ) :
$post_count = count_user_posts( $contributor_id );

Expand Down
134 changes: 134 additions & 0 deletions wp-includes/class-wp-user-query.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ public static function fill_query_vars( $args ) {
'role' => '',
'role__in' => array(),
'role__not_in' => array(),
'capability' => '',
'capability__in' => array(),
'capability__not_in' => array(),
'meta_key' => '',
'meta_value' => '',
'meta_compare' => '',
Expand Down Expand Up @@ -133,6 +136,7 @@ public static function fill_query_vars( $args ) {
* querying for all users with using -1.
* @since 4.7.0 Added 'nicename', 'nicename__in', 'nicename__not_in', 'login', 'login__in',
* and 'login__not_in' parameters.
* @since 5.9.0 Added 'capability', 'capability__in', and 'capability__not_in' parameters.
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int $blog_id
Expand All @@ -148,6 +152,19 @@ public static function fill_query_vars( $args ) {
* roles. Default empty array.
* @type string[] $role__not_in An array of role names to exclude. Users matching one or more of these
* roles will not be included in results. Default empty array.
* @type string $capability An array or a comma-separated list of capability names that users must match
* to be included in results. Note that this is an inclusive list: users
* must match *each* capability.
* Does NOT work for capabilities not in the database or filtered via {@see 'map_meta_cap'}.
* Default empty.
* @type string[] $capability__in An array of capability names. Matched users must have at least one of these
* capabilities.
* Does NOT work for capabilities not in the database or filtered via {@see 'map_meta_cap'}.
* Default empty array.
* @type string[] $capability__not_in An array of capability names to exclude. Users matching one or more of these
* capabilities will not be included in results.
* Does NOT work for capabilities not in the database or filtered via {@see 'map_meta_cap'}.
* Default empty array.
* @type string $meta_key User meta key. Default empty.
* @type string $meta_value User meta value. Default empty.
* @type string $meta_compare Comparison operator to test the `$meta_value`. Accepts '=', '!=',
Expand Down Expand Up @@ -320,6 +337,17 @@ public function prepare_query( $query = array() ) {
$this->meta_query->parse_query_vars( $qv );

if ( isset( $qv['who'] ) && 'authors' === $qv['who'] && $blog_id ) {
_deprecated_argument(
'WP_User_Query',
'5.9.0',
sprintf(
/* translators: 1: who, 2: capability */
__( '%1$s is deprecated. Use %2$s instead.' ),
'<code>who</code>',
'<code>capability</code>'
)
);

$who_query = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'user_level',
'value' => 0,
Expand All @@ -343,6 +371,7 @@ public function prepare_query( $query = array() ) {
$this->meta_query->parse_query_vars( $this->meta_query->queries );
}

// Roles.
$roles = array();
if ( isset( $qv['role'] ) ) {
if ( is_array( $qv['role'] ) ) {
Expand All @@ -362,6 +391,111 @@ public function prepare_query( $query = array() ) {
$role__not_in = (array) $qv['role__not_in'];
}

// Capabilities.
$available_roles = array();

if ( ! empty( $qv['capability'] ) || ! empty( $qv['capability__in'] ) || ! empty( $qv['capability__not_in'] ) ) {
global $wp_roles;

$wp_roles->for_site( $blog_id );
$available_roles = $wp_roles->roles;
}

$capabilities = array();
if ( ! empty( $qv['capability'] ) ) {
if ( is_array( $qv['capability'] ) ) {
$capabilities = $qv['capability'];
} elseif ( is_string( $qv['capability'] ) ) {
$capabilities = array_map( 'trim', explode( ',', $qv['capability'] ) );
}
}

$capability__in = array();
if ( ! empty( $qv['capability__in'] ) ) {
$capability__in = (array) $qv['capability__in'];
}

$capability__not_in = array();
if ( ! empty( $qv['capability__not_in'] ) ) {
$capability__not_in = (array) $qv['capability__not_in'];
}

// Keep track of all capabilities and the roles they're added on.
$caps_with_roles = array();

foreach ( $available_roles as $role => $role_data ) {
$role_caps = array_keys( array_filter( $role_data['capabilities'] ) );

foreach ( $capabilities as $cap ) {
if ( in_array( $cap, $role_caps, true ) ) {
$caps_with_roles[ $cap ][] = $role;
break;
}
}

foreach ( $capability__in as $cap ) {
if ( in_array( $cap, $role_caps, true ) ) {
$role__in[] = $role;
break;
}
}

foreach ( $capability__not_in as $cap ) {
if ( in_array( $cap, $role_caps, true ) ) {
$role__not_in[] = $role;
break;
}
}
}

$role__in = array_merge( $role__in, $capability__in );
$role__not_in = array_merge( $role__not_in, $capability__not_in );

$roles = array_unique( $roles );
$role__in = array_unique( $role__in );
$role__not_in = array_unique( $role__not_in );

// Support querying by capabilities added directly to users.
if ( $blog_id && ! empty( $capabilities ) ) {
$capabilities_clauses = array( 'relation' => 'AND' );

foreach ( $capabilities as $cap ) {
$clause = array( 'relation' => 'OR' );

$clause[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'value' => '"' . $cap . '"',
'compare' => 'LIKE',
);

if ( ! empty( $caps_with_roles[ $cap ] ) ) {
foreach ( $caps_with_roles[ $cap ] as $role ) {
$clause[] = array(
'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
'value' => '"' . $role . '"',
'compare' => 'LIKE',
);
}
}

$capabilities_clauses[] = $clause;
}

$role_queries[] = $capabilities_clauses;

if ( empty( $this->meta_query->queries ) ) {
$this->meta_query->queries[] = $capabilities_clauses;
} else {
// Append the cap query to the original queries and reparse the query.
$this->meta_query->queries = array(
'relation' => 'AND',
array( $this->meta_query->queries, array( $capabilities_clauses ) ),
);
}

$this->meta_query->parse_query_vars( $this->meta_query->queries );
}

if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) {
$role_queries = array();

Expand Down
32 changes: 25 additions & 7 deletions wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,15 @@ public function get_items_permissions_check( $request ) {
);
}

// Check if capabilities is specified in GET request and if user can list users.
if ( ! empty( $request['capabilities'] ) && ! current_user_can( 'list_users' ) ) {
return new WP_Error(
'rest_user_cannot_view',
__( 'Sorry, you are not allowed to filter users by capability.' ),
array( 'status' => rest_authorization_required_code() )
);
}

if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) {
return new WP_Error(
'rest_forbidden_context',
Expand Down Expand Up @@ -254,13 +263,14 @@ public function get_items( $request ) {
* present in $registered will be set.
*/
$parameter_mappings = array(
'exclude' => 'exclude',
'include' => 'include',
'order' => 'order',
'per_page' => 'number',
'search' => 'search',
'roles' => 'role__in',
'slug' => 'nicename__in',
'exclude' => 'exclude',
'include' => 'include',
'order' => 'order',
'per_page' => 'number',
'search' => 'search',
'roles' => 'role__in',
'capabilities' => 'capability__in',
'slug' => 'nicename__in',
);

$prepared_args = array();
Expand Down Expand Up @@ -1554,6 +1564,14 @@ public function get_collection_params() {
),
);

$query_params['capabilities'] = array(
'description' => __( 'Limit result set to users matching at least one specific capability provided. Accepts csv list or single capability.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
);

$query_params['who'] = array(
'description' => __( 'Limit result set to users who are considered authors.' ),
'type' => 'string',
Expand Down
21 changes: 20 additions & 1 deletion wp-includes/user.php
Original file line number Diff line number Diff line change
Expand Up @@ -1320,13 +1320,32 @@ function wp_dropdown_users( $args = '' ) {
'role' => '',
'role__in' => array(),
'role__not_in' => array(),
'capability' => '',
'capability__in' => array(),
'capability__not_in' => array(),
);

$defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;

$parsed_args = wp_parse_args( $args, $defaults );

$query_args = wp_array_slice_assoc( $parsed_args, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who', 'role', 'role__in', 'role__not_in' ) );
$query_args = wp_array_slice_assoc(
$parsed_args,
array(
'blog_id',
'include',
'exclude',
'orderby',
'order',
'who',
'role',
'role__in',
'role__not_in',
'capability',
'capability__in',
'capability__not_in',
)
);

$fields = array( 'ID', 'user_login' );

Expand Down
2 changes: 1 addition & 1 deletion wp-includes/version.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '5.9-alpha-51942';
$wp_version = '5.9-alpha-51943';

/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.
Expand Down

0 comments on commit a225165

Please sign in to comment.