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