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