| 1 |
<?php |
| 2 |
/** |
| 3 |
* A user roles class for Jetpack. |
| 4 |
* |
| 5 |
* @package automattic/jetpack-roles |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Automattic\Jetpack; |
| 9 |
|
| 10 |
/** |
| 11 |
* Class Automattic\Jetpack\Roles |
| 12 |
* |
| 13 |
* Contains utilities for translating user roles to capabilities and vice versa. |
| 14 |
*/ |
| 15 |
class Roles { |
| 16 |
/** |
| 17 |
* Map of roles we care about, and their corresponding minimum capabilities. |
| 18 |
* |
| 19 |
* @access protected |
| 20 |
* |
| 21 |
* @var array |
| 22 |
*/ |
| 23 |
protected $capability_translations = array( |
| 24 |
'administrator' => 'manage_options', |
| 25 |
'editor' => 'edit_others_posts', |
| 26 |
'author' => 'publish_posts', |
| 27 |
'contributor' => 'edit_posts', |
| 28 |
'subscriber' => 'read', |
| 29 |
); |
| 30 |
|
| 31 |
/** |
| 32 |
* Get the role of the current user. |
| 33 |
* |
| 34 |
* @access public |
| 35 |
* |
| 36 |
* @return string|boolean Current user's role, false if not enough capabilities for any of the roles. |
| 37 |
*/ |
| 38 |
public function translate_current_user_to_role() { |
| 39 |
foreach ( $this->capability_translations as $role => $cap ) { |
| 40 |
if ( current_user_can( $role ) || current_user_can( $cap ) ) { |
| 41 |
return $role; |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
return false; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Get the role of a particular user. |
| 50 |
* |
| 51 |
* @access public |
| 52 |
* |
| 53 |
* @param \WP_User $user User object. |
| 54 |
* @return string|boolean User's role, false if not enough capabilities for any of the roles. |
| 55 |
*/ |
| 56 |
public function translate_user_to_role( $user ) { |
| 57 |
foreach ( $this->capability_translations as $role => $cap ) { |
| 58 |
if ( user_can( $user, $role ) || user_can( $user, $cap ) ) { |
| 59 |
return $role; |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
return false; |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Get the minimum capability for a role. |
| 68 |
* |
| 69 |
* @access public |
| 70 |
* |
| 71 |
* @param string $role Role name. |
| 72 |
* @return string|boolean Capability, false if role isn't mapped to any capabilities. |
| 73 |
*/ |
| 74 |
public function translate_role_to_cap( $role ) { |
| 75 |
if ( ! isset( $this->capability_translations[ $role ] ) ) { |
| 76 |
return false; |
| 77 |
} |
| 78 |
|
| 79 |
return $this->capability_translations[ $role ]; |
| 80 |
} |
| 81 |
} |
| 82 |
|