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