Merge pull request #15815 from artfulrobot/issue-1108-fix-unsubscribe
[civicrm-core.git] / CRM / Core / Permission / Drupal8.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 * $Id$
17 *
18 */
19
20 /**
21 *
22 */
23 class CRM_Core_Permission_Drupal8 extends CRM_Core_Permission_DrupalBase {
24
25 /**
26 * Given a permission string, check for access requirements
27 *
28 * @param string $str
29 * The permission to check.
30 *
31 * @param int $userId
32 *
33 * @return bool
34 */
35 public function check($str, $userId = NULL) {
36 $str = $this->translatePermission($str, 'Drupal', [
37 'view user account' => 'access user profiles',
38 ]);
39
40 if ($str == CRM_Core_Permission::ALWAYS_DENY_PERMISSION) {
41 return FALSE;
42 }
43 if ($str == CRM_Core_Permission::ALWAYS_ALLOW_PERMISSION) {
44 return TRUE;
45 }
46 $acct = $userId ? \Drupal\user\Entity\User::load($userId) : \Drupal::currentUser();
47 return $acct->hasPermission($str);
48 }
49
50 /**
51 * Get all the contact emails for users that have a specific permission.
52 *
53 * @param string $permissionName
54 * Name of the permission we are interested in.
55 *
56 * @return string
57 * a comma separated list of email addresses
58 */
59 public function permissionEmails($permissionName) {
60 static $_cache = [];
61
62 if (isset($_cache[$permissionName])) {
63 return $_cache[$permissionName];
64 }
65
66 $role_ids = array_map(
67 function (\Drupal\user\RoleInterface $role) {
68 return $role->id();
69 }, user_roles(TRUE, $permissionName)
70 );
71 $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(['roles' => $role_ids]);
72 $uids = array_keys($users);
73
74 $_cache[$permissionName] = self::getContactEmails($uids);
75 return $_cache[$permissionName];
76 }
77
78 /**
79 * @inheritDoc
80 */
81 public function upgradePermissions($permissions) {
82 $civicrm_perms = array_keys(CRM_Core_Permission::getCorePermissions());
83 if (empty($civicrm_perms)) {
84 throw new CRM_Core_Exception("Cannot upgrade permissions: permission list missing");
85 }
86
87 $roles = user_roles(TRUE);
88 foreach ($roles as $role) {
89 foreach ($civicrm_perms as $permission) {
90 $role->revokePermission($permission);
91 }
92 }
93 }
94
95 }