Return from getACLRoles when contactID is null
[civicrm-core.git] / CRM / ACL / BAO / ACL.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Access Control List
20 */
21 class CRM_ACL_BAO_ACL extends CRM_ACL_DAO_ACL {
22 /**
23 * @var string
24 */
25 public static $_entityTable = NULL;
26 public static $_objectTable = NULL;
27 public static $_operation = NULL;
28
29 public static $_fieldKeys = NULL;
30
31 /**
32 * Available operations for pseudoconstant.
33 *
34 * @return array
35 */
36 public static function operation() {
37 if (!self::$_operation) {
38 self::$_operation = [
39 'View' => ts('View'),
40 'Edit' => ts('Edit'),
41 'Create' => ts('Create'),
42 'Delete' => ts('Delete'),
43 'Search' => ts('Search'),
44 'All' => ts('All'),
45 ];
46 }
47 return self::$_operation;
48 }
49
50 /**
51 * Construct an associative array of an ACL rule's properties
52 *
53 * @param string $format
54 * Sprintf format for array.
55 * @param bool $hideEmpty
56 * Only return elements that have a value set.
57 *
58 * @return array
59 * Assoc. array of the ACL rule's properties
60 */
61 public function toArray($format = '%s', $hideEmpty = FALSE) {
62 $result = [];
63
64 if (!self::$_fieldKeys) {
65 $fields = CRM_ACL_DAO_ACL::fields();
66 self::$_fieldKeys = array_keys($fields);
67 }
68
69 foreach (self::$_fieldKeys as $field) {
70 $result[$field] = $this->$field;
71 }
72 return $result;
73 }
74
75 /**
76 * Retrieve ACLs for a contact or group. Note that including a contact id
77 * without a group id will return those ACL rules which are granted
78 * directly to the contact, but not those granted to the contact through
79 * any/all of his group memberships.
80 *
81 * @param int $contact_id
82 * ID of a contact to search for.
83 *
84 * @return array
85 * Array of assoc. arrays of ACL rules
86 *
87 * @throws \CRM_Core_Exception
88 */
89 protected static function getACLs(int $contact_id) {
90 $results = [];
91 $query = " SELECT acl.*
92 FROM civicrm_acl acl
93 WHERE acl.entity_table = 'civicrm_contact'
94 AND acl.entity_id = $contact_id";
95
96 $rule = CRM_Core_DAO::executeQuery($query);
97
98 while ($rule->fetch()) {
99 $results[$rule->id] = $rule->toArray();
100 }
101
102 $results += self::getACLRoles($contact_id);
103
104 return $results;
105 }
106
107 /**
108 * Get all of the ACLs through ACL groups.
109 *
110 * @param int $contact_id
111 * ID of a contact to search for.
112 *
113 * @return array
114 * Array of assoc. arrays of ACL rules
115 *
116 * @throws \CRM_Core_Exception
117 */
118 protected static function getACLRoles($contact_id = NULL) {
119 $contact_id = CRM_Utils_Type::escape($contact_id, 'Integer');
120
121 $query = 'SELECT acl.* FROM civicrm_acl acl';
122 $where = ['acl.entity_table = "civicrm_acl_role" AND acl.entity_id IN (' . implode(',', array_keys(CRM_Core_OptionGroup::values('acl_role'))) . ')'];
123
124 if (!empty($contact_id)) {
125 return [];
126 }
127
128 $results = [];
129
130 $rule = CRM_Core_DAO::executeQuery($query . ' WHERE ' . implode(' AND ', $where));
131
132 while ($rule->fetch()) {
133 $results[$rule->id] = $rule->toArray();
134 }
135
136 return $results;
137 }
138
139 /**
140 * Get all ACLs granted to a contact through all group memberships.
141 *
142 * @param int $contact_id
143 * The contact's ID.
144 * @param bool $aclRoles
145 * Include ACL Roles?.
146 *
147 * @return array
148 * Assoc array of ACL rules
149 * @throws \CRM_Core_Exception
150 */
151 protected static function getGroupACLs($contact_id, $aclRoles = FALSE) {
152 $contact_id = CRM_Utils_Type::escape($contact_id, 'Integer');
153
154 $results = [];
155
156 if ($contact_id) {
157 $query = "
158 SELECT acl.*
159 FROM civicrm_acl acl
160 INNER JOIN civicrm_group_contact group_contact
161 ON acl.entity_id = group_contact.group_id
162 WHERE acl.entity_table = 'civicrm_group'
163 AND group_contact.contact_id = $contact_id
164 AND group_contact.status = 'Added'";
165
166 $rule = CRM_Core_DAO::executeQuery($query);
167
168 while ($rule->fetch()) {
169 $results[$rule->id] = $rule->toArray();
170 }
171 }
172
173 if ($aclRoles) {
174 $results += self::getGroupACLRoles($contact_id);
175 }
176
177 return $results;
178 }
179
180 /**
181 * Get all of the ACLs for a contact through ACL groups owned by Contact.
182 * groups.
183 *
184 * @param int $contact_id
185 * ID of a contact to search for.
186 *
187 * @return array
188 * Array of assoc. arrays of ACL rules
189 * @throws \CRM_Core_Exception
190 */
191 protected static function getGroupACLRoles($contact_id) {
192 $contact_id = CRM_Utils_Type::escape($contact_id, 'Integer');
193
194 $query = " SELECT acl.*
195 FROM civicrm_acl acl
196 INNER JOIN civicrm_option_group og
197 ON og.name = 'acl_role'
198 INNER JOIN civicrm_option_value ov
199 ON acl.entity_table = 'civicrm_acl_role'
200 AND ov.option_group_id = og.id
201 AND acl.entity_id = ov.value
202 AND ov.is_active = 1
203 INNER JOIN civicrm_acl_entity_role acl_entity_role
204 ON acl_entity_role.acl_role_id = acl.entity_id
205 AND acl_entity_role.is_active = 1
206 INNER JOIN civicrm_group_contact group_contact
207 ON acl_entity_role.entity_id = group_contact.group_id
208 AND acl_entity_role.entity_table = 'civicrm_group'
209 WHERE acl.entity_table = 'civicrm_acl_role'
210 AND acl.is_active = 1
211 AND group_contact.contact_id = $contact_id
212 AND group_contact.status = 'Added'";
213
214 $results = [];
215
216 $rule = CRM_Core_DAO::executeQuery($query);
217
218 while ($rule->fetch()) {
219 $results[$rule->id] = $rule->toArray();
220 }
221
222 // also get all acls for "Any Role" case
223 // and authenticated User Role if present
224 $roles = "0";
225 $session = CRM_Core_Session::singleton();
226 if ($session->get('ufID') > 0) {
227 $roles .= ",2";
228 }
229
230 $query = "
231 SELECT acl.*
232 FROM civicrm_acl acl
233 WHERE acl.entity_id IN ( $roles )
234 AND acl.entity_table = 'civicrm_acl_role'
235 ";
236
237 $rule = CRM_Core_DAO::executeQuery($query);
238 while ($rule->fetch()) {
239 $results[$rule->id] = $rule->toArray();
240 }
241
242 return $results;
243 }
244
245 /**
246 * Get all ACLs owned by a given contact, including domain and group-level.
247 *
248 * @param int $contact_id
249 * The contact ID.
250 *
251 * @return array
252 * Assoc array of ACL rules
253 *
254 * @throws \CRM_Core_Exception
255 */
256 public static function getAllByContact($contact_id) {
257 $result = [];
258
259 /* First, the contact-specific ACLs, including ACL Roles */
260 if ($contact_id) {
261 $result += self::getACLs((int) $contact_id);
262 }
263
264 /* Then, all ACLs granted through group membership */
265 $result += self::getGroupACLs($contact_id, TRUE);
266
267 return $result;
268 }
269
270 /**
271 * @param array $params
272 *
273 * @return CRM_ACL_DAO_ACL
274 */
275 public static function create($params) {
276 $dao = new CRM_ACL_DAO_ACL();
277 $dao->copyValues($params);
278 $dao->save();
279 return $dao;
280 }
281
282 /**
283 * @param array $params
284 * @param array $defaults
285 */
286 public static function retrieve(&$params, &$defaults) {
287 CRM_Core_DAO::commonRetrieve('CRM_ACL_DAO_ACL', $params, $defaults);
288 }
289
290 /**
291 * Update the is_active flag in the db.
292 *
293 * @param int $id
294 * Id of the database record.
295 * @param bool $is_active
296 * Value we want to set the is_active field.
297 *
298 * @return bool
299 * true if we found and updated the object, else false
300 */
301 public static function setIsActive($id, $is_active) {
302 Civi::cache('fields')->flush();
303 // reset ACL and system caches.
304 CRM_Core_BAO_Cache::resetCaches();
305
306 return CRM_Core_DAO::setFieldValue('CRM_ACL_DAO_ACL', $id, 'is_active', $is_active);
307 }
308
309 /**
310 * @param $str
311 * @param int $contactID
312 *
313 * @return bool
314 */
315 public static function check($str, $contactID) {
316
317 $acls = CRM_ACL_BAO_Cache::build($contactID);
318
319 $aclKeys = array_keys($acls);
320 $aclKeys = implode(',', $aclKeys);
321
322 if (empty($aclKeys)) {
323 return FALSE;
324 }
325
326 $query = "
327 SELECT count( a.id )
328 FROM civicrm_acl_cache c, civicrm_acl a
329 WHERE c.acl_id = a.id
330 AND a.is_active = 1
331 AND a.object_table = %1
332 AND a.id IN ( $aclKeys )
333 ";
334 $params = [1 => [$str, 'String']];
335
336 $count = CRM_Core_DAO::singleValueQuery($query, $params);
337 return (bool) $count;
338 }
339
340 /**
341 * @param $type
342 * @param $tables
343 * @param $whereTables
344 * @param int $contactID
345 *
346 * @return null|string
347 */
348 public static function whereClause($type, &$tables, &$whereTables, $contactID = NULL) {
349 $acls = CRM_ACL_BAO_Cache::build($contactID);
350
351 $whereClause = NULL;
352 $clauses = [];
353
354 if (!empty($acls)) {
355 $aclKeys = array_keys($acls);
356 $aclKeys = implode(',', $aclKeys);
357
358 $query = "
359 SELECT a.operation, a.object_id
360 FROM civicrm_acl_cache c, civicrm_acl a
361 WHERE c.acl_id = a.id
362 AND a.is_active = 1
363 AND a.object_table = 'civicrm_saved_search'
364 AND a.id IN ( $aclKeys )
365 ORDER BY a.object_id
366 ";
367
368 $dao = CRM_Core_DAO::executeQuery($query);
369
370 // do an or of all the where clauses u see
371 $ids = [];
372 while ($dao->fetch()) {
373 // make sure operation matches the type TODO
374 if (self::matchType($type, $dao->operation)) {
375 if (!$dao->object_id) {
376 $ids = [];
377 $whereClause = ' ( 1 ) ';
378 break;
379 }
380 $ids[] = $dao->object_id;
381 }
382 }
383
384 if (!empty($ids)) {
385 $ids = implode(',', $ids);
386 $query = "
387 SELECT g.*
388 FROM civicrm_group g
389 WHERE g.id IN ( $ids )
390 AND g.is_active = 1
391 ";
392 $dao = CRM_Core_DAO::executeQuery($query);
393 $groupIDs = [];
394 $groupContactCacheClause = FALSE;
395 while ($dao->fetch()) {
396 $groupIDs[] = $dao->id;
397
398 if (($dao->saved_search_id || $dao->children || $dao->parents)) {
399 if ($dao->cache_date == NULL) {
400 CRM_Contact_BAO_GroupContactCache::load($dao);
401 }
402 $groupContactCacheClause = " UNION SELECT contact_id FROM civicrm_group_contact_cache WHERE group_id IN (" . implode(', ', $groupIDs) . ")";
403 }
404
405 }
406
407 if ($groupIDs) {
408 $clauses[] = "(
409 `contact_a`.id IN (
410 SELECT contact_id FROM civicrm_group_contact WHERE group_id IN (" . implode(', ', $groupIDs) . ") AND status = 'Added'
411 $groupContactCacheClause
412 )
413 )";
414 }
415 }
416 }
417
418 if (!empty($clauses)) {
419 $whereClause = ' ( ' . implode(' OR ', $clauses) . ' ) ';
420 }
421
422 // call the hook to get additional whereClauses
423 CRM_Utils_Hook::aclWhereClause($type, $tables, $whereTables, $contactID, $whereClause);
424
425 if (empty($whereClause)) {
426 $whereClause = ' ( 0 ) ';
427 }
428
429 return $whereClause;
430 }
431
432 /**
433 * @param int $type
434 * @param int $contactID
435 * @param string $tableName
436 * @param null $allGroups
437 * @param null $includedGroups
438 *
439 * @return array
440 */
441 public static function group(
442 $type,
443 $contactID = NULL,
444 $tableName = 'civicrm_saved_search',
445 $allGroups = NULL,
446 $includedGroups = NULL
447 ) {
448 $userCacheKey = "{$contactID}_{$type}_{$tableName}_" . CRM_Core_Config::domainID() . '_' . md5(implode(',', array_merge((array) $allGroups, (array) $includedGroups)));
449 if (empty(Civi::$statics[__CLASS__]['permissioned_groups'])) {
450 Civi::$statics[__CLASS__]['permissioned_groups'] = [];
451 }
452 if (!empty(Civi::$statics[__CLASS__]['permissioned_groups'][$userCacheKey])) {
453 return Civi::$statics[__CLASS__]['permissioned_groups'][$userCacheKey];
454 }
455
456 if ($allGroups == NULL) {
457 $allGroups = CRM_Contact_BAO_Contact::buildOptions('group_id', 'get');
458 }
459
460 $acls = CRM_ACL_BAO_Cache::build($contactID);
461
462 $ids = [];
463 if (!empty($acls)) {
464 $aclKeys = array_keys($acls);
465 $aclKeys = implode(',', $aclKeys);
466
467 $cacheKey = CRM_Utils_Cache::cleanKey("$type-$tableName-$aclKeys");
468 $cache = CRM_Utils_Cache::singleton();
469 $ids = $cache->get($cacheKey);
470 if (!is_array($ids)) {
471 $ids = [];
472 $query = "
473 SELECT a.operation, a.object_id
474 FROM civicrm_acl_cache c, civicrm_acl a
475 WHERE c.acl_id = a.id
476 AND a.is_active = 1
477 AND a.object_table = %1
478 AND a.id IN ( $aclKeys )
479 GROUP BY a.operation,a.object_id
480 ORDER BY a.object_id
481 ";
482 $params = [1 => [$tableName, 'String']];
483 $dao = CRM_Core_DAO::executeQuery($query, $params);
484 while ($dao->fetch()) {
485 if ($dao->object_id) {
486 if (self::matchType($type, $dao->operation)) {
487 $ids[] = $dao->object_id;
488 }
489 }
490 else {
491 // this user has got the permission for all objects of this type
492 // check if the type matches
493 if (self::matchType($type, $dao->operation)) {
494 foreach ($allGroups as $id => $dontCare) {
495 $ids[] = $id;
496 }
497 }
498 break;
499 }
500 }
501 $cache->set($cacheKey, $ids);
502 }
503 }
504
505 if (empty($ids) && !empty($includedGroups) &&
506 is_array($includedGroups)
507 ) {
508 // This is pretty alarming - we 'sometimes' include all included groups
509 // seems problematic per https://lab.civicrm.org/dev/core/-/issues/1879
510 $ids = $includedGroups;
511 }
512 if ($contactID) {
513 $groupWhere = '';
514 if (!empty($allGroups)) {
515 $groupWhere = " AND id IN (" . implode(',', array_keys($allGroups)) . ")";
516 }
517 // Contacts create hidden groups from search results. They should be able to retrieve their own.
518 $ownHiddenGroupsList = CRM_Core_DAO::singleValueQuery("
519 SELECT GROUP_CONCAT(id) FROM civicrm_group WHERE is_hidden =1 AND created_id = $contactID
520 $groupWhere
521 ");
522 if ($ownHiddenGroupsList) {
523 $ownHiddenGroups = explode(',', $ownHiddenGroupsList);
524 $ids = array_merge((array) $ids, $ownHiddenGroups);
525 }
526
527 }
528
529 CRM_Utils_Hook::aclGroup($type, $contactID, $tableName, $allGroups, $ids);
530 Civi::$statics[__CLASS__]['permissioned_groups'][$userCacheKey] = $ids;
531 return $ids;
532 }
533
534 /**
535 * @param int $type
536 * @param $operation
537 *
538 * @return bool
539 */
540 protected static function matchType($type, $operation) {
541 $typeCheck = FALSE;
542 switch ($operation) {
543 case 'All':
544 $typeCheck = TRUE;
545 break;
546
547 case 'View':
548 if ($type == CRM_ACL_API::VIEW) {
549 $typeCheck = TRUE;
550 }
551 break;
552
553 case 'Edit':
554 if ($type == CRM_ACL_API::VIEW || $type == CRM_ACL_API::EDIT) {
555 $typeCheck = TRUE;
556 }
557 break;
558
559 case 'Create':
560 if ($type == CRM_ACL_API::CREATE) {
561 $typeCheck = TRUE;
562 }
563 break;
564
565 case 'Delete':
566 if ($type == CRM_ACL_API::DELETE) {
567 $typeCheck = TRUE;
568 }
569 break;
570
571 case 'Search':
572 if ($type == CRM_ACL_API::SEARCH) {
573 $typeCheck = TRUE;
574 }
575 break;
576 }
577 return $typeCheck;
578 }
579
580 /**
581 * Delete ACL records.
582 *
583 * @param int $aclId
584 * ID of the ACL record to be deleted.
585 *
586 */
587 public static function del($aclId) {
588 // delete all entries from the acl cache
589 CRM_ACL_BAO_Cache::resetCache();
590
591 $acl = new CRM_ACL_DAO_ACL();
592 $acl->id = $aclId;
593 $acl->delete();
594 }
595
596 }