Capabilities.php
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * ====================================================================== |
| 5 | * LICENSE: This file is subject to the terms and conditions defined in * |
| 6 | * file 'license.txt', which is part of this source code package. * |
| 7 | * ====================================================================== |
| 8 | */ |
| 9 | |
| 10 | /** |
| 11 | * AAM framework utilities |
| 12 | * |
| 13 | * @package AAM |
| 14 | * |
| 15 | * @version 7.0.0 |
| 16 | */ |
| 17 | class AAM_Framework_Utility_Capabilities implements AAM_Framework_Utility_Interface |
| 18 | { |
| 19 | |
| 20 | use AAM_Framework_Utility_BaseTrait; |
| 21 | |
| 22 | /** |
| 23 | * Determine the max user level based on provided array of capabilities |
| 24 | * |
| 25 | * @param array $caps |
| 26 | * |
| 27 | * @return int |
| 28 | * @access public |
| 29 | * |
| 30 | * @version 7.0.0 |
| 31 | */ |
| 32 | public function get_max_user_level($caps) |
| 33 | { |
| 34 | $max = 0; |
| 35 | |
| 36 | if (is_array($caps)) { |
| 37 | foreach ($caps as $cap => $granted) { |
| 38 | if (!empty($granted) && (strpos($cap, 'level_') === 0)) { |
| 39 | $level = intval(substr($cap, 6)); |
| 40 | $max = ($max < $level ? $level : $max); |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | return intval($max); |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Get list of all known capabilities |
| 50 | * |
| 51 | * This method returns the combined list of all registered capabilities on the |
| 52 | * role level as well as caps for the currently logged in user. |
| 53 | * |
| 54 | * @param WP_User|int $user [Optional] |
| 55 | * |
| 56 | * @return array |
| 57 | * @access public |
| 58 | * |
| 59 | * @version 7.0.0 |
| 60 | */ |
| 61 | public function get_all_caps($user = null) |
| 62 | { |
| 63 | $result = []; |
| 64 | |
| 65 | foreach (wp_roles()->role_objects as $role) { |
| 66 | if (is_array($role->capabilities)) { |
| 67 | $result = array_merge($result, array_keys($role->capabilities)); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // Also get the list of all capabilities assigned directly to user |
| 72 | if (is_numeric($user)) { |
| 73 | $user = get_user_by('id', $user); |
| 74 | } |
| 75 | |
| 76 | if (is_a($user, WP_User::class)) { |
| 77 | $result = array_merge($result, array_keys($user->allcaps)); |
| 78 | } |
| 79 | |
| 80 | return array_unique($result); |
| 81 | } |
| 82 | |
| 83 | /** |
| 84 | * Check if capability exists |
| 85 | * |
| 86 | * @param string $capability |
| 87 | * |
| 88 | * @return bool |
| 89 | * @access public |
| 90 | * |
| 91 | * @version 7.0.0 |
| 92 | */ |
| 93 | public function exists($capability) |
| 94 | { |
| 95 | return in_array($capability, $this->get_all_caps(), true); |
| 96 | } |
| 97 | |
| 98 | } |