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