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