Merge pull request #17926 from civicrm/5.28
[civicrm-core.git] / CRM / Core / Permission / Temp.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This supplements the permissions of the CMS system, allowing us
20 * to temporarily acknowledge permission grants for API keys.
21 *
22 * In normal usage, the class isn't even instantiated - it's only
23 * used when processing certain API backends.
24 */
25 class CRM_Core_Permission_Temp {
26 public static $id = 0;
27
28 /**
29 * Array(int $grantId => array($perm))
30 *
31 * @var array
32 */
33 private $grants;
34
35 /**
36 * Array ($perm => 1);
37 * @var array
38 */
39 private $idx;
40
41 /**
42 * Grant permissions temporarily.
43 *
44 * @param string|array $perms
45 * List of permissions to apply.
46 * @return string|int
47 * A handle for the grant. Useful for revoking later on.
48 */
49 public function grant($perms) {
50 $perms = (array) $perms;
51 $id = self::$id++;
52 $this->grants[$id] = $perms;
53 $this->idx = $this->index($this->grants);
54 return $id;
55 }
56
57 /**
58 * Revoke a previously granted permission.
59 *
60 * @param string|int $id
61 * The handle previously returned by grant().
62 */
63 public function revoke($id) {
64 unset($this->grants[$id]);
65 $this->idx = $this->index($this->grants);
66 }
67
68 /**
69 * Determine if a permission has been granted.
70 *
71 * @param string $perm
72 * The permission name (e.g. "view all contacts").
73 * @return bool
74 */
75 public function check($perm) {
76 return (isset($this->idx['administer CiviCRM']) || isset($this->idx[$perm]));
77 }
78
79 /**
80 * Generate an optimized index of granted permissions.
81 *
82 * @param array $grants
83 * Array(string $permName).
84 * @return array
85 * Array(string $permName => bool $granted).
86 */
87 protected function index($grants) {
88 $idx = [];
89 foreach ($grants as $grant) {
90 foreach ($grant as $perm) {
91 $idx[$perm] = 1;
92 }
93 }
94 return $idx;
95 }
96
97 }