47b0350d7b8e8d0bbd526e7c594dc1021688f24c
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This is the basic permission class wrapper
21 class CRM_Core_Permission
{
24 * Static strings used to compose permissions.
29 const EDIT_GROUPS
= 'edit contacts in ', VIEW_GROUPS
= 'view contacts in ';
32 * The various type of permissions.
36 const EDIT
= 1, VIEW
= 2, DELETE
= 3, CREATE
= 4, SEARCH
= 5, ALL
= 6, ADMIN
= 7;
39 * A placeholder permission which always fails.
41 const ALWAYS_DENY_PERMISSION
= "*always deny*";
44 * A placeholder permission which always fails.
46 const ALWAYS_ALLOW_PERMISSION
= "*always allow*";
49 * Various authentication sources.
53 const AUTH_SRC_UNKNOWN
= 0, AUTH_SRC_CHECKSUM
= 1, AUTH_SRC_SITEKEY
= 2, AUTH_SRC_LOGIN
= 4;
56 * Get the current permission of this user.
59 * the permission of the user (edit or view or null)
61 public static function getPermission() {
62 $config = CRM_Core_Config
::singleton();
63 return $config->userPermissionClass
->getPermission();
67 * Given a permission string or array, check for access requirements
69 * Ex 1: Must have 'access CiviCRM'
70 * (string) 'access CiviCRM'
72 * Ex 2: Must have 'access CiviCRM' and 'access AJAX API'
73 * ['access CiviCRM', 'access AJAX API']
75 * Ex 3: Must have 'access CiviCRM' or 'access AJAX API'
77 * ['access CiviCRM', 'access AJAX API'],
80 * Ex 4: Must have 'access CiviCRM' or 'access AJAX API' AND 'access CiviEvent'
82 * ['access CiviCRM', 'access AJAX API'],
86 * Note that in permissions.php this is keyed by the action eg.
87 * (access Civi || access AJAX) && (access CiviEvent || access CiviContribute)
89 * ['access CiviCRM', 'access AJAX API'],
90 * ['access CiviEvent', 'access CiviContribute']
93 * @param string|array $permissions
94 * The permission to check as an array or string -see examples.
96 * @param int $contactId
97 * Contact id to check permissions for. Defaults to current logged-in user.
100 * true if contact has permission(s), else false
102 public static function check($permissions, $contactId = NULL) {
103 $permissions = (array) $permissions;
104 $userId = CRM_Core_BAO_UFMatch
::getUFId($contactId);
106 /** @var CRM_Core_Permission_Temp $tempPerm */
107 $tempPerm = CRM_Core_Config
::singleton()->userPermissionTemp
;
109 foreach ($permissions as $permission) {
110 if (is_array($permission)) {
111 foreach ($permission as $orPerm) {
112 if (self
::check($orPerm, $contactId)) {
113 //one of our 'or' permissions has succeeded - stop checking this permission
117 //none of our our conditions was met
121 // This is an individual permission
122 $impliedPermissions = self
::getImpliedPermissionsFor($permission);
123 $impliedPermissions[] = $permission;
124 foreach ($impliedPermissions as $permissionOption) {
125 $granted = CRM_Core_Config
::singleton()->userPermissionClass
->check($permissionOption, $userId);
126 // Call the permission_check hook to permit dynamic escalation (CRM-19256)
127 CRM_Utils_Hook
::permission_check($permissionOption, $granted, $contactId);
135 && !($tempPerm && $tempPerm->check($permission))
137 //one of our 'and' conditions has not been met
146 * Determine if any one of the permissions strings applies to current user.
148 * @param array $perms
151 public static function checkAnyPerm($perms) {
152 foreach ($perms as $perm) {
153 if (CRM_Core_Permission
::check($perm)) {
161 * Given a group/role array, check for access requirements
163 * @param array $array
164 * The group/role to check.
167 * true if yes, else false
169 public static function checkGroupRole($array) {
170 $config = CRM_Core_Config
::singleton();
171 return $config->userPermissionClass
->checkGroupRole($array);
175 * Get the permissioned where clause for the user.
178 * The type of permission needed.
179 * @param array $tables
180 * (reference ) add the tables that are needed for the select clause.
181 * @param array $whereTables
182 * (reference ) add the tables that are needed for the where clause.
185 * the group where clause for this user
187 public static function getPermissionedStaticGroupClause($type, &$tables, &$whereTables) {
188 $config = CRM_Core_Config
::singleton();
189 return $config->userPermissionClass
->getPermissionedStaticGroupClause($type, $tables, $whereTables);
193 * Get all groups from database, filtered by permissions
196 * @param string $groupType
197 * Type of group(Access/Mailing).
198 * @param bool $excludeHidden
199 * exclude hidden groups.
203 * array reference of all groups.
205 public static function group($groupType, $excludeHidden = TRUE) {
206 $config = CRM_Core_Config
::singleton();
207 return $config->userPermissionClass
->group($groupType, $excludeHidden);
214 public static function customGroupAdmin($userId = NULL) {
215 // check if user has all powerful permission
216 // or administer civicrm permission (CRM-1905)
217 if (self
::check('access all custom data', $userId)) {
222 self
::check('administer Multiple Organizations', $userId) &&
223 self
::isMultisiteEnabled()
228 if (self
::check('administer CiviCRM data', $userId)) {
242 public static function customGroup($type = CRM_Core_Permission
::VIEW
, $reset = FALSE, $userId = NULL) {
243 $customGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_CustomField', 'custom_group_id',
244 ['fresh' => $reset]);
247 // check if user has all powerful permission
248 // or administer civicrm permission (CRM-1905)
249 if (self
::customGroupAdmin($userId)) {
250 return array_keys($customGroups);
253 return CRM_ACL_API
::group($type, $userId, 'civicrm_custom_group', $customGroups, $defaultGroups);
258 * @param string|null $prefix
263 public static function customGroupClause($type = CRM_Core_Permission
::VIEW
, $prefix = NULL, $reset = FALSE) {
264 if (self
::customGroupAdmin()) {
268 $groups = self
::customGroup($type, $reset);
269 if (empty($groups)) {
273 return "{$prefix}id IN ( " . implode(',', $groups) . ' ) ';
283 public static function ufGroupValid($gid, $type = CRM_Core_Permission
::VIEW
) {
288 $groups = self
::ufGroup($type);
289 return !empty($groups) && in_array($gid, $groups);
297 public static function ufGroup($type = CRM_Core_Permission
::VIEW
) {
298 $ufGroups = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_UFField', 'uf_group_id');
300 $allGroups = array_keys($ufGroups);
302 // check if user has all powerful permission
303 if (self
::check('profile listings and forms')) {
308 case CRM_Core_Permission
::VIEW
:
309 if (self
::check('profile view')) {
314 case CRM_Core_Permission
::CREATE
:
315 if (self
::check('profile create')) {
320 case CRM_Core_Permission
::EDIT
:
321 if (self
::check('profile edit')) {
326 case CRM_Core_Permission
::SEARCH
:
327 if (self
::check('profile listings')) {
333 return CRM_ACL_API
::group($type, NULL, 'civicrm_uf_group', $ufGroups);
338 * @param string $prefix
339 * @param bool $returnUFGroupIds
341 * @return array|string
343 public static function ufGroupClause($type = CRM_Core_Permission
::VIEW
, $prefix = NULL, $returnUFGroupIds = FALSE) {
344 $groups = self
::ufGroup($type);
345 if ($returnUFGroupIds) {
348 elseif (empty($groups)) {
352 return "{$prefix}id IN ( " . implode(',', $groups) . ' ) ';
358 * @param int $eventID
359 * @param string $context
363 public static function event($type = CRM_Core_Permission
::VIEW
, $eventID = NULL, $context = '') {
364 if (!empty($context)) {
365 if (CRM_Core_Permission
::check($context)) {
369 $events = CRM_Event_PseudoConstant
::event(NULL, TRUE);
372 // check if user has all powerful permission
373 if (self
::check('register for events')) {
374 $includeEvents = array_keys($events);
377 if ($type == CRM_Core_Permission
::VIEW
&&
378 self
::check('view event info')
380 $includeEvents = array_keys($events);
383 $permissionedEvents = CRM_ACL_API
::group($type, NULL, 'civicrm_event', $events, $includeEvents);
385 return $permissionedEvents;
387 if (!empty($permissionedEvents)) {
388 return array_search($eventID, $permissionedEvents) === FALSE ?
NULL : $eventID;
395 * @param null $prefix
399 public static function eventClause($type = CRM_Core_Permission
::VIEW
, $prefix = NULL) {
400 $events = self
::event($type);
401 if (empty($events)) {
405 return "{$prefix}id IN ( " . implode(',', $events) . ' ) ';
410 * Checks that component is enabled and optionally that user has basic perm.
412 * @param string $module
413 * Specifies the name of the CiviCRM component.
414 * @param bool $checkPermission
415 * Check not only that module is enabled, but that user has necessary
417 * @param bool $requireAllCasesPermOnCiviCase
418 * Significant only if $module == CiviCase
419 * Require "access all cases and activities", not just
420 * "access my cases and activities".
423 * Access to specified $module is granted.
425 public static function access($module, $checkPermission = TRUE, $requireAllCasesPermOnCiviCase = FALSE) {
426 $config = CRM_Core_Config
::singleton();
428 if (!in_array($module, $config->enableComponents
)) {
432 if ($checkPermission) {
435 $access_all_cases = CRM_Core_Permission
::check("access all cases and activities");
436 $access_my_cases = CRM_Core_Permission
::check("access my cases and activities");
437 return $access_all_cases ||
(!$requireAllCasesPermOnCiviCase && $access_my_cases);
440 return CRM_Core_Permission
::check("administer $module");
443 return CRM_Core_Permission
::check("access $module");
451 * Check permissions for delete and edit actions.
453 * @param string $module
456 * Action to be check across component.
461 public static function checkActionPermission($module, $action) {
462 //check delete related permissions.
463 if ($action & CRM_Core_Action
::DELETE
) {
464 $permissionName = "delete in $module";
468 'CiviEvent' => 'edit event participants',
469 'CiviMember' => 'edit memberships',
470 'CiviPledge' => 'edit pledges',
471 'CiviContribute' => 'edit contributions',
472 'CiviGrant' => 'edit grants',
473 'CiviMail' => 'access CiviMail',
474 'CiviAuction' => 'add auction items',
476 $permissionName = $editPermissions[$module] ??
NULL;
479 if ($module == 'CiviCase' && !$permissionName) {
480 return CRM_Case_BAO_Case
::accessCiviCase();
483 //check for permission.
484 return CRM_Core_Permission
::check($permissionName);
494 public static function checkMenu(&$args, $op = 'and') {
495 if (!is_array($args)) {
498 foreach ($args as $str) {
499 $res = CRM_Core_Permission
::check($str);
500 if ($op == 'or' && $res) {
503 elseif ($op == 'and' && !$res) {
507 return ($op == 'or') ?
FALSE : TRUE;
516 public static function checkMenuItem(&$item) {
517 if (!array_key_exists('access_callback', $item)) {
518 CRM_Core_Error
::backtrace();
519 throw new CRM_Core_Exception('Missing Access Callback key in menu item');
522 // if component_id is present, ensure it is enabled
523 if (isset($item['component_id']) && $item['component_id']) {
524 if (!isset(Civi
::$statics[__CLASS__
]['componentNameId'])) {
525 Civi
::$statics[__CLASS__
]['componentNameId'] = array_flip(CRM_Core_Component
::getComponentIDs());
527 $componentName = Civi
::$statics[__CLASS__
]['componentNameId'][$item['component_id']];
529 $config = CRM_Core_Config
::singleton();
530 if (is_array($config->enableComponents
) && in_array($componentName, $config->enableComponents
)) {
531 // continue with process
538 // the following is imitating drupal 6 code in includes/menu.inc
539 if (empty($item['access_callback']) ||
540 is_numeric($item['access_callback'])
542 return (bool) $item['access_callback'];
545 // check whether the following Ajax requests submitted the right key
546 // FIXME: this should be integrated into ACLs proper
547 if (CRM_Utils_Array
::value('page_type', $item) == 3) {
548 if (!CRM_Core_Key
::validate($_REQUEST['key'], $item['path'])) {
553 // check if callback is for checkMenu, if so optimize it
554 if (is_array($item['access_callback']) &&
555 $item['access_callback'][0] == 'CRM_Core_Permission' &&
556 $item['access_callback'][1] == 'checkMenu'
558 $op = CRM_Utils_Array
::value(1, $item['access_arguments'], 'and');
559 return self
::checkMenu($item['access_arguments'][0], $op);
562 return call_user_func_array($item['access_callback'], $item['access_arguments']);
568 * Include disabled components
569 * @param bool $descriptions
570 * Whether to return descriptions
574 public static function basicPermissions($all = FALSE, $descriptions = FALSE) {
575 $cacheKey = implode('-', [$all, $descriptions]);
576 if (empty(Civi
::$statics[__CLASS__
][__FUNCTION__
][$cacheKey])) {
577 Civi
::$statics[__CLASS__
][__FUNCTION__
][$cacheKey] = self
::assembleBasicPermissions($all, $descriptions);
579 return Civi
::$statics[__CLASS__
][__FUNCTION__
][$cacheKey];
584 * @param bool $descriptions
585 * whether to return descriptions
588 * @throws \CRM_Core_Exception
590 public static function assembleBasicPermissions($all = FALSE, $descriptions = FALSE): array {
591 $permissions = self
::getCoreAndComponentPermissions($all);
593 // Add any permissions defined in hook_civicrm_permission implementations.
594 $module_permissions = CRM_Core_Config
::singleton()->userPermissionClass
->getAllModulePermissions(TRUE);
595 $permissions = array_merge($permissions, $module_permissions);
596 if (!$descriptions) {
597 foreach ($permissions as $name => $attr) {
598 $permissions[$name] = array_shift($attr);
607 public static function getAnonymousPermissionsWarnings() {
608 static $permissions = [];
609 if (empty($permissions)) {
611 'administer CiviCRM',
613 $components = CRM_Core_Component
::getComponents();
614 foreach ($components as $comp) {
615 if (!method_exists($comp, 'getAnonymousPermissionWarnings')) {
618 $permissions = array_merge($permissions, $comp->getAnonymousPermissionWarnings());
625 * @param $anonymous_perms
629 public static function validateForPermissionWarnings($anonymous_perms) {
630 return array_intersect($anonymous_perms, self
::getAnonymousPermissionsWarnings());
634 * Get core permissions.
638 public static function getCorePermissions() {
639 $prefix = ts('CiviCRM') . ': ';
642 $prefix . ts('add contacts'),
643 ts('Create a new contact record in CiviCRM'),
645 'view all contacts' => [
646 $prefix . ts('view all contacts'),
647 ts('View ANY CONTACT in the CiviCRM database, export contact info and perform activities such as Send Email, Phone Call, etc.'),
649 'edit all contacts' => [
650 $prefix . ts('edit all contacts'),
651 ts('View, Edit and Delete ANY CONTACT in the CiviCRM database; Create and edit relationships, tags and other info about the contacts'),
653 'view my contact' => [
654 $prefix . ts('view my contact'),
656 'edit my contact' => [
657 $prefix . ts('edit my contact'),
659 'delete contacts' => [
660 $prefix . ts('delete contacts'),
662 'access deleted contacts' => [
663 $prefix . ts('access deleted contacts'),
664 ts('Access contacts in the trash'),
666 'import contacts' => [
667 $prefix . ts('import contacts'),
668 ts('Import contacts and activities'),
670 'import SQL datasource' => [
671 $prefix . ts('import SQL datasource'),
672 ts('When importing, consume data directly from a SQL datasource'),
675 $prefix . ts('edit groups'),
676 ts('Create new groups, edit group settings (e.g. group name, visibility...), delete groups'),
678 'administer CiviCRM' => [
679 $prefix . ts('administer CiviCRM'),
680 ts('Perform all tasks in the Administer CiviCRM control panel and Import Contacts'),
682 'skip IDS check' => [
683 $prefix . ts('skip IDS check'),
684 ts('Warning: Give to trusted roles only; this permission has security implications. IDS system is bypassed for users with this permission. Prevents false errors for admin users.'),
686 'access uploaded files' => [
687 $prefix . ts('access uploaded files'),
688 ts('View / download files including images and photos'),
690 'profile listings and forms' => [
691 $prefix . ts('profile listings and forms'),
692 ts('Warning: Give to trusted roles only; this permission has privacy implications. Add/edit data in online forms and access public searchable directories.'),
694 'profile listings' => [
695 $prefix . ts('profile listings'),
696 ts('Warning: Give to trusted roles only; this permission has privacy implications. Access public searchable directories.'),
698 'profile create' => [
699 $prefix . ts('profile create'),
700 ts('Add data in a profile form.'),
703 $prefix . ts('profile edit'),
704 ts('Edit data in a profile form.'),
707 $prefix . ts('profile view'),
708 ts('View data in a profile.'),
710 'access all custom data' => [
711 $prefix . ts('access all custom data'),
712 ts('View all custom fields regardless of ACL rules'),
714 'view all activities' => [
715 $prefix . ts('view all activities'),
716 ts('View all activities (for visible contacts)'),
718 'delete activities' => [
719 $prefix . ts('Delete activities'),
721 'edit inbound email basic information' => [
722 $prefix . ts('edit inbound email basic information'),
723 ts('Edit all inbound email activities (for visible contacts) basic information. Content editing not allowed.'),
725 'edit inbound email basic information and content' => [
726 $prefix . ts('edit inbound email basic information and content'),
727 ts('Edit all inbound email activities (for visible contacts) basic information and content.'),
729 'access CiviCRM' => [
730 $prefix . ts('access CiviCRM backend and API'),
731 ts('Master control for access to the main CiviCRM backend and API. Give to trusted roles only.'),
733 'access Contact Dashboard' => [
734 $prefix . ts('access Contact Dashboard'),
735 ts('View Contact Dashboard (for themselves and visible contacts)'),
737 'translate CiviCRM' => [
738 $prefix . ts('translate CiviCRM'),
739 ts('Allow User to enable multilingual'),
742 $prefix . ts('manage tags'),
743 ts('Create and rename tags'),
745 'administer reserved groups' => [
746 $prefix . ts('administer reserved groups'),
747 ts('Edit and disable Reserved Groups (Needs Edit Groups)'),
749 'administer Tagsets' => [
750 $prefix . ts('administer Tagsets'),
752 'administer reserved tags' => [
753 $prefix . ts('administer reserved tags'),
755 'administer queues' => [
756 $prefix . ts('administer queues'),
757 ts('Initialize, browse, and cancel background processing queues'),
758 // At time of writing, we have specifically omitted the ability to edit fine-grained
759 // data about specific queue-tasks. Tasks are usually defined as PHP callables...
760 // and one should hesitate before allowing open-ended edits of PHP callables.
761 // However, it seems fine for web-admins to browse and cancel these things.
763 'administer dedupe rules' => [
764 $prefix . ts('administer dedupe rules'),
765 ts('Create and edit rules, change the supervised and unsupervised rules'),
767 'merge duplicate contacts' => [
768 $prefix . ts('merge duplicate contacts'),
769 ts('Delete Contacts must also be granted in order for this to work.'),
771 'force merge duplicate contacts' => [
772 $prefix . ts('force merge duplicate contacts'),
773 ts('Delete Contacts must also be granted in order for this to work.'),
775 'view debug output' => [
776 $prefix . ts('view debug output'),
777 ts('View results of debug and backtrace'),
780 'view all notes' => [
781 $prefix . ts('view all notes'),
782 ts("View notes (for visible contacts) even if they're marked admin only"),
784 'add contact notes' => [
785 $prefix . ts('add contact notes'),
786 ts("Create notes for contacts"),
788 'access AJAX API' => [
789 $prefix . ts('access AJAX API'),
790 ts('Allow API access even if Access CiviCRM is not granted'),
792 'access contact reference fields' => [
793 $prefix . ts('access contact reference fields'),
794 ts('Allow entering data into contact reference fields'),
796 'create manual batch' => [
797 $prefix . ts('create manual batch'),
798 ts('Create an accounting batch (with Access to CiviContribute and View Own/All Manual Batches)'),
800 'edit own manual batches' => [
801 $prefix . ts('edit own manual batches'),
802 ts('Edit accounting batches created by user'),
804 'edit all manual batches' => [
805 $prefix . ts('edit all manual batches'),
806 ts('Edit all accounting batches'),
808 'close own manual batches' => [
809 $prefix . ts('close own manual batches'),
810 ts('Close accounting batches created by user (with Access to CiviContribute)'),
812 'close all manual batches' => [
813 $prefix . ts('close all manual batches'),
814 ts('Close all accounting batches (with Access to CiviContribute)'),
816 'reopen own manual batches' => [
817 $prefix . ts('reopen own manual batches'),
818 ts('Reopen accounting batches created by user (with Access to CiviContribute)'),
820 'reopen all manual batches' => [
821 $prefix . ts('reopen all manual batches'),
822 ts('Reopen all accounting batches (with Access to CiviContribute)'),
824 'view own manual batches' => [
825 $prefix . ts('view own manual batches'),
826 ts('View accounting batches created by user (with Access to CiviContribute)'),
828 'view all manual batches' => [
829 $prefix . ts('view all manual batches'),
830 ts('View all accounting batches (with Access to CiviContribute)'),
832 'delete own manual batches' => [
833 $prefix . ts('delete own manual batches'),
834 ts('Delete accounting batches created by user'),
836 'delete all manual batches' => [
837 $prefix . ts('delete all manual batches'),
838 ts('Delete all accounting batches'),
840 'export own manual batches' => [
841 $prefix . ts('export own manual batches'),
842 ts('Export accounting batches created by user'),
844 'export all manual batches' => [
845 $prefix . ts('export all manual batches'),
846 ts('Export all accounting batches'),
848 'administer payment processors' => [
849 $prefix . ts('administer payment processors'),
850 ts('Add, Update, or Disable Payment Processors'),
852 'render templates' => [
853 $prefix . ts('render templates'),
854 ts('Render open-ended template content. (Additional constraints may apply to autoloaded records and specific notations.)'),
856 'edit message templates' => [
857 $prefix . ts('edit message templates'),
859 'edit system workflow message templates' => [
860 $prefix . ts('edit system workflow message templates'),
862 'edit user-driven message templates' => [
863 $prefix . ts('edit user-driven message templates'),
865 'view my invoices' => [
866 $prefix . ts('view my invoices'),
867 ts('Allow users to view/ download their own invoices'),
870 $prefix . ts('edit api keys'),
873 'edit own api keys' => [
874 $prefix . ts('edit own api keys'),
875 ts('Edit user\'s own API keys'),
878 $prefix . ts('send SMS'),
881 'administer CiviCRM system' => [
882 'label' => $prefix . ts('administer CiviCRM System'),
883 'description' => ts('Perform all system administration tasks in CiviCRM'),
885 'administer CiviCRM data' => [
886 'label' => $prefix . ts('administer CiviCRM Data'),
887 'description' => ts('Permit altering all restricted data options'),
889 'all CiviCRM permissions and ACLs' => [
890 'label' => $prefix . ts('all CiviCRM permissions and ACLs'),
891 'description' => ts('Administer and use CiviCRM bypassing any other permission or ACL checks and enabling the creation of displays and forms that allow others to bypass checks. This permission should be given out with care'),
894 if (self
::isMultisiteEnabled()) {
895 // This could arguably be moved to the multisite extension but
896 // within core it does permit editing group-organization records.
897 $permissions['administer Multiple Organizations'] = [
898 'label' => $prefix . ts('administer Multiple Organizations'),
899 'description' => ts('Administer multiple organizations. In practice this allows editing the group organization link'),
906 * Get permissions implied by 'superset' permissions.
910 public static function getImpliedAdminPermissions(): array {
912 'administer CiviCRM' => ['implied_permissions' => ['administer CiviCRM system', 'administer CiviCRM data']],
913 'administer CiviCRM data' => ['implied_permissions' => ['edit message templates', 'administer dedupe rules']],
914 'administer CiviCRM system' => ['implied_permissions' => ['edit system workflow message templates']],
919 * Get any super-permissions that imply the given permission.
921 * @param string $permission
925 public static function getImpliedPermissionsFor(string $permission): array {
926 if (in_array($permission[0], ['@', '*'], TRUE)) {
927 // Special permissions like '*always deny*' - see DynamicFKAuthorizationTest.
928 // Also '@afform - see AfformUsageTest.
931 $implied = Civi
::cache('metadata')->get('implied_permissions', []);
932 if (isset($implied[$permission])) {
933 return $implied[$permission];
935 $implied[$permission] = ['all CiviCRM permissions and ACLs'];
936 foreach (self
::getImpliedAdminPermissions() as $key => $details) {
937 if (in_array($permission, $details['implied_permissions'] ??
[], TRUE)) {
938 $implied[$permission][] = $key;
941 Civi
::cache('metadata')->set('implied_permissions', $implied);
942 return $implied[$permission];
946 * For each entity provides an array of permissions required for each action
948 * The action is the array key, possible values:
949 * * create: applies to create (with no id in params)
950 * * update: applies to update, setvalue, create (with id in params)
951 * * get: applies to getcount, getsingle, getvalue and other gets
952 * * delete: applies to delete, replace
953 * * meta: applies to getfields, getoptions, getspec
954 * * default: catch-all for anything not declared
956 * Note: some APIs declare other actions as well
958 * Permissions should use arrays for AND and arrays of arrays for OR
959 * @see CRM_Core_Permission::check
961 * @return array of permissions
963 public static function getEntityActionPermissions() {
965 // These are the default permissions - if any entity does not declare permissions for a given action,
966 // (or the entity does not declare permissions at all) - then the action will be used from here
967 $permissions['default'] = [
968 // applies to getfields, getoptions, etc.
969 'meta' => ['access CiviCRM'],
970 // catch-all, applies to create, get, delete, etc.
971 // If an entity declares it's own 'default' action it will override this one
972 'default' => ['administer CiviCRM'],
975 // Note: Additional permissions in DynamicFKAuthorization
976 $permissions['attachment'] = [
978 ['access CiviCRM', 'access AJAX API'],
982 // Contact permissions
983 $permissions['contact'] = [
992 // managed by query object
994 // managed by _civicrm_api3_check_edit_permissions
997 ['access CiviCRM', 'access AJAX API'],
999 'duplicatecheck' => [
1002 'merge' => ['merge duplicate contacts'],
1005 $permissions['dedupe'] = [
1006 'getduplicates' => ['access CiviCRM'],
1007 'getstatistics' => ['access CiviCRM'],
1010 // CRM-16963 - Permissions for country.
1011 $permissions['country'] = [
1016 'administer CiviCRM',
1020 // Contact-related data permissions.
1021 $permissions['address'] = [
1022 // get is managed by BAO::addSelectWhereClause
1023 // create/delete are managed by _civicrm_api3_check_edit_permissions
1026 $permissions['email'] = $permissions['address'];
1027 $permissions['phone'] = $permissions['address'];
1028 $permissions['website'] = $permissions['address'];
1029 $permissions['im'] = $permissions['address'];
1030 $permissions['open_i_d'] = $permissions['address'];
1032 // Also managed by ACLs - CRM-19448
1033 $permissions['entity_tag'] = ['default' => []];
1034 $permissions['note'] = $permissions['entity_tag'];
1036 // Allow non-admins to get and create tags to support tagset widget
1037 // Delete is still reserved for admins
1038 $permissions['tag'] = [
1039 'get' => ['access CiviCRM'],
1040 'create' => ['access CiviCRM'],
1041 'update' => ['access CiviCRM'],
1044 //relationship permissions
1045 $permissions['relationship'] = [
1046 // get is managed by BAO::addSelectWhereClause
1050 'edit all contacts',
1054 'edit all contacts',
1058 // CRM-17741 - Permissions for RelationshipType.
1059 $permissions['relationship_type'] = [
1064 'administer CiviCRM',
1068 // Activity permissions
1069 $permissions['activity'] = [
1072 'delete activities',
1076 // Note that view all activities is also required within the api
1077 // if the id is not passed in. Where the id is passed in the activity
1078 // specific check functions are used and tested.
1082 'view all activities',
1085 $permissions['activity_contact'] = $permissions['activity'];
1088 $permissions['case'] = [
1095 'delete in CiviCase',
1098 'administer CiviCase',
1101 'administer CiviCase',
1104 // At minimum the user needs one of the following. Finer-grained access is controlled by CRM_Case_BAO_Case::addSelectWhereClause
1105 ['access my cases and activities', 'access all cases and activities'],
1108 $permissions['case_contact'] = $permissions['case'];
1109 $permissions['case_activity'] = $permissions['case'];
1111 $permissions['case_type'] = [
1112 'default' => ['administer CiviCase'],
1114 // nested array = OR
1115 ['access my cases and activities', 'access all cases and activities'],
1119 // Campaign permissions
1120 $permissions['campaign'] = [
1121 'get' => ['access CiviCRM'],
1123 // nested array = OR
1124 ['administer CiviCampaign', 'manage campaign'],
1127 $permissions['survey'] = $permissions['campaign'];
1129 // Financial permissions
1130 $permissions['contribution'] = [
1133 'access CiviContribute',
1137 'access CiviContribute',
1138 'delete in CiviContribute',
1140 'completetransaction' => [
1141 'edit contributions',
1145 'access CiviContribute',
1146 'edit contributions',
1149 $permissions['line_item'] = $permissions['contribution'];
1150 $permissions['product'] = $permissions['contribution'];
1152 $permissions['financial_item'] = $permissions['contribution'];
1153 $permissions['financial_type']['get'] = $permissions['contribution']['get'];
1154 $permissions['entity_financial_account']['get'] = $permissions['contribution']['get'];
1155 $permissions['financial_account']['get'] = $permissions['contribution']['get'];
1156 $permissions['financial_trxn']['get'] = $permissions['contribution']['get'];
1158 // Payment permissions
1159 $permissions['payment'] = [
1162 'access CiviContribute',
1166 'access CiviContribute',
1167 'delete in CiviContribute',
1171 'access CiviContribute',
1172 'edit contributions',
1176 'access CiviContribute',
1177 'edit contributions',
1181 'access CiviContribute',
1182 'edit contributions',
1185 $permissions['contribution_recur'] = $permissions['payment'];
1187 // Custom field permissions
1188 $permissions['custom_field'] = [
1190 'administer CiviCRM',
1191 'access all custom data',
1194 $permissions['custom_group'] = $permissions['custom_field'];
1196 // Event permissions
1197 $permissions['event'] = [
1206 'delete in CiviEvent',
1219 // Exception refers to dedupe_exception.
1220 $permissions['exception'] = [
1221 'default' => ['merge duplicate contacts'],
1224 $permissions['job'] = [
1225 'process_batch_merge' => ['merge duplicate contacts'],
1227 $permissions['rule_group']['get'] = [['merge duplicate contacts', 'administer CiviCRM']];
1228 // Loc block is only used for events
1229 $permissions['loc_block'] = $permissions['event'];
1231 $permissions['state_province'] = [
1237 // Price sets are shared by several components, user needs access to at least one of them
1238 $permissions['price_set'] = [
1240 ['access CiviEvent', 'access CiviContribute', 'access CiviMember'],
1243 ['access CiviCRM', 'view event info', 'make online contributions'],
1248 $permissions['file'] = [
1251 'access uploaded files',
1254 $permissions['files_by_entity'] = $permissions['file'];
1256 // Group permissions
1257 $permissions['group'] = [
1267 $permissions['group_nesting'] = $permissions['group'];
1268 $permissions['group_organization'] = $permissions['group'];
1270 //Group Contact permission
1271 $permissions['group_contact'] = [
1277 'edit all contacts',
1281 // CiviMail Permissions
1282 $civiMailBasePerms = [
1283 // To get/preview/update, one must have least one of these perms:
1284 // Mailing API implementations enforce nuances of create/approve/schedule permissions.
1287 'schedule mailings',
1290 $permissions['mailing'] = [
1298 'delete in CiviMail',
1302 ['access CiviMail', 'schedule mailings'],
1309 $permissions['mailing_group'] = $permissions['mailing'];
1310 $permissions['mailing_job'] = $permissions['mailing'];
1311 $permissions['mailing_recipients'] = $permissions['mailing'];
1313 $permissions['mailing_a_b'] = [
1321 'delete in CiviMail',
1325 ['access CiviMail', 'schedule mailings'],
1333 // Membership permissions
1334 $permissions['membership'] = [
1337 'access CiviMember',
1341 'access CiviMember',
1342 'delete in CiviMember',
1346 'access CiviMember',
1350 $permissions['membership_status'] = $permissions['membership'];
1351 $permissions['membership_type'] = $permissions['membership'];
1352 $permissions['membership_payment'] = [
1355 'access CiviMember',
1357 'access CiviContribute',
1358 'edit contributions',
1362 'access CiviMember',
1363 'delete in CiviMember',
1364 'access CiviContribute',
1365 'delete in CiviContribute',
1369 'access CiviMember',
1370 'access CiviContribute',
1374 'access CiviMember',
1376 'access CiviContribute',
1377 'edit contributions',
1381 // Participant permissions
1382 $permissions['participant'] = [
1386 'register for events',
1391 'edit event participants',
1396 'view event participants',
1401 'edit event participants',
1404 $permissions['participant_payment'] = [
1408 'register for events',
1409 'access CiviContribute',
1410 'edit contributions',
1415 'edit event participants',
1416 'access CiviContribute',
1417 'delete in CiviContribute',
1422 'view event participants',
1423 'access CiviContribute',
1428 'edit event participants',
1429 'access CiviContribute',
1430 'edit contributions',
1434 // Pledge permissions
1435 $permissions['pledge'] = [
1438 'access CiviPledge',
1443 'access CiviPledge',
1444 'delete in CiviPledge',
1448 'access CiviPledge',
1452 'access CiviPledge',
1457 //CRM-16777: Disable schedule reminder for user that have 'edit all events' and 'administer CiviCRM' permission.
1458 $permissions['action_schedule'] = [
1467 $permissions['pledge_payment'] = [
1470 'access CiviPledge',
1472 'access CiviContribute',
1473 'edit contributions',
1477 'access CiviPledge',
1478 'delete in CiviPledge',
1479 'access CiviContribute',
1480 'delete in CiviContribute',
1484 'access CiviPledge',
1485 'access CiviContribute',
1489 'access CiviPledge',
1491 'access CiviContribute',
1492 'edit contributions',
1496 // Dashboard permissions
1497 $permissions['dashboard'] = [
1502 $permissions['dashboard_contact'] = [
1508 $permissions['saved_search'] = [
1509 'default' => ['administer CiviCRM data'],
1512 // Profile permissions
1513 $permissions['profile'] = [
1514 // the profile will take care of this
1518 $permissions['uf_group'] = [
1522 'administer CiviCRM',
1523 'manage event profiles',
1532 'administer CiviCRM',
1533 'manage event profiles',
1537 $permissions['uf_field'] = $permissions['uf_join'] = $permissions['uf_group'];
1538 $permissions['uf_field']['delete'] = [
1541 'administer CiviCRM',
1542 'manage event profiles',
1545 $permissions['option_value'] = $permissions['uf_group'];
1546 $permissions['option_group'] = $permissions['option_value'];
1548 $permissions['custom_value'] = [
1549 'gettree' => ['access CiviCRM'],
1552 $permissions['message_template'] = [
1553 'get' => ['access CiviCRM'],
1554 'create' => [['edit message templates', 'edit user-driven message templates', 'edit system workflow message templates']],
1555 'update' => [['edit message templates', 'edit user-driven message templates', 'edit system workflow message templates']],
1558 $permissions['report_template']['update'] = 'save Report Criteria';
1559 $permissions['report_template']['create'] = 'save Report Criteria';
1560 return $permissions;
1564 * Translate an unknown action to a canonical form.
1566 * @param string $action
1569 * the standardised action name
1571 public static function getGenericAction($action) {
1572 $snippet = substr($action, 0, 3);
1573 if ($action == 'replace' ||
$snippet == 'del') {
1574 // 'Replace' is a combination of get+create+update+delete; however, the permissions
1575 // on each of those will be tested separately at runtime. This is just a sniff-test
1576 // based on the heuristic that 'delete' tends to be the most closely guarded
1577 // of the necessary permissions.
1580 elseif ($action == 'setvalue' ||
$snippet == 'upd') {
1583 elseif ($action == 'getfields' ||
$action == 'getfield' ||
$action == 'getspec' ||
$action == 'getoptions') {
1586 elseif ($snippet == 'get') {
1593 * Validate user permission across.
1594 * edit or view or with supportable acls.
1598 public static function giveMeAllACLs() {
1599 if (CRM_Core_Permission
::check('view all contacts') ||
1600 CRM_Core_Permission
::check('edit all contacts')
1605 $session = CRM_Core_Session
::singleton();
1606 $contactID = $session->get('userID');
1609 $aclPermission = self
::getPermission();
1610 if (in_array($aclPermission, [
1611 CRM_Core_Permission
::EDIT
,
1612 CRM_Core_Permission
::VIEW
,
1618 // run acl where hook and see if the user is supplying an ACL clause
1619 // that is not false
1620 $tables = $whereTables = [];
1623 CRM_Utils_Hook
::aclWhereClause(CRM_Core_Permission
::VIEW
,
1624 $tables, $whereTables,
1627 return empty($whereTables) ?
FALSE : TRUE;
1631 * Get component name from given permission.
1633 * @param string $permission
1635 * @return null|string
1636 * the name of component.
1638 public static function getComponentName($permission) {
1639 $componentName = NULL;
1640 $permission = trim($permission);
1641 if (empty($permission)) {
1642 return $componentName;
1645 static $allCompPermissions = [];
1646 if (empty($allCompPermissions)) {
1647 $components = CRM_Core_Component
::getComponents();
1648 foreach ($components as $name => $comp) {
1649 //get all permissions of each components unconditionally
1650 $allCompPermissions[$name] = $comp->getPermissions(TRUE);
1654 if (is_array($allCompPermissions)) {
1655 foreach ($allCompPermissions as $name => $permissions) {
1656 if (array_key_exists($permission, $permissions)) {
1657 $componentName = $name;
1663 return $componentName;
1667 * Get all the contact emails for users that have a specific permission.
1669 * @param string $permissionName
1670 * Name of the permission we are interested in.
1673 * a comma separated list of email addresses
1675 public static function permissionEmails($permissionName) {
1676 $config = CRM_Core_Config
::singleton();
1677 return $config->userPermissionClass
->permissionEmails($permissionName);
1681 * Get all the contact emails for users that have a specific role.
1683 * @param string $roleName
1684 * Name of the role we are interested in.
1687 * a comma separated list of email addresses
1689 public static function roleEmails($roleName) {
1690 $config = CRM_Core_Config
::singleton();
1691 return $config->userRoleClass
->roleEmails($roleName);
1697 public static function isMultisiteEnabled() {
1698 return (bool) Civi
::settings()->get('is_enabled');
1702 * Verify if the user has permission to get the invoice.
1705 * TRUE if the user has download all invoices permission or download my
1706 * invoices permission and the invoice author is the current user.
1708 public static function checkDownloadInvoice() {
1709 $cid = CRM_Core_Session
::getLoggedInContactID();
1710 if (CRM_Core_Permission
::check('access CiviContribute') ||
1711 (CRM_Core_Permission
::check('view my invoices') && $_GET['cid'] == $cid)
1719 * Get permissions for components.
1721 * @param bool $includeDisabled
1724 * @throws \CRM_Core_Exception
1726 protected static function getComponentPermissions(bool $includeDisabled): array {
1727 if (!$includeDisabled) {
1728 $components = CRM_Core_Component
::getEnabledComponents();
1731 $components = CRM_Core_Component
::getComponents();
1735 foreach ($components as $comp) {
1736 $perm = $comp->getPermissions($includeDisabled, TRUE);
1738 $info = $comp->getInfo();
1739 foreach ($perm as $p => $attr) {
1741 if (!is_array($attr)) {
1745 $attr[0] = $info['translatedName'] . ': ' . $attr[0];
1746 $permissions[$p] = $attr;
1750 return $permissions;
1754 * Get permissions for core functionality and for that of core components.
1759 * @throws \CRM_Core_Exception
1761 protected static function getCoreAndComponentPermissions(bool $all): array {
1762 $permissions = self
::getCorePermissions();
1763 $permissions = array_merge($permissions, self
::getComponentPermissions($all));
1764 $permissions['all CiviCRM permissions and ACLs']['implied_permissions'] = array_keys($permissions);
1765 return $permissions;