3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2020
33 class CRM_Contact_BAO_Contact_Permission
{
38 public static $useTempTable = TRUE;
41 * Set whether to use a temporary table or not when building ACL Cache
42 * @param bool $useTemporaryTable
44 public static function setUseTemporaryTable($useTemporaryTable = TRUE) {
45 self
::$useTempTable = $useTemporaryTable;
49 * Get variable for determining if we should use Temporary Table or not
52 public static function getUseTemporaryTable() {
53 return self
::$useTempTable;
57 * Check which of the given contact IDs the logged in user
58 * has permissions for the operation type according to:
59 * - general permissions (e.g. 'edit all contacts')
60 * - deletion status (unless you have 'access deleted contacts')
62 * - permissions inherited through relationships (also second degree if enabled)
64 * @param array $contact_ids
66 * @param int $type the type of operation (view|edit)
68 * @see CRM_Contact_BAO_Contact_Permission::allow
71 * list of contact IDs the logged in user has the given permission for
73 public static function allowList($contact_ids, $type = CRM_Core_Permission
::VIEW
) {
75 if (empty($contact_ids)) {
76 // empty contact lists would cause trouble in the SQL. And be pointless.
80 // make sure the the general permissions are given
81 if (CRM_Core_Permission
::check('edit all contacts')
82 ||
$type == CRM_Core_Permission
::VIEW
&& CRM_Core_Permission
::check('view all contacts')
85 // if the general permission is there, all good
86 if (CRM_Core_Permission
::check('access deleted contacts')) {
87 // if user can access deleted contacts -> fine
91 // if the user CANNOT access deleted contacts, these need to be filtered
92 $contact_id_list = implode(',', $contact_ids);
93 $filter_query = "SELECT DISTINCT(id) FROM civicrm_contact WHERE id IN ($contact_id_list) AND is_deleted = 0";
94 $query = CRM_Core_DAO
::executeQuery($filter_query);
95 while ($query->fetch()) {
96 $result_set[(int) $query->id
] = TRUE;
98 return array_keys($result_set);
102 // get logged in user
103 $contactID = CRM_Core_Session
::getLoggedInContactID();
104 if (empty($contactID)) {
108 // make sure the cache is filled
109 self
::cache($contactID, $type);
112 $operation = ($type == CRM_Core_Permission
::VIEW
) ?
'View' : 'Edit';
114 // add clause for deleted contacts, if the user doesn't have the permission to access them
115 $LEFT_JOIN_DELETED = $AND_CAN_ACCESS_DELETED = '';
116 if (!CRM_Core_Permission
::check('access deleted contacts')) {
117 $LEFT_JOIN_DELETED = "LEFT JOIN civicrm_contact ON civicrm_contact.id = contact_id";
118 $AND_CAN_ACCESS_DELETED = "AND civicrm_contact.is_deleted = 0";
122 $contact_id_list = implode(',', $contact_ids);
125 FROM civicrm_acl_contact_cache
127 WHERE contact_id IN ({$contact_id_list})
128 AND user_id = {$contactID}
129 AND operation = '{$operation}'
130 {$AND_CAN_ACCESS_DELETED}";
131 $result = CRM_Core_DAO
::executeQuery($query);
132 while ($result->fetch()) {
133 $result_set[(int) $result->contact_id
] = TRUE;
136 // if some have been rejected, double check for permissions inherited by relationship
137 if (count($result_set) < count($contact_ids)) {
138 $rejected_contacts = array_diff_key($contact_ids, $result_set);
139 // @todo consider storing these to the acl cache for next time, since we have fetched.
140 $allowed_by_relationship = self
::relationshipList($rejected_contacts, $type);
141 foreach ($allowed_by_relationship as $contact_id) {
142 $result_set[(int) $contact_id] = TRUE;
146 return array_keys($result_set);
150 * Check if the logged in user has permissions for the operation type.
154 * @param int|string $type the type of operation (view|edit)
157 * true if the user has permission, false otherwise
159 public static function allow($id, $type = CRM_Core_Permission
::VIEW
) {
160 // get logged in user
161 $contactID = CRM_Core_Session
::getLoggedInContactID();
163 // first: check if contact is trying to view own contact
164 if ($contactID == $id && ($type == CRM_Core_Permission
::VIEW
&& CRM_Core_Permission
::check('view my contact')
165 ||
$type == CRM_Core_Permission
::EDIT
&& CRM_Core_Permission
::check('edit my contact'))
170 // FIXME: push this somewhere below, to not give this permission so many rights
171 $isDeleted = (bool) CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'is_deleted');
172 if (CRM_Core_Permission
::check('access deleted contacts') && $isDeleted) {
176 // short circuit for admin rights here so we avoid unneeeded queries
177 // some duplication of code, but we skip 3-5 queries
178 if (CRM_Core_Permission
::check('edit all contacts') ||
179 ($type == CRM_ACL_API
::VIEW
&& CRM_Core_Permission
::check('view all contacts'))
184 // check permission based on relationship, CRM-2963
185 if (self
::relationshipList([$id], $type)) {
189 // We should probably do a cheap check whether it's in the cache first.
190 // check permission based on ACL
194 $permission = CRM_ACL_API
::whereClause($type, $tables, $whereTables, NULL, FALSE, FALSE, TRUE);
195 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
200 WHERE contact_a.id = %1 AND $permission
204 if (CRM_Core_DAO
::singleValueQuery($query, [1 => [$id, 'Integer']])) {
211 * Fill the acl contact cache for this ACLed contact id if empty.
213 * @param int $userID - contact_id of the ACLed user
214 * @param int|string $type the type of operation (view|edit)
215 * @param bool $force - Should we force a recompute.
218 public static function cache($userID, $type = CRM_Core_Permission
::VIEW
, $force = FALSE) {
219 // FIXME: maybe find a better way of keeping track of this. @eileen pointed out
220 // that somebody might flush the cache away from under our feet,
221 // but the alternative would be a SQL call every time this is called,
222 // and a complete rebuild if the result was an empty set...
223 if (!isset(Civi
::$statics[__CLASS__
]['processed'])) {
224 Civi
::$statics[__CLASS__
]['processed'] = [
225 CRM_Core_Permission
::VIEW
=> [],
226 CRM_Core_Permission
::EDIT
=> [],
230 if ($type == CRM_Core_Permission
::VIEW
) {
231 $operationClause = " operation IN ( 'Edit', 'View' ) ";
235 $operationClause = " operation = 'Edit' ";
238 $queryParams = [1 => [$userID, 'Integer']];
241 // skip if already calculated
242 if (!empty(Civi
::$statics[__CLASS__
]['processed'][$type][$userID])) {
246 // run a query to see if the cache is filled
249 FROM civicrm_acl_contact_cache
253 $count = CRM_Core_DAO
::singleValueQuery($sql, $queryParams);
255 Civi
::$statics[__CLASS__
]['processed'][$type][$userID] = 1;
260 // grab a lock so other processes don't compete and do the same query
261 $lock = Civi
::lockManager()->acquire("data.core.aclcontact.{$userID}");
262 if (!$lock->isAcquired()) {
263 // this can cause inconsistent results since we don't know if the other process
264 // will fill up the cache before our calling routine needs it.
265 // The default 3 second timeout should be enough for the other process to finish.
266 // However this routine does not return the status either, so basically
267 // its a "lets return and hope for the best"
274 $permission = CRM_ACL_API
::whereClause($type, $tables, $whereTables, $userID, FALSE, FALSE, TRUE);
276 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
277 /* Ends up something like this:
278 CREATE TEMPORARY TABLE civicrm_temp_acl_contact_cache1310 (SELECT DISTINCT 2960 as user_id, contact_a.id as contact_id, 'View' as operation
279 FROM civicrm_contact contact_a LEFT JOIN civicrm_group_contact_cache `civicrm_group_contact_cache-ACL` ON contact_a.id = `civicrm_group_contact_cache-ACL`.contact_id
280 LEFT JOIN civicrm_acl_contact_cache ac ON ac.user_id = 2960 AND ac.contact_id = contact_a.id AND ac.operation = 'View'
281 WHERE ( `civicrm_group_contact_cache-ACL`.group_id IN (14, 25, 46, 47, 48, 49, 50, 51) ) AND (contact_a.is_deleted = 0)
282 AND ac.user_id IS NULL*/
283 /*$sql = "SELECT DISTINCT $userID as user_id, contact_a.id as contact_id, '{$operation}' as operation
285 LEFT JOIN civicrm_acl_contact_cache ac ON ac.user_id = $userID AND ac.contact_id = contact_a.id AND ac.operation = '{$operation}'
287 AND ac.user_id IS NULL
289 $sql = "SELECT DISTINCT $userID as user_id, contact_a.id as contact_id, '{$operation}' as operation
292 $useTempTable = self
::getUseTemporaryTable();
294 $aclContactsTempTable = CRM_Utils_SQL_TempTable
::build()->setCategory('aclccache')->setMemory();
295 $tempTable = $aclContactsTempTable->getName();
296 $aclContactsTempTable->createWithColumns('user_id int, contact_id int, operation varchar(255), UNIQUE UI_user_contact_operation (user_id,contact_id,operation)');
297 CRM_Core_DAO
::executeQuery("INSERT INTO {$tempTable} (user_id, contact_id, operation) {$sql}");
298 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO civicrm_acl_contact_cache (user_id, contact_id, operation) SELECT user_id, contact_id, operation FROM {$tempTable}");
299 $aclContactsTempTable->drop();
302 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO civicrm_acl_contact_cache (user_id, contact_id, operation) {$sql}");
305 // Add in a row for the logged in contact. Do not try to combine with the above query or an ugly OR will appear in
306 // the permission clause.
307 if (CRM_Core_Permission
::check('edit my contact') ||
308 ($type == CRM_Core_Permission
::VIEW
&& CRM_Core_Permission
::check('view my contact'))) {
309 if (!CRM_Core_DAO
::singleValueQuery("
310 SELECT count(*) FROM civicrm_acl_contact_cache WHERE user_id = %1 AND contact_id = %1 AND operation = '{$operation}' LIMIT 1", $queryParams)) {
311 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO civicrm_acl_contact_cache ( user_id, contact_id, operation ) VALUES(%1, %1, '{$operation}')", $queryParams);
314 Civi
::$statics[__CLASS__
]['processed'][$type][$userID] = 1;
319 * @param string $contactAlias
323 public static function cacheClause($contactAlias = 'contact_a') {
324 if (CRM_Core_Permission
::check('view all contacts') ||
325 CRM_Core_Permission
::check('edit all contacts')
327 if (is_array($contactAlias)) {
329 foreach ($contactAlias as $alias) {
331 $wheres[] = "$alias.is_deleted = 0";
333 return [NULL, '(' . implode(' AND ', $wheres) . ')'];
337 return [NULL, "$contactAlias.is_deleted = 0"];
341 $contactID = (int) CRM_Core_Session
::getLoggedInContactID();
342 self
::cache($contactID);
344 if (is_array($contactAlias) && !empty($contactAlias)) {
345 //More than one contact alias
347 foreach ($contactAlias as $k => $alias) {
348 $clauses[] = " INNER JOIN civicrm_acl_contact_cache aclContactCache_{$k} ON {$alias}.id = aclContactCache_{$k}.contact_id AND aclContactCache_{$k}.user_id = $contactID ";
351 $fromClause = implode(" ", $clauses);
355 $fromClause = " INNER JOIN civicrm_acl_contact_cache aclContactCache ON {$contactAlias}.id = aclContactCache.contact_id ";
356 $whereClase = " aclContactCache.user_id = $contactID AND $contactAlias.is_deleted = 0";
359 return [$fromClause, $whereClase];
363 * Generate acl subquery that can be placed in the WHERE clause of a query or the ON clause of a JOIN.
365 * This is specifically for VIEW operations.
367 * @return string|null
369 public static function cacheSubquery() {
370 if (!CRM_Core_Permission
::check([['view all contacts', 'edit all contacts']])) {
371 $contactID = (int) CRM_Core_Session
::getLoggedInContactID();
372 self
::cache($contactID);
373 return "IN (SELECT contact_id FROM civicrm_acl_contact_cache WHERE user_id = $contactID)";
379 * Filter a list of contact_ids by the ones that the
380 * currently active user as a permissioned relationship with
382 * @param array $contact_ids
383 * List of contact IDs to be filtered
386 * access type CRM_Core_Permission::VIEW or CRM_Core_Permission::EDIT
389 * List of contact IDs that the user has permissions for
391 public static function relationshipList($contact_ids, $type) {
394 // no processing empty lists (avoid SQL errors as well)
395 if (empty($contact_ids)) {
399 // get the currently logged in user
400 $contactID = CRM_Core_Session
::getLoggedInContactID();
401 if (empty($contactID)) {
405 // compile a list of queries (later to UNION)
407 $contact_id_list = implode(',', $contact_ids);
409 // add a select statement for each direction
410 $directions = [['from' => 'a', 'to' => 'b'], ['from' => 'b', 'to' => 'a']];
412 // CRM_Core_Permission::VIEW is satisfied by either CRM_Contact_BAO_Relationship::VIEW or CRM_Contact_BAO_Relationship::EDIT
413 if ($type == CRM_Core_Permission
::VIEW
) {
414 $is_perm_condition = ' IN ( ' . CRM_Contact_BAO_Relationship
::EDIT
. ' , ' . CRM_Contact_BAO_Relationship
::VIEW
. ' ) ';
417 $is_perm_condition = ' = ' . CRM_Contact_BAO_Relationship
::EDIT
;
420 // NORMAL/SINGLE DEGREE RELATIONSHIPS
421 foreach ($directions as $direction) {
422 $user_id_column = "contact_id_{$direction['from']}";
423 $contact_id_column = "contact_id_{$direction['to']}";
425 // add clause for deleted contacts, if the user doesn't have the permission to access them
426 $LEFT_JOIN_DELETED = $AND_CAN_ACCESS_DELETED = '';
427 if (!CRM_Core_Permission
::check('access deleted contacts')) {
428 $LEFT_JOIN_DELETED = "LEFT JOIN civicrm_contact ON civicrm_contact.id = {$contact_id_column} ";
429 $AND_CAN_ACCESS_DELETED = "AND civicrm_contact.is_deleted = 0";
433 SELECT civicrm_relationship.{$contact_id_column} AS contact_id
434 FROM civicrm_relationship
436 WHERE civicrm_relationship.{$user_id_column} = {$contactID}
437 AND civicrm_relationship.{$contact_id_column} IN ({$contact_id_list})
438 AND civicrm_relationship.is_active = 1
439 AND civicrm_relationship.is_permission_{$direction['from']}_{$direction['to']} {$is_perm_condition}
440 $AND_CAN_ACCESS_DELETED";
443 // FIXME: secondDegRelPermissions should be a setting
444 $config = CRM_Core_Config
::singleton();
445 if ($config->secondDegRelPermissions
) {
446 foreach ($directions as $first_direction) {
447 foreach ($directions as $second_direction) {
448 // add clause for deleted contacts, if the user doesn't have the permission to access them
449 $LEFT_JOIN_DELETED = $AND_CAN_ACCESS_DELETED = '';
450 if (!CRM_Core_Permission
::check('access deleted contacts')) {
451 $LEFT_JOIN_DELETED = "LEFT JOIN civicrm_contact first_degree_contact ON first_degree_contact.id = second_degree_relationship.contact_id_{$second_direction['from']}\n";
452 $LEFT_JOIN_DELETED .= "LEFT JOIN civicrm_contact second_degree_contact ON second_degree_contact.id = second_degree_relationship.contact_id_{$second_direction['to']} ";
453 $AND_CAN_ACCESS_DELETED = "AND first_degree_contact.is_deleted = 0\n";
454 $AND_CAN_ACCESS_DELETED .= "AND second_degree_contact.is_deleted = 0 ";
458 SELECT second_degree_relationship.contact_id_{$second_direction['to']} AS contact_id
459 FROM civicrm_relationship first_degree_relationship
460 LEFT JOIN civicrm_relationship second_degree_relationship ON first_degree_relationship.contact_id_{$first_direction['to']} = second_degree_relationship.contact_id_{$second_direction['from']}
462 WHERE first_degree_relationship.contact_id_{$first_direction['from']} = {$contactID}
463 AND second_degree_relationship.contact_id_{$second_direction['to']} IN ({$contact_id_list})
464 AND first_degree_relationship.is_active = 1
465 AND first_degree_relationship.is_permission_{$first_direction['from']}_{$first_direction['to']} {$is_perm_condition}
466 AND second_degree_relationship.is_active = 1
467 AND second_degree_relationship.is_permission_{$second_direction['from']}_{$second_direction['to']} {$is_perm_condition}
468 $AND_CAN_ACCESS_DELETED";
473 // finally UNION the queries and call
474 $query = "(" . implode(")\nUNION DISTINCT (", $queries) . ")";
475 $result = CRM_Core_DAO
::executeQuery($query);
476 while ($result->fetch()) {
477 $result_set[(int) $result->contact_id
] = TRUE;
479 return array_keys($result_set);
483 * @param int $contactID
484 * @param CRM_Core_Form $form
485 * @param bool $redirect
489 public static function validateOnlyChecksum($contactID, &$form, $redirect = TRUE) {
490 // check if this is of the format cs=XXX
491 if (!CRM_Contact_BAO_Contact_Utils
::validChecksum($contactID,
492 CRM_Utils_Request
::retrieve('cs', 'String', $form, FALSE)
496 // also set a message in the UF framework
497 $message = ts('You do not have permission to edit this contact record. Contact the site administrator if you need assistance.');
498 CRM_Utils_System
::setUFMessage($message);
500 $config = CRM_Core_Config
::singleton();
501 CRM_Core_Error
::statusBounce($message,
502 $config->userFrameworkBaseURL
504 // does not come here, we redirect in the above statement
509 // set appropriate AUTH source
510 self
::initChecksumAuthSrc(TRUE, $form);
512 // so here the contact is posing as $contactID, lets set the logging contact ID variable
514 CRM_Core_DAO
::executeQuery('SET @civicrm_user_id = %1',
515 [1 => [$contactID, 'Integer']]
522 * @param bool $checkSumValidationResult
525 public static function initChecksumAuthSrc($checkSumValidationResult = FALSE, $form = NULL) {
526 $session = CRM_Core_Session
::singleton();
527 if ($checkSumValidationResult && $form && CRM_Utils_Request
::retrieve('cs', 'String', $form, FALSE)) {
528 // if result is already validated, and url has cs, set the flag.
529 $session->set('authSrc', CRM_Core_Permission
::AUTH_SRC_CHECKSUM
);
531 elseif (($session->get('authSrc') & CRM_Core_Permission
::AUTH_SRC_CHECKSUM
) == CRM_Core_Permission
::AUTH_SRC_CHECKSUM
) {
532 // if checksum wasn't present in REQUEST OR checksum result validated as FALSE,
533 // and flag was already set exactly as AUTH_SRC_CHECKSUM, unset it.
534 $session->set('authSrc', CRM_Core_Permission
::AUTH_SRC_UNKNOWN
);
539 * @param int $contactID
540 * @param CRM_Core_Form $form
541 * @param bool $redirect
545 public static function validateChecksumContact($contactID, &$form, $redirect = TRUE) {
546 if (!self
::allow($contactID, CRM_Core_Permission
::EDIT
)) {
547 // check if this is of the format cs=XXX
548 return self
::validateOnlyChecksum($contactID, $form, $redirect);