88767deb9a8d4620341b13dc5fe30d4f56b85b06
[civicrm-core.git] / CRM / Contact / BAO / Contact / Permission.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2016
32 */
33 class CRM_Contact_BAO_Contact_Permission {
34
35 /**
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')
40 * - ACL
41 * - permissions inherited through relationships (also second degree if enabled)
42 *
43 * @param array $contact_ids
44 * Contact IDs.
45 * @param int $type the type of operation (view|edit)
46 *
47 * @see CRM_Contact_BAO_Contact_Permission::allow
48 *
49 * @return array
50 * list of contact IDs the logged in user has the given permission for
51 */
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.
56 return $result_set;
57 }
58
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')
62 ) {
63
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
67 return $contact_ids;
68 }
69 else {
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;
76 }
77 return array_keys($result_set);
78 }
79 }
80
81 // get logged in user
82 $contactID = CRM_Core_Session::getLoggedInContactID();
83 if (empty($contactID)) {
84 return array();
85 }
86
87 // make sure the cache is filled
88 self::cache($contactID, $type);
89
90 // compile query
91 $operation = ($type == CRM_Core_Permission::VIEW) ? 'View' : 'Edit';
92
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";
98 }
99
100 // RUN the query
101 $contact_id_list = implode(',', $contact_ids);
102 $query = "
103 SELECT contact_id
104 FROM civicrm_acl_contact_cache
105 {$LEFT_JOIN_DELETED}
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;
113 }
114
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;
122 }
123 }
124
125 return array_keys($result_set);
126 }
127
128 /**
129 * Check if the logged in user has permissions for the operation type.
130 *
131 * @param int $id
132 * Contact id.
133 * @param int|string $type the type of operation (view|edit)
134 *
135 * @return bool
136 * true if the user has permission, false otherwise
137 */
138 public static function allow($id, $type = CRM_Core_Permission::VIEW) {
139 // get logged in user
140 $contactID = CRM_Core_Session::getLoggedInContactID();
141
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'))
145 ) {
146 return TRUE;
147 }
148
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) {
152 return TRUE;
153 }
154
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'))
159 ) {
160 return TRUE;
161 }
162
163 // check permission based on relationship, CRM-2963
164 if (self::relationshipList(array($id))) {
165 return TRUE;
166 }
167
168 // We should probably do a cheap check whether it's in the cache first.
169 // check permission based on ACL
170 $tables = array();
171 $whereTables = array();
172
173 $permission = CRM_ACL_API::whereClause($type, $tables, $whereTables);
174 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
175
176 $query = "
177 SELECT contact_a.id
178 $from
179 WHERE contact_a.id = %1 AND $permission
180 LIMIT 1
181 ";
182
183 if (CRM_Core_DAO::singleValueQuery($query, array(1 => array($id, 'Integer')))) {
184 return TRUE;
185 }
186 return FALSE;
187 }
188
189 /**
190 * Fill the acl contact cache for this contact id if empty.
191 *
192 * @param int $userID
193 * @param int|string $type the type of operation (view|edit)
194 * @param bool $force
195 * Should we force a recompute.
196 */
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 altenative would be a SQL call every time this is called,
201 // and a complete rebuild if the result was an empty set...
202 static $_processed = array(
203 CRM_Core_Permission::VIEW => array(),
204 CRM_Core_Permission::EDIT => array());
205
206 if ($type == CRM_Core_Permission::VIEW) {
207 $operationClause = " operation IN ( 'Edit', 'View' ) ";
208 $operation = 'View';
209 }
210 else {
211 $operationClause = " operation = 'Edit' ";
212 $operation = 'Edit';
213 }
214
215 if (!$force) {
216 // skip if already calculated
217 if (!empty($_processed[$type][$userID])) {
218 return;
219 }
220
221 // run a query to see if the cache is filled
222 $sql = "
223 SELECT count(id)
224 FROM civicrm_acl_contact_cache
225 WHERE user_id = %1
226 AND $operationClause
227 ";
228 $params = array(1 => array($userID, 'Integer'));
229 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
230 if ($count > 0) {
231 $_processed[$type][$userID] = 1;
232 return;
233 }
234 }
235
236 $tables = array();
237 $whereTables = array();
238
239 $permission = CRM_ACL_API::whereClause($type, $tables, $whereTables, $userID);
240
241 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
242 CRM_Core_DAO::executeQuery("
243 INSERT INTO civicrm_acl_contact_cache ( user_id, contact_id, operation )
244 SELECT DISTINCT $userID as user_id, contact_a.id as contact_id, '{$operation}' as operation
245 $from
246 LEFT JOIN civicrm_acl_contact_cache ac ON ac.user_id = $userID AND ac.contact_id = contact_a.id AND ac.operation = '{$operation}'
247 WHERE $permission
248 AND ac.user_id IS NULL
249 ");
250 $_processed[$type][$userID] = 1;
251 }
252
253 /**
254 * @param string $contactAlias
255 *
256 * @return array
257 */
258 public static function cacheClause($contactAlias = 'contact_a') {
259 if (CRM_Core_Permission::check('view all contacts') ||
260 CRM_Core_Permission::check('edit all contacts')
261 ) {
262 if (is_array($contactAlias)) {
263 $wheres = array();
264 foreach ($contactAlias as $alias) {
265 // CRM-6181
266 $wheres[] = "$alias.is_deleted = 0";
267 }
268 return array(NULL, '(' . implode(' AND ', $wheres) . ')');
269 }
270 else {
271 // CRM-6181
272 return array(NULL, "$contactAlias.is_deleted = 0");
273 }
274 }
275
276 $contactID = (int) CRM_Core_Session::getLoggedInContactID();
277 self::cache($contactID);
278
279 if (is_array($contactAlias) && !empty($contactAlias)) {
280 //More than one contact alias
281 $clauses = array();
282 foreach ($contactAlias as $k => $alias) {
283 $clauses[] = " INNER JOIN civicrm_acl_contact_cache aclContactCache_{$k} ON {$alias}.id = aclContactCache_{$k}.contact_id AND aclContactCache_{$k}.user_id = $contactID ";
284 }
285
286 $fromClause = implode(" ", $clauses);
287 $whereClase = NULL;
288 }
289 else {
290 $fromClause = " INNER JOIN civicrm_acl_contact_cache aclContactCache ON {$contactAlias}.id = aclContactCache.contact_id ";
291 $whereClase = " aclContactCache.user_id = $contactID AND $contactAlias.is_deleted = 0";
292 }
293
294 return array($fromClause, $whereClase);
295 }
296
297 /**
298 * Generate acl subquery that can be placed in the WHERE clause of a query or the ON clause of a JOIN
299 *
300 * @return string|null
301 */
302 public static function cacheSubquery() {
303 if (!CRM_Core_Permission::check(array(array('view all contacts', 'edit all contacts')))) {
304 $contactID = (int) CRM_Core_Session::getLoggedInContactID();
305 self::cache($contactID);
306 return "IN (SELECT contact_id FROM civicrm_acl_contact_cache WHERE user_id = $contactID)";
307 }
308 return NULL;
309 }
310
311 /**
312 * Filter a list of contact_ids by the ones that the
313 * currently active user as a permissioned relationship with
314 *
315 * @param array $contact_ids
316 * List of contact IDs to be filtered
317 *
318 * @return array
319 * List of contact IDs that the user has permissions for
320 */
321 public static function relationshipList($contact_ids) {
322 $result_set = array();
323
324 // no processing empty lists (avoid SQL errors as well)
325 if (empty($contact_ids)) {
326 return array();
327 }
328
329 // get the currently logged in user
330 $contactID = CRM_Core_Session::getLoggedInContactID();
331 if (empty($contactID)) {
332 return array();
333 }
334
335 // compile a list of queries (later to UNION)
336 $queries = array();
337 $contact_id_list = implode(',', $contact_ids);
338
339 // add a select statement for each direection
340 $directions = array(array('from' => 'a', 'to' => 'b'), array('from' => 'b', 'to' => 'a'));
341
342 // NORMAL/SINGLE DEGREE RELATIONSHIPS
343 foreach ($directions as $direction) {
344 $user_id_column = "contact_id_{$direction['from']}";
345 $contact_id_column = "contact_id_{$direction['to']}";
346
347 // add clause for deleted contacts, if the user doesn't have the permission to access them
348 $LEFT_JOIN_DELETED = $AND_CAN_ACCESS_DELETED = '';
349 if (!CRM_Core_Permission::check('access deleted contacts')) {
350 $LEFT_JOIN_DELETED = "LEFT JOIN civicrm_contact ON civicrm_contact.id = {$contact_id_column} ";
351 $AND_CAN_ACCESS_DELETED = "AND civicrm_contact.is_deleted = 0";
352 }
353
354 $queries[] = "
355 SELECT civicrm_relationship.{$contact_id_column} AS contact_id
356 FROM civicrm_relationship
357 {$LEFT_JOIN_DELETED}
358 WHERE civicrm_relationship.{$user_id_column} = {$contactID}
359 AND civicrm_relationship.{$contact_id_column} IN ({$contact_id_list})
360 AND civicrm_relationship.is_active = 1
361 AND civicrm_relationship.is_permission_{$direction['from']}_{$direction['to']} = 1
362 $AND_CAN_ACCESS_DELETED";
363 }
364
365 // FIXME: secondDegRelPermissions should be a setting
366 $config = CRM_Core_Config::singleton();
367 if ($config->secondDegRelPermissions) {
368 foreach ($directions as $first_direction) {
369 foreach ($directions as $second_direction) {
370 // add clause for deleted contacts, if the user doesn't have the permission to access them
371 $LEFT_JOIN_DELETED = $AND_CAN_ACCESS_DELETED = '';
372 if (!CRM_Core_Permission::check('access deleted contacts')) {
373 $LEFT_JOIN_DELETED = "LEFT JOIN civicrm_contact first_degree_contact ON first_degree_contact.id = second_degree_relationship.contact_id_{$second_direction['from']}\n";
374 $LEFT_JOIN_DELETED .= "LEFT JOIN civicrm_contact second_degree_contact ON second_degree_contact.id = second_degree_relationship.contact_id_{$second_direction['to']} ";
375 $AND_CAN_ACCESS_DELETED = "AND first_degree_contact.is_deleted = 0\n";
376 $AND_CAN_ACCESS_DELETED .= "AND second_degree_contact.is_deleted = 0 ";
377 }
378
379 $queries[] = "
380 SELECT second_degree_relationship.contact_id_{$second_direction['to']} AS contact_id
381 FROM civicrm_relationship first_degree_relationship
382 LEFT JOIN civicrm_relationship second_degree_relationship ON first_degree_relationship.contact_id_{$first_direction['to']} = second_degree_relationship.contact_id_{$first_direction['from']}
383 {$LEFT_JOIN_DELETED}
384 WHERE first_degree_relationship.contact_id_{$first_direction['from']} = {$contactID}
385 AND second_degree_relationship.contact_id_{$second_direction['to']} IN ({$contact_id_list})
386 AND first_degree_relationship.is_active = 1
387 AND first_degree_relationship.is_permission_{$first_direction['from']}_{$first_direction['to']} = 1
388 AND second_degree_relationship.is_active = 1
389 AND second_degree_relationship.is_permission_{$second_direction['from']}_{$second_direction['to']} = 1
390 $AND_CAN_ACCESS_DELETED";
391 }
392 }
393 }
394
395 // finally UNION the queries and call
396 $query = "(" . implode(")\nUNION DISTINCT (", $queries) . ")";
397 $result = CRM_Core_DAO::executeQuery($query);
398 while ($result->fetch()) {
399 $result_set[(int) $result->contact_id] = TRUE;
400 }
401 return array_keys($result_set);
402 }
403
404
405 /**
406 * @param int $contactID
407 * @param CRM_Core_Form $form
408 * @param bool $redirect
409 *
410 * @return bool
411 */
412 public static function validateOnlyChecksum($contactID, &$form, $redirect = TRUE) {
413 // check if this is of the format cs=XXX
414 if (!CRM_Contact_BAO_Contact_Utils::validChecksum($contactID,
415 CRM_Utils_Request::retrieve('cs', 'String', $form, FALSE)
416 )
417 ) {
418 if ($redirect) {
419 // also set a message in the UF framework
420 $message = ts('You do not have permission to edit this contact record. Contact the site administrator if you need assistance.');
421 CRM_Utils_System::setUFMessage($message);
422
423 $config = CRM_Core_Config::singleton();
424 CRM_Core_Error::statusBounce($message,
425 $config->userFrameworkBaseURL
426 );
427 // does not come here, we redirect in the above statement
428 }
429 return FALSE;
430 }
431
432 // set appropriate AUTH source
433 self::initChecksumAuthSrc(TRUE, $form);
434
435 // so here the contact is posing as $contactID, lets set the logging contact ID variable
436 // CRM-8965
437 CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1',
438 array(1 => array($contactID, 'Integer'))
439 );
440
441 return TRUE;
442 }
443
444 /**
445 * @param bool $checkSumValidationResult
446 * @param null $form
447 */
448 public static function initChecksumAuthSrc($checkSumValidationResult = FALSE, $form = NULL) {
449 $session = CRM_Core_Session::singleton();
450 if ($checkSumValidationResult && $form && CRM_Utils_Request::retrieve('cs', 'String', $form, FALSE)) {
451 // if result is already validated, and url has cs, set the flag.
452 $session->set('authSrc', CRM_Core_Permission::AUTH_SRC_CHECKSUM);
453 }
454 elseif (($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM) == CRM_Core_Permission::AUTH_SRC_CHECKSUM) {
455 // if checksum wasn't present in REQUEST OR checksum result validated as FALSE,
456 // and flag was already set exactly as AUTH_SRC_CHECKSUM, unset it.
457 $session->set('authSrc', CRM_Core_Permission::AUTH_SRC_UNKNOWN);
458 }
459 }
460
461 /**
462 * @param int $contactID
463 * @param CRM_Core_Form $form
464 * @param bool $redirect
465 *
466 * @return bool
467 */
468 public static function validateChecksumContact($contactID, &$form, $redirect = TRUE) {
469 if (!self::allow($contactID, CRM_Core_Permission::EDIT)) {
470 // check if this is of the format cs=XXX
471 return self::validateOnlyChecksum($contactID, $form, $redirect);
472 }
473 return TRUE;
474 }
475
476 }