| 1 |
<?php |
| 2 |
|
| 3 |
namespace Yoast\WP\SEO\Helpers; |
| 4 |
|
| 5 |
/** |
| 6 |
* A helper object for user capabilities. |
| 7 |
*/ |
| 8 |
class Capability_Helper { |
| 9 |
|
| 10 |
/** |
| 11 |
* Checks if the user has at least one of the proper capabilities. |
| 12 |
* |
| 13 |
* @param string $capability Capability to check. |
| 14 |
* |
| 15 |
* @return bool True if the user has at least one of the proper rights. |
| 16 |
*/ |
| 17 |
public function current_user_can( $capability ) { |
| 18 |
if ( $capability === 'wpseo_manage_options' ) { |
| 19 |
return \current_user_can( $capability ); |
| 20 |
} |
| 21 |
|
| 22 |
return $this->has_any( [ 'wpseo_manage_options', $capability ] ); |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* Retrieves the users that have the specified capability. |
| 27 |
* |
| 28 |
* @param string $capability The name of the capability. |
| 29 |
* |
| 30 |
* @return array The users that have the capability. |
| 31 |
*/ |
| 32 |
public function get_applicable_users( $capability ) { |
| 33 |
$applicable_roles = $this->get_applicable_roles( $capability ); |
| 34 |
|
| 35 |
if ( $applicable_roles === [] ) { |
| 36 |
return []; |
| 37 |
} |
| 38 |
|
| 39 |
return \get_users( [ 'role__in' => $applicable_roles ] ); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Retrieves the roles that have the specified capability. |
| 44 |
* |
| 45 |
* @param string $capability The name of the capability. |
| 46 |
* |
| 47 |
* @return array The names of the roles that have the capability. |
| 48 |
*/ |
| 49 |
public function get_applicable_roles( $capability ) { |
| 50 |
$roles = \wp_roles(); |
| 51 |
$role_names = $roles->get_names(); |
| 52 |
|
| 53 |
$applicable_roles = []; |
| 54 |
foreach ( \array_keys( $role_names ) as $role_name ) { |
| 55 |
$role = $roles->get_role( $role_name ); |
| 56 |
|
| 57 |
if ( ! $role ) { |
| 58 |
continue; |
| 59 |
} |
| 60 |
|
| 61 |
// Add role if it has the capability. |
| 62 |
if ( \array_key_exists( $capability, $role->capabilities ) && $role->capabilities[ $capability ] === true ) { |
| 63 |
$applicable_roles[] = $role_name; |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
return $applicable_roles; |
| 68 |
} |
| 69 |
|
| 70 |
/** |
| 71 |
* Checks if the current user has at least one of the supplied capabilities. |
| 72 |
* |
| 73 |
* @param array $capabilities Capabilities to check against. |
| 74 |
* |
| 75 |
* @return bool True if the user has at least one capability. |
| 76 |
*/ |
| 77 |
private function has_any( array $capabilities ) { |
| 78 |
foreach ( $capabilities as $capability ) { |
| 79 |
if ( \current_user_can( $capability ) ) { |
| 80 |
return true; |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
return false; |
| 85 |
} |
| 86 |
} |
| 87 |
|