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