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