WordPress.org

Make WordPress Core

Opened 4 years ago

Closed 3 years ago

#14602 closed enhancement (fixed)

Create user_can, refactor current_user_can, author_can, current_user_can_for_blog

Reported by: simonwheatley Owned by:
Milestone: 3.1 Priority: normal
Severity: normal Version: 3.0.1
Component: Role/Capability Keywords: has-patch needs-testing
Focuses: Cc:

Description

Currently we have no function to pass a user ID and a capability/rolewhich will return whether the user can perform that role or has that capability. Further, the functions current_user_can, author_can, and current_user_can_for_blog have some code duplication.

I suggest adding a new function user_can, which accepts any user_ID or a user object and a capability, and returns a boolean. The other *_can* functions can then be refactored to use the new function.

See attached patch.

Attachments (1)

user_can.diff (1.6 KB) - added by simonwheatley 4 years ago.
Now using ! is_object() instead of is_int

Download all attachments as: .zip

Change History (8)

comment:1 simonwheatley4 years ago

Looking at the current patch I wonder whether the is_int check in the first line of the new user_can function ought to be more like this:

function user_can( $user, $capability ) {
	if ( ! is_object( $user ) )
		$user = new WP_User( (int) $user );
	
	if ( ! $user || ! $user->ID )
		return false;

	$args = array_slice( func_get_args(), 2 );
	$args = array_merge( array( $capability ), $args );

	return call_user_func_array( array( &$user, 'has_cap' ), $args );
}

comment:2 follow-up: scribu4 years ago

  • Component changed from Users to Role/Capability
  • Milestone changed from Awaiting Review to 3.1

Looking good. +1

comment:3 scribu4 years ago

But I think you should drop the * @author Simon Wheatley from the docblock.

comment:4 in reply to: ↑ 2 ; follow-up: simonwheatley4 years ago

Replying to scribu:

Looking good. +1

Should the user_can function be using get_userdata rather than instantiating a new WP_User object every time, so it takes advantage of the cache?

simonwheatley4 years ago

Now using ! is_object() instead of is_int

comment:5 in reply to: ↑ 4 scribu4 years ago

Replying to simonwheatley:

Replying to scribu:

Looking good. +1

Should the user_can function be using get_userdata rather than instantiating a new WP_User object every time, so it takes advantage of the cache?

No, because WP_User calls get_userdata() internally.

comment:6 ryan3 years ago

I think each of these functions still need to get the args, slice, merge, and call_user_func_array() so that the extra args aren't dropped. After doing all that has_cap should be called directly rather than going through user_can() and doing the same thing again.

comment:7 automattor3 years ago

  • Resolution set to fixed
  • Status changed from new to closed

(In [16209]) Introduce user_can(). Props simonwheatley. fixes #14602

Note: See TracTickets for help on using tickets.