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