3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
33 class CRM_Contact_BAO_Contact_Permission
{
36 * Check which of the given contact IDs the logged in user
37 * has permissions for the operation type according to:
38 * - general permissions (e.g. 'edit all contacts')
39 * - deletion status (unless you have 'access deleted contacts')
41 * - permissions inherited through relationships (also second degree if enabled)
43 * @param array $contact_ids
45 * @param int $type the type of operation (view|edit)
47 * @see CRM_Contact_BAO_Contact_Permission::allow
50 * list of contact IDs the logged in user has the given permission for
52 public static function allowList($contact_ids, $type = CRM_Core_Permission
::VIEW
) {
53 $result_set = array();
54 if (empty($contact_ids)) {
55 // empty contact lists would cause trouble in the SQL. And be pointless.
59 // make sure the the general permissions are given
60 if (CRM_Core_Permission
::check('edit all contacts')
61 ||
$type == CRM_Core_Permission
::VIEW
&& CRM_Core_Permission
::check('view all contacts')
64 // if the general permission is there, all good
65 if (CRM_Core_Permission
::check('access deleted contacts')) {
66 // if user can access deleted contacts -> fine
70 // if the user CANNOT access deleted contacts, these need to be filtered
71 $contact_id_list = implode(',', $contact_ids);
72 $filter_query = "SELECT DISTINCT(id) FROM civicrm_contact WHERE id IN ($contact_id_list) AND is_deleted = 0";
73 $query = CRM_Core_DAO
::executeQuery($filter_query);
74 while ($query->fetch()) {
75 $result_set[(int) $query->id
] = TRUE;
77 return array_keys($result_set);
82 $contactID = CRM_Core_Session
::getLoggedInContactID();
83 if (empty($contactID)) {
87 // make sure the cache is filled
88 self
::cache($contactID, $type);
91 $operation = ($type == CRM_Core_Permission
::VIEW
) ?
'View' : 'Edit';
93 // add clause for deleted contacts, if the user doesn't have the permission to access them
94 $LEFT_JOIN_DELETED = $AND_CAN_ACCESS_DELETED = '';
95 if (!CRM_Core_Permission
::check('access deleted contacts')) {
96 $LEFT_JOIN_DELETED = "LEFT JOIN civicrm_contact ON civicrm_contact.id = contact_id";
97 $AND_CAN_ACCESS_DELETED = "AND civicrm_contact.is_deleted = 0";
101 $contact_id_list = implode(',', $contact_ids);
104 FROM civicrm_acl_contact_cache
106 WHERE contact_id IN ({$contact_id_list})
107 AND user_id = {$contactID}
108 AND operation = '{$operation}'
109 {$AND_CAN_ACCESS_DELETED}";
110 $result = CRM_Core_DAO
::executeQuery($query);
111 while ($result->fetch()) {
112 $result_set[(int) $result->contact_id
] = TRUE;
115 // if some have been rejected, double check for permissions inherited by relationship
116 if (count($result_set) < count($contact_ids)) {
117 $rejected_contacts = array_diff_key($contact_ids, $result_set);
118 // @todo consider storing these to the acl cache for next time, since we have fetched.
119 $allowed_by_relationship = self
::relationshipList($rejected_contacts);
120 foreach ($allowed_by_relationship as $contact_id) {
121 $result_set[(int) $contact_id] = TRUE;
125 return array_keys($result_set);
129 * Check if the logged in user has permissions for the operation type.
133 * @param int|string $type the type of operation (view|edit)
136 * true if the user has permission, false otherwise
138 public static function allow($id, $type = CRM_Core_Permission
::VIEW
) {
139 // get logged in user
140 $contactID = CRM_Core_Session
::getLoggedInContactID();
142 // first: check if contact is trying to view own contact
143 if ($contactID == $id && ($type == CRM_Core_Permission
::VIEW
&& CRM_Core_Permission
::check('view my contact')
144 ||
$type == CRM_Core_Permission
::EDIT
&& CRM_Core_Permission
::check('edit my contact'))
149 # FIXME: push this somewhere below, to not give this permission so many rights
150 $isDeleted = (bool) CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $id, 'is_deleted');
151 if (CRM_Core_Permission
::check('access deleted contacts') && $isDeleted) {
155 // short circuit for admin rights here so we avoid unneeeded queries
156 // some duplication of code, but we skip 3-5 queries
157 if (CRM_Core_Permission
::check('edit all contacts') ||
158 ($type == CRM_ACL_API
::VIEW
&& CRM_Core_Permission
::check('view all contacts'))
163 // check permission based on relationship, CRM-2963
164 if (self
::relationshipList(array($id))) {
168 // We should probably do a cheap check whether it's in the cache first.
169 // check permission based on ACL
171 $whereTables = array();
173 $permission = CRM_ACL_API
::whereClause($type, $tables, $whereTables, NULL, FALSE, FALSE, TRUE);
174 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
179 WHERE contact_a.id = %1 AND $permission
183 if (CRM_Core_DAO
::singleValueQuery($query, array(1 => array($id, 'Integer')))) {
190 * Fill the acl contact cache for this contact id if empty.
193 * @param int|string $type the type of operation (view|edit)
195 * Should we force a recompute.
197 public static function cache($userID, $type = CRM_Core_Permission
::VIEW
, $force = FALSE) {
198 // FIXME: maybe find a better way of keeping track of this. @eileen pointed out
199 // that somebody might flush the cache away from under our feet,
200 // but the alternative would be a SQL call every time this is called,
201 // and a complete rebuild if the result was an empty set...
202 if (!isset(Civi
::$statics[__CLASS__
]['processed'])) {
203 Civi
::$statics[__CLASS__
]['processed'] = [
204 CRM_Core_Permission
::VIEW
=> [],
205 CRM_Core_Permission
::EDIT
=> [],
209 if ($type == CRM_Core_Permission
::VIEW
) {
210 $operationClause = " operation IN ( 'Edit', 'View' ) ";
214 $operationClause = " operation = 'Edit' ";
217 $queryParams = array(1 => array($userID, 'Integer'));
220 // skip if already calculated
221 if (!empty(Civi
::$statics[__CLASS__
]['processed'][$type][$userID])) {
225 // run a query to see if the cache is filled
228 FROM civicrm_acl_contact_cache
232 $count = CRM_Core_DAO
::singleValueQuery($sql, $queryParams);
234 Civi
::$statics[__CLASS__
]['processed'][$type][$userID] = 1;
240 $whereTables = array();
242 $permission = CRM_ACL_API
::whereClause($type, $tables, $whereTables, $userID, FALSE, FALSE, TRUE);
244 $from = CRM_Contact_BAO_Query
::fromClause($whereTables);
245 CRM_Core_DAO
::executeQuery("
246 INSERT INTO civicrm_acl_contact_cache ( user_id, contact_id, operation )
247 SELECT DISTINCT $userID as user_id, contact_a.id as contact_id, '{$operation}' as operation
249 LEFT JOIN civicrm_acl_contact_cache ac ON ac.user_id = $userID AND ac.contact_id = contact_a.id AND ac.operation = '{$operation}'
251 AND ac.user_id IS NULL
254 // 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
255 // the permission clause.
256 if (CRM_Core_Permission
::check('edit my contact') ||
257 ($type == CRM_Core_Permission
::VIEW
&& CRM_Core_Permission
::check('view my contact'))) {
258 if (!CRM_Core_DAO
::singleValueQuery("
259 SELECT count(*) FROM civicrm_acl_contact_cache WHERE user_id = %1 AND contact_id = %1 AND operation = '{$operation}' LIMIT 1", $queryParams)) {
260 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_acl_contact_cache ( user_id, contact_id, operation ) VALUES(%1, %1, '{$operation}')", $queryParams);
263 Civi
::$statics[__CLASS__
]['processed'][$type][$userID] = 1;
267 * @param string $contactAlias
271 public static function cacheClause($contactAlias = 'contact_a') {
272 if (CRM_Core_Permission
::check('view all contacts') ||
273 CRM_Core_Permission
::check('edit all contacts')
275 if (is_array($contactAlias)) {
277 foreach ($contactAlias as $alias) {
279 $wheres[] = "$alias.is_deleted = 0";
281 return array(NULL, '(' . implode(' AND ', $wheres) . ')');
285 return array(NULL, "$contactAlias.is_deleted = 0");
289 $contactID = (int) CRM_Core_Session
::getLoggedInContactID();
290 self
::cache($contactID);
292 if (is_array($contactAlias) && !empty($contactAlias)) {
293 //More than one contact alias
295 foreach ($contactAlias as $k => $alias) {
296 $clauses[] = " INNER JOIN civicrm_acl_contact_cache aclContactCache_{$k} ON {$alias}.id = aclContactCache_{$k}.contact_id AND aclContactCache_{$k}.user_id = $contactID ";
299 $fromClause = implode(" ", $clauses);
303 $fromClause = " INNER JOIN civicrm_acl_contact_cache aclContactCache ON {$contactAlias}.id = aclContactCache.contact_id ";
304 $whereClase = " aclContactCache.user_id = $contactID AND $contactAlias.is_deleted = 0";
307 return array($fromClause, $whereClase);
311 * Generate acl subquery that can be placed in the WHERE clause of a query or the ON clause of a JOIN.
313 * This is specifically for VIEW operations.
315 * @return string|null
317 public static function cacheSubquery() {
318 if (!CRM_Core_Permission
::check(array(array('view all contacts', 'edit all contacts')))) {
319 $contactID = (int) CRM_Core_Session
::getLoggedInContactID();
320 self
::cache($contactID);
321 return "IN (SELECT contact_id FROM civicrm_acl_contact_cache WHERE user_id = $contactID)";
327 * Filter a list of contact_ids by the ones that the
328 * currently active user as a permissioned relationship with
330 * @param array $contact_ids
331 * List of contact IDs to be filtered
334 * List of contact IDs that the user has permissions for
336 public static function relationshipList($contact_ids) {
337 $result_set = array();
339 // no processing empty lists (avoid SQL errors as well)
340 if (empty($contact_ids)) {
344 // get the currently logged in user
345 $contactID = CRM_Core_Session
::getLoggedInContactID();
346 if (empty($contactID)) {
350 // compile a list of queries (later to UNION)
352 $contact_id_list = implode(',', $contact_ids);
354 // add a select statement for each direection
355 $directions = array(array('from' => 'a', 'to' => 'b'), array('from' => 'b', 'to' => 'a'));
357 // NORMAL/SINGLE DEGREE RELATIONSHIPS
358 foreach ($directions as $direction) {
359 $user_id_column = "contact_id_{$direction['from']}";
360 $contact_id_column = "contact_id_{$direction['to']}";
362 // add clause for deleted contacts, if the user doesn't have the permission to access them
363 $LEFT_JOIN_DELETED = $AND_CAN_ACCESS_DELETED = '';
364 if (!CRM_Core_Permission
::check('access deleted contacts')) {
365 $LEFT_JOIN_DELETED = "LEFT JOIN civicrm_contact ON civicrm_contact.id = {$contact_id_column} ";
366 $AND_CAN_ACCESS_DELETED = "AND civicrm_contact.is_deleted = 0";
370 SELECT civicrm_relationship.{$contact_id_column} AS contact_id
371 FROM civicrm_relationship
373 WHERE civicrm_relationship.{$user_id_column} = {$contactID}
374 AND civicrm_relationship.{$contact_id_column} IN ({$contact_id_list})
375 AND civicrm_relationship.is_active = 1
376 AND civicrm_relationship.is_permission_{$direction['from']}_{$direction['to']} = 1
377 $AND_CAN_ACCESS_DELETED";
380 // FIXME: secondDegRelPermissions should be a setting
381 $config = CRM_Core_Config
::singleton();
382 if ($config->secondDegRelPermissions
) {
383 foreach ($directions as $first_direction) {
384 foreach ($directions as $second_direction) {
385 // add clause for deleted contacts, if the user doesn't have the permission to access them
386 $LEFT_JOIN_DELETED = $AND_CAN_ACCESS_DELETED = '';
387 if (!CRM_Core_Permission
::check('access deleted contacts')) {
388 $LEFT_JOIN_DELETED = "LEFT JOIN civicrm_contact first_degree_contact ON first_degree_contact.id = second_degree_relationship.contact_id_{$second_direction['from']}\n";
389 $LEFT_JOIN_DELETED .= "LEFT JOIN civicrm_contact second_degree_contact ON second_degree_contact.id = second_degree_relationship.contact_id_{$second_direction['to']} ";
390 $AND_CAN_ACCESS_DELETED = "AND first_degree_contact.is_deleted = 0\n";
391 $AND_CAN_ACCESS_DELETED .= "AND second_degree_contact.is_deleted = 0 ";
395 SELECT second_degree_relationship.contact_id_{$second_direction['to']} AS contact_id
396 FROM civicrm_relationship first_degree_relationship
397 LEFT JOIN civicrm_relationship second_degree_relationship ON first_degree_relationship.contact_id_{$first_direction['to']} = second_degree_relationship.contact_id_{$first_direction['from']}
399 WHERE first_degree_relationship.contact_id_{$first_direction['from']} = {$contactID}
400 AND second_degree_relationship.contact_id_{$second_direction['to']} IN ({$contact_id_list})
401 AND first_degree_relationship.is_active = 1
402 AND first_degree_relationship.is_permission_{$first_direction['from']}_{$first_direction['to']} = 1
403 AND second_degree_relationship.is_active = 1
404 AND second_degree_relationship.is_permission_{$second_direction['from']}_{$second_direction['to']} = 1
405 $AND_CAN_ACCESS_DELETED";
410 // finally UNION the queries and call
411 $query = "(" . implode(")\nUNION DISTINCT (", $queries) . ")";
412 $result = CRM_Core_DAO
::executeQuery($query);
413 while ($result->fetch()) {
414 $result_set[(int) $result->contact_id
] = TRUE;
416 return array_keys($result_set);
421 * @param int $contactID
422 * @param CRM_Core_Form $form
423 * @param bool $redirect
427 public static function validateOnlyChecksum($contactID, &$form, $redirect = TRUE) {
428 // check if this is of the format cs=XXX
429 if (!CRM_Contact_BAO_Contact_Utils
::validChecksum($contactID,
430 CRM_Utils_Request
::retrieve('cs', 'String', $form, FALSE)
434 // also set a message in the UF framework
435 $message = ts('You do not have permission to edit this contact record. Contact the site administrator if you need assistance.');
436 CRM_Utils_System
::setUFMessage($message);
438 $config = CRM_Core_Config
::singleton();
439 CRM_Core_Error
::statusBounce($message,
440 $config->userFrameworkBaseURL
442 // does not come here, we redirect in the above statement
447 // set appropriate AUTH source
448 self
::initChecksumAuthSrc(TRUE, $form);
450 // so here the contact is posing as $contactID, lets set the logging contact ID variable
452 CRM_Core_DAO
::executeQuery('SET @civicrm_user_id = %1',
453 array(1 => array($contactID, 'Integer'))
460 * @param bool $checkSumValidationResult
463 public static function initChecksumAuthSrc($checkSumValidationResult = FALSE, $form = NULL) {
464 $session = CRM_Core_Session
::singleton();
465 if ($checkSumValidationResult && $form && CRM_Utils_Request
::retrieve('cs', 'String', $form, FALSE)) {
466 // if result is already validated, and url has cs, set the flag.
467 $session->set('authSrc', CRM_Core_Permission
::AUTH_SRC_CHECKSUM
);
469 elseif (($session->get('authSrc') & CRM_Core_Permission
::AUTH_SRC_CHECKSUM
) == CRM_Core_Permission
::AUTH_SRC_CHECKSUM
) {
470 // if checksum wasn't present in REQUEST OR checksum result validated as FALSE,
471 // and flag was already set exactly as AUTH_SRC_CHECKSUM, unset it.
472 $session->set('authSrc', CRM_Core_Permission
::AUTH_SRC_UNKNOWN
);
477 * @param int $contactID
478 * @param CRM_Core_Form $form
479 * @param bool $redirect
483 public static function validateChecksumContact($contactID, &$form, $redirect = TRUE) {
484 if (!self
::allow($contactID, CRM_Core_Permission
::EDIT
)) {
485 // check if this is of the format cs=XXX
486 return self
::validateOnlyChecksum($contactID, $form, $redirect);