Merge pull request #4882 from colemanw/CRM-15789
[civicrm-core.git] / CRM / Core / Permission.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This is the basic permission class wrapper
38 */
39 class CRM_Core_Permission {
40
41 /**
42 * Static strings used to compose permissions
43 *
44 * @const
45 * @var string
46 */
47 const EDIT_GROUPS = 'edit contacts in ', VIEW_GROUPS = 'view contacts in ';
48
49 /**
50 * The various type of permissions
51 *
52 * @var int
53 */
54 const EDIT = 1, VIEW = 2, DELETE = 3, CREATE = 4, SEARCH = 5, ALL = 6, ADMIN = 7;
55
56 /**
57 * A placeholder permission which always fails
58 */
59 const ALWAYS_DENY_PERMISSION = "*always deny*";
60
61 /**
62 * A placeholder permission which always fails
63 */
64 const ALWAYS_ALLOW_PERMISSION = "*always allow*";
65
66 /**
67 * Various authentication sources
68 *
69 * @var int
70 */
71 const AUTH_SRC_UNKNOWN = 0, AUTH_SRC_CHECKSUM = 1, AUTH_SRC_SITEKEY = 2, AUTH_SRC_LOGIN = 4;
72
73 /**
74 * Get the current permission of this user
75 *
76 * @return string the permission of the user (edit or view or null)
77 */
78 public static function getPermission() {
79 $config = CRM_Core_Config::singleton();
80 return $config->userPermissionClass->getPermission();
81 }
82
83 /**
84 * Given a permission string or array, check for access requirements
85 * @param mixed $permissions
86 * The permission to check as an array or string -see examples.
87 * arrays
88 *
89 * Ex 1
90 *
91 * Must have 'access CiviCRM'
92 * (string) 'access CiviCRM'
93 *
94 *
95 * Ex 2 Must have 'access CiviCRM' and 'access Ajax API'
96 * array('access CiviCRM', 'access Ajax API')
97 *
98 * Ex 3 Must have 'access CiviCRM' or 'access Ajax API'
99 * array(
100 * array('access CiviCRM', 'access Ajax API'),
101 * ),
102 *
103 * Ex 4 Must have 'access CiviCRM' or 'access Ajax API' AND 'access CiviEvent'
104 * array(
105 * array('access CiviCRM', 'access Ajax API'),
106 * 'access CiviEvent',
107 * ),
108 *
109 * Note that in permissions.php this is keyed by the action eg.
110 * (access Civi || access AJAX) && (access CiviEvent || access CiviContribute)
111 * 'myaction' => array(
112 * array('access CiviCRM', 'access Ajax API'),
113 * array('access CiviEvent', 'access CiviContribute')
114 * ),
115 *
116 * @return boolean true if yes, else false
117 * @static
118 */
119 public static function check($permissions) {
120 $permissions = (array) $permissions;
121
122 foreach ($permissions as $permission) {
123 if (is_array($permission)) {
124 foreach ($permission as $orPerm) {
125 if (self::check($orPerm)) {
126 //one of our 'or' permissions has succeeded - stop checking this permission
127 return TRUE;;
128 }
129 }
130 //none of our our conditions was met
131 return FALSE;
132 }
133 else {
134 if (!CRM_Core_Config::singleton()->userPermissionClass->check($permission)) {
135 //one of our 'and' conditions has not been met
136 return FALSE;
137 }
138 }
139 }
140 return TRUE;
141 }
142
143 /**
144 * Determine if any one of the permissions strings applies to current user
145 *
146 * @param array $perms
147 * @return bool
148 */
149 public static function checkAnyPerm($perms) {
150 foreach ($perms as $perm) {
151 if (CRM_Core_Permission::check($perm)) {
152 return TRUE;
153 }
154 }
155 return FALSE;
156 }
157
158 /**
159 * Given a group/role array, check for access requirements
160 *
161 * @param array $array
162 * The group/role to check.
163 *
164 * @return boolean true if yes, else false
165 * @static
166 */
167 public static function checkGroupRole($array) {
168 $config = CRM_Core_Config::singleton();
169 return $config->userPermissionClass->checkGroupRole($array);
170 }
171
172 /**
173 * Get the permissioned where clause for the user
174 *
175 * @param int $type
176 * The type of permission needed.
177 * @param array $tables
178 * (reference ) add the tables that are needed for the select clause.
179 * @param array $whereTables
180 * (reference ) add the tables that are needed for the where clause.
181 *
182 * @return string the group where clause for this user
183 */
184 public static function getPermissionedStaticGroupClause($type, &$tables, &$whereTables) {
185 $config = CRM_Core_Config::singleton();
186 return $config->userPermissionClass->getPermissionedStaticGroupClause($type, $tables, $whereTables);
187 }
188
189 /**
190 * Get all groups from database, filtered by permissions
191 * for this user
192 *
193 * @param string $groupType
194 * Type of group(Access/Mailing).
195 * @param bool|\boolen $excludeHidden exclude hidden groups.
196 *
197 * @static
198 *
199 * @return array - array reference of all groups.
200 */
201 public static function group($groupType, $excludeHidden = TRUE) {
202 $config = CRM_Core_Config::singleton();
203 return $config->userPermissionClass->group($groupType, $excludeHidden);
204 }
205
206 /**
207 * @return bool
208 */
209 public static function customGroupAdmin() {
210 $admin = FALSE;
211
212 // check if user has all powerful permission
213 // or administer civicrm permission (CRM-1905)
214 if (self::check('access all custom data')) {
215 return TRUE;
216 }
217
218 if (
219 self::check('administer Multiple Organizations') &&
220 self::isMultisiteEnabled()
221 ) {
222 return TRUE;
223 }
224
225 if (self::check('administer CiviCRM')) {
226 return TRUE;
227 }
228
229 return FALSE;
230 }
231
232 /**
233 * @param int $type
234 * @param bool $reset
235 *
236 * @return array
237 */
238 public static function customGroup($type = CRM_Core_Permission::VIEW, $reset = FALSE) {
239 $customGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id',
240 array('fresh' => $reset));
241 $defaultGroups = array();
242
243 // check if user has all powerful permission
244 // or administer civicrm permission (CRM-1905)
245 if (self::customGroupAdmin()) {
246 $defaultGroups = array_keys($customGroups);
247 }
248
249 return CRM_ACL_API::group($type, NULL, 'civicrm_custom_group', $customGroups, $defaultGroups);
250 }
251
252 /**
253 * @param int $type
254 * @param null $prefix
255 * @param bool $reset
256 *
257 * @return string
258 */
259 public static function customGroupClause($type = CRM_Core_Permission::VIEW, $prefix = NULL, $reset = FALSE) {
260 if (self::customGroupAdmin()) {
261 return ' ( 1 ) ';
262 }
263
264 $groups = self::customGroup($type, $reset);
265 if (empty($groups)) {
266 return ' ( 0 ) ';
267 }
268 else {
269 return "{$prefix}id IN ( " . implode(',', $groups) . ' ) ';
270 }
271 }
272
273 /**
274 * @param int $gid
275 * @param int $type
276 *
277 * @return bool
278 */
279 public static function ufGroupValid($gid, $type = CRM_Core_Permission::VIEW) {
280 if (empty($gid)) {
281 return TRUE;
282 }
283
284 $groups = self::ufGroup($type);
285 return !empty($groups) && in_array($gid, $groups) ? TRUE : FALSE;
286 }
287
288 /**
289 * @param int $type
290 *
291 * @return array
292 */
293 public static function ufGroup($type = CRM_Core_Permission::VIEW) {
294 $ufGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id');
295
296 $allGroups = array_keys($ufGroups);
297
298 // check if user has all powerful permission
299 if (self::check('profile listings and forms')) {
300 return $allGroups;
301 }
302
303 switch ($type) {
304 case CRM_Core_Permission::VIEW:
305 if (self::check('profile view')) {
306 return $allGroups;
307 }
308 break;
309
310 case CRM_Core_Permission::CREATE:
311 if (self::check('profile create')) {
312 return $allGroups;
313 }
314 break;
315
316 case CRM_Core_Permission::EDIT:
317 if (self::check('profile edit')) {
318 return $allGroups;
319 }
320 break;
321
322 case CRM_Core_Permission::SEARCH:
323 if (self::check('profile listings')) {
324 return $allGroups;
325 }
326 break;
327 }
328
329 return CRM_ACL_API::group($type, NULL, 'civicrm_uf_group', $ufGroups);
330 }
331
332 /**
333 * @param int $type
334 * @param null $prefix
335 * @param bool $returnUFGroupIds
336 *
337 * @return array|string
338 */
339 public static function ufGroupClause($type = CRM_Core_Permission::VIEW, $prefix = NULL, $returnUFGroupIds = FALSE) {
340 $groups = self::ufGroup($type);
341 if ($returnUFGroupIds) {
342 return $groups;
343 }
344 elseif (empty($groups)) {
345 return ' ( 0 ) ';
346 }
347 else {
348 return "{$prefix}id IN ( " . implode(',', $groups) . ' ) ';
349 }
350 }
351
352 /**
353 * @param int $type
354 * @param int $eventID
355 * @param string $context
356 *
357 * @return array|null
358 */
359 public static function event($type = CRM_Core_Permission::VIEW, $eventID = NULL, $context = '') {
360 if (!empty($context)) {
361 if (CRM_Core_Permission::check($context)) {
362 return TRUE;
363 }
364 }
365 $events = CRM_Event_PseudoConstant::event(NULL, TRUE);
366 $includeEvents = array();
367
368 // check if user has all powerful permission
369 if (self::check('register for events')) {
370 $includeEvents = array_keys($events);
371 }
372
373 if ($type == CRM_Core_Permission::VIEW &&
374 self::check('view event info')
375 ) {
376 $includeEvents = array_keys($events);
377 }
378
379 $permissionedEvents = CRM_ACL_API::group($type, NULL, 'civicrm_event', $events, $includeEvents);
380 if (!$eventID) {
381 return $permissionedEvents;
382 }
383 if (!empty($permissionedEvents)) {
384 return array_search($eventID, $permissionedEvents) === FALSE ? NULL : $eventID;
385 }
386 return NULL;
387 }
388
389 /**
390 * @param int $type
391 * @param null $prefix
392 *
393 * @return string
394 */
395 public static function eventClause($type = CRM_Core_Permission::VIEW, $prefix = NULL) {
396 $events = self::event($type);
397 if (empty($events)) {
398 return ' ( 0 ) ';
399 }
400 else {
401 return "{$prefix}id IN ( " . implode(',', $events) . ' ) ';
402 }
403 }
404
405 /**
406 * @param $module
407 * @param bool $checkPermission
408 *
409 * @return bool
410 */
411 public static function access($module, $checkPermission = TRUE) {
412 $config = CRM_Core_Config::singleton();
413
414 if (!in_array($module, $config->enableComponents)) {
415 return FALSE;
416 }
417
418 if ($checkPermission) {
419 if ($module == 'CiviCase') {
420 return CRM_Case_BAO_Case::accessCiviCase();
421 }
422 else {
423 return CRM_Core_Permission::check("access $module");
424 }
425 }
426
427 return TRUE;
428 }
429
430 /**
431 * Check permissions for delete and edit actions
432 *
433 * @param string $module
434 * Component name.
435 * @param int $action
436 * Action to be check across component.
437 *
438 *
439 * @return bool
440 */
441 public static function checkActionPermission($module, $action) {
442 //check delete related permissions.
443 if ($action & CRM_Core_Action::DELETE) {
444 $permissionName = "delete in $module";
445 }
446 else {
447 $editPermissions = array(
448 'CiviEvent' => 'edit event participants',
449 'CiviMember' => 'edit memberships',
450 'CiviPledge' => 'edit pledges',
451 'CiviContribute' => 'edit contributions',
452 'CiviGrant' => 'edit grants',
453 'CiviMail' => 'access CiviMail',
454 'CiviAuction' => 'add auction items',
455 );
456 $permissionName = CRM_Utils_Array::value($module, $editPermissions);
457 }
458
459 if ($module == 'CiviCase' && !$permissionName) {
460 return CRM_Case_BAO_Case::accessCiviCase();
461 }
462 else {
463 //check for permission.
464 return CRM_Core_Permission::check($permissionName);
465 }
466 }
467
468 /**
469 * @param $args
470 * @param string $op
471 *
472 * @return bool
473 */
474 public static function checkMenu(&$args, $op = 'and') {
475 if (!is_array($args)) {
476 return $args;
477 }
478 foreach ($args as $str) {
479 $res = CRM_Core_Permission::check($str);
480 if ($op == 'or' && $res) {
481 return TRUE;
482 }
483 elseif ($op == 'and' && !$res) {
484 return FALSE;
485 }
486 }
487 return ($op == 'or') ? FALSE : TRUE;
488 }
489
490 /**
491 * @param $item
492 *
493 * @return bool|mixed
494 * @throws Exception
495 */
496 public static function checkMenuItem(&$item) {
497 if (!array_key_exists('access_callback', $item)) {
498 CRM_Core_Error::backtrace();
499 CRM_Core_Error::fatal();
500 }
501
502 // if component_id is present, ensure it is enabled
503 if (isset($item['component_id']) &&
504 $item['component_id']
505 ) {
506 $config = CRM_Core_Config::singleton();
507 if (is_array($config->enableComponentIDs) &&
508 in_array($item['component_id'], $config->enableComponentIDs)
509 ) {
510 // continue with process
511 }
512 else {
513 return FALSE;
514 }
515 }
516
517 // the following is imitating drupal 6 code in includes/menu.inc
518 if (empty($item['access_callback']) ||
519 is_numeric($item['access_callback'])
520 ) {
521 return (boolean ) $item['access_callback'];
522 }
523
524 // check whether the following Ajax requests submitted the right key
525 // FIXME: this should be integrated into ACLs proper
526 if (CRM_Utils_Array::value('page_type', $item) == 3) {
527 if (!CRM_Core_Key::validate($_REQUEST['key'], $item['path'])) {
528 return FALSE;
529 }
530 }
531
532 // check if callback is for checkMenu, if so optimize it
533 if (is_array($item['access_callback']) &&
534 $item['access_callback'][0] == 'CRM_Core_Permission' &&
535 $item['access_callback'][1] == 'checkMenu'
536 ) {
537 $op = CRM_Utils_Array::value(1, $item['access_arguments'], 'and');
538 return self::checkMenu($item['access_arguments'][0], $op);
539 }
540 else {
541 return call_user_func_array($item['access_callback'], $item['access_arguments']);
542 }
543 }
544
545 /**
546 * @param bool $all
547 *
548 * @return array
549 */
550 public static function &basicPermissions($all = FALSE) {
551 static $permissions = NULL;
552
553 if (!$permissions) {
554 $config = CRM_Core_Config::singleton();
555 $prefix = ts('CiviCRM') . ': ';
556 $permissions = self::getCorePermissions();
557
558 if (self::isMultisiteEnabled()) {
559 $permissions['administer Multiple Organizations'] = $prefix . ts('administer Multiple Organizations');
560 }
561
562 if (!$all) {
563 $components = CRM_Core_Component::getEnabledComponents();
564 }
565 else {
566 $components = CRM_Core_Component::getComponents();
567 }
568
569 foreach ($components as $comp) {
570 $perm = $comp->getPermissions();
571 if ($perm) {
572 $info = $comp->getInfo();
573 foreach ($perm as $p) {
574 $permissions[$p] = $info['translatedName'] . ': ' . $p;
575 }
576 }
577 }
578
579 // Add any permissions defined in hook_civicrm_permission implementations.
580 $module_permissions = $config->userPermissionClass->getAllModulePermissions();
581 $permissions = array_merge($permissions, $module_permissions);
582 }
583
584 return $permissions;
585 }
586
587 /**
588 * @return array
589 */
590 public static function getAnonymousPermissionsWarnings() {
591 static $permissions = array();
592 if (empty($permissions)) {
593 $permissions = array(
594 'administer CiviCRM',
595 );
596 $components = CRM_Core_Component::getComponents();
597 foreach ($components as $comp) {
598 if (!method_exists($comp, 'getAnonymousPermissionWarnings')) {
599 continue;
600 }
601 $permissions = array_merge($permissions, $comp->getAnonymousPermissionWarnings());
602 }
603 }
604 return $permissions;
605 }
606
607 /**
608 * @param $anonymous_perms
609 *
610 * @return array
611 */
612 public static function validateForPermissionWarnings($anonymous_perms) {
613 return array_intersect($anonymous_perms, self::getAnonymousPermissionsWarnings());
614 }
615
616 /**
617 * @return array
618 */
619 public static function getCorePermissions() {
620 $prefix = ts('CiviCRM') . ': ';
621 $permissions = array(
622 'add contacts' => $prefix . ts('add contacts'),
623 'view all contacts' => $prefix . ts('view all contacts'),
624 'edit all contacts' => $prefix . ts('edit all contacts'),
625 'view my contact' => $prefix . ts('view my contact'),
626 'edit my contact' => $prefix . ts('edit my contact'),
627 'delete contacts' => $prefix . ts('delete contacts'),
628 'access deleted contacts' => $prefix . ts('access deleted contacts'),
629 'import contacts' => $prefix . ts('import contacts'),
630 'edit groups' => $prefix . ts('edit groups'),
631 'administer CiviCRM' => $prefix . ts('administer CiviCRM'),
632 'skip IDS check' => $prefix . ts('skip IDS check'),
633 'access uploaded files' => $prefix . ts('access uploaded files'),
634 'profile listings and forms' => $prefix . ts('profile listings and forms'),
635 'profile listings' => $prefix . ts('profile listings'),
636 'profile create' => $prefix . ts('profile create'),
637 'profile edit' => $prefix . ts('profile edit'),
638 'profile view' => $prefix . ts('profile view'),
639 'access all custom data' => $prefix . ts('access all custom data'),
640 'view all activities' => $prefix . ts('view all activities'),
641 'delete activities' => $prefix . ts('delete activities'),
642 'access CiviCRM' => $prefix . ts('access CiviCRM'),
643 'access Contact Dashboard' => $prefix . ts('access Contact Dashboard'),
644 'translate CiviCRM' => $prefix . ts('translate CiviCRM'),
645 'administer reserved groups' => $prefix . ts('administer reserved groups'),
646 'administer Tagsets' => $prefix . ts('administer Tagsets'),
647 'administer reserved tags' => $prefix . ts('administer reserved tags'),
648 'administer dedupe rules' => $prefix . ts('administer dedupe rules'),
649 'merge duplicate contacts' => $prefix . ts('merge duplicate contacts'),
650 'view debug output' => $prefix . ts('view debug output'),
651 'view all notes' => $prefix . ts('view all notes'),
652 'access AJAX API' => $prefix . ts('access AJAX API'),
653 'access contact reference fields' => $prefix . ts('access contact reference fields'),
654 'create manual batch' => $prefix . ts('create manual batch'),
655 'edit own manual batches' => $prefix . ts('edit own manual batches'),
656 'edit all manual batches' => $prefix . ts('edit all manual batches'),
657 'view own manual batches' => $prefix . ts('view own manual batches'),
658 'view all manual batches' => $prefix . ts('view all manual batches'),
659 'delete own manual batches' => $prefix . ts('delete own manual batches'),
660 'delete all manual batches' => $prefix . ts('delete all manual batches'),
661 'export own manual batches' => $prefix . ts('export own manual batches'),
662 'export all manual batches' => $prefix . ts('export all manual batches'),
663 'administer payment processors' => $prefix . ts('administer payment processors'),
664 );
665
666 return $permissions;
667 }
668
669 /**
670 * Validate user permission across
671 * edit or view or with supportable acls.
672 *
673 * return boolean true/false.
674 **/
675 public static function giveMeAllACLs() {
676 if (CRM_Core_Permission::check('view all contacts') ||
677 CRM_Core_Permission::check('edit all contacts')
678 ) {
679 return TRUE;
680 }
681
682 $session = CRM_Core_Session::singleton();
683 $contactID = $session->get('userID');
684
685 //check for acl.
686 $aclPermission = self::getPermission();
687 if (in_array($aclPermission, array(
688 CRM_Core_Permission::EDIT,
689 CRM_Core_Permission::VIEW,
690 ))
691 ) {
692 return TRUE;
693 }
694
695 // run acl where hook and see if the user is supplying an ACL clause
696 // that is not false
697 $tables = $whereTables = array();
698 $where = NULL;
699
700 CRM_Utils_Hook::aclWhereClause(CRM_Core_Permission::VIEW,
701 $tables, $whereTables,
702 $contactID, $where
703 );
704 return empty($whereTables) ? FALSE : TRUE;
705 }
706
707 /**
708 * Get component name from given permission.
709 *
710 * @param string $permission
711 *
712 * return string $componentName the name of component.
713 *
714 * @return int|null|string
715 * @static
716 */
717 public static function getComponentName($permission) {
718 $componentName = NULL;
719 $permission = trim($permission);
720 if (empty($permission)) {
721 return $componentName;
722 }
723
724 static $allCompPermissions = array();
725 if (empty($allCompPermissions)) {
726 $components = CRM_Core_Component::getComponents();
727 foreach ($components as $name => $comp) {
728 //get all permissions of each components unconditionally
729 $allCompPermissions[$name] = $comp->getPermissions(TRUE);
730 }
731 }
732
733 if (is_array($allCompPermissions)) {
734 foreach ($allCompPermissions as $name => $permissions) {
735 if (in_array($permission, $permissions)) {
736 $componentName = $name;
737 break;
738 }
739 }
740 }
741
742 return $componentName;
743 }
744
745 /**
746 * Get all the contact emails for users that have a specific permission
747 *
748 * @param string $permissionName
749 * Name of the permission we are interested in.
750 *
751 * @return string a comma separated list of email addresses
752 */
753 public static function permissionEmails($permissionName) {
754 $config = CRM_Core_Config::singleton();
755 return $config->userPermissionClass->permissionEmails($permissionName);
756 }
757
758 /**
759 * Get all the contact emails for users that have a specific role
760 *
761 * @param string $roleName
762 * Name of the role we are interested in.
763 *
764 * @return string a comma separated list of email addresses
765 */
766 public static function roleEmails($roleName) {
767 $config = CRM_Core_Config::singleton();
768 return $config->userRoleClass->roleEmails($roleName);
769 }
770
771 /**
772 * @return bool
773 */
774 public static function isMultisiteEnabled() {
775 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
776 'is_enabled'
777 ) ? TRUE : FALSE;
778 }
779 }