Merge pull request #8158 from eileenmcnaughton/CRM-18426
[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 if the logged in user has permissions for the operation type.
37 *
38 * @param int $id
39 * Contact id.
40 * @param int|string $type the type of operation (view|edit)
41 *
42 * @return bool
43 * true if the user has permission, false otherwise
44 */
45 public static function allow($id, $type = CRM_Core_Permission::VIEW) {
46 $tables = array();
47 $whereTables = array();
48
49 # FIXME: push this somewhere below, to not give this permission so many rights
50 $isDeleted = (bool) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $id, 'is_deleted');
51 if (CRM_Core_Permission::check('access deleted contacts') && $isDeleted) {
52 return TRUE;
53 }
54
55 // short circuit for admin rights here so we avoid unneeeded queries
56 // some duplication of code, but we skip 3-5 queries
57 if (CRM_Core_Permission::check('edit all contacts') ||
58 ($type == CRM_ACL_API::VIEW && CRM_Core_Permission::check('view all contacts'))
59 ) {
60 return TRUE;
61 }
62
63 //check permission based on relationship, CRM-2963
64 if (self::relationship($id)) {
65 return TRUE;
66 }
67
68 $permission = CRM_ACL_API::whereClause($type, $tables, $whereTables);
69
70 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
71
72 $query = "
73 SELECT count(DISTINCT contact_a.id)
74 $from
75 WHERE contact_a.id = %1 AND $permission";
76 $params = array(1 => array($id, 'Integer'));
77
78 return (CRM_Core_DAO::singleValueQuery($query, $params) > 0) ? TRUE : FALSE;
79 }
80
81 /**
82 * Fill the acl contact cache for this contact id if empty.
83 *
84 * @param int $userID
85 * @param int|string $type the type of operation (view|edit)
86 * @param bool $force
87 * Should we force a recompute.
88 */
89 public static function cache($userID, $type = CRM_Core_Permission::VIEW, $force = FALSE) {
90 static $_processed = array();
91
92 if ($type = CRM_Core_Permission::VIEW) {
93 $operationClause = " operation IN ( 'Edit', 'View' ) ";
94 $operation = 'View';
95 }
96 else {
97 $operationClause = " operation = 'Edit' ";
98 $operation = 'Edit';
99 }
100
101 if (!$force) {
102 if (!empty($_processed[$userID])) {
103 return;
104 }
105
106 // run a query to see if the cache is filled
107 $sql = "
108 SELECT count(id)
109 FROM civicrm_acl_contact_cache
110 WHERE user_id = %1
111 AND $operationClause
112 ";
113 $params = array(1 => array($userID, 'Integer'));
114 $count = CRM_Core_DAO::singleValueQuery($sql, $params);
115 if ($count > 0) {
116 $_processed[$userID] = 1;
117 return;
118 }
119 }
120
121 $tables = array();
122 $whereTables = array();
123
124 $permission = CRM_ACL_API::whereClause($type, $tables, $whereTables, $userID);
125
126 $from = CRM_Contact_BAO_Query::fromClause($whereTables);
127
128 CRM_Core_DAO::executeQuery("
129 INSERT INTO civicrm_acl_contact_cache ( user_id, contact_id, operation )
130 SELECT $userID as user_id, contact_a.id as contact_id, '$operation' as operation
131 $from
132 WHERE $permission
133 GROUP BY contact_a.id
134 ON DUPLICATE KEY UPDATE
135 user_id=VALUES(user_id),
136 contact_id=VALUES(contact_id),
137 operation=VALUES(operation)"
138 );
139
140 $_processed[$userID] = 1;
141 }
142
143 /**
144 * Check if there are any contacts in cache table.
145 *
146 * @param int|string $type the type of operation (view|edit)
147 * @param int $contactID
148 * Contact id.
149 *
150 * @return bool
151 */
152 public static function hasContactsInCache(
153 $type = CRM_Core_Permission::VIEW,
154 $contactID = NULL
155 ) {
156 if (!$contactID) {
157 $session = CRM_Core_Session::singleton();
158 $contactID = $session->get('userID');
159 }
160
161 if ($type = CRM_Core_Permission::VIEW) {
162 $operationClause = " operation IN ( 'Edit', 'View' ) ";
163 $operation = 'View';
164 }
165 else {
166 $operationClause = " operation = 'Edit' ";
167 $operation = 'Edit';
168 }
169
170 // fill cache
171 self::cache($contactID);
172
173 $sql = "
174 SELECT id
175 FROM civicrm_acl_contact_cache
176 WHERE user_id = %1
177 AND $operationClause LIMIT 1";
178
179 $params = array(1 => array($contactID, 'Integer'));
180 return (bool) CRM_Core_DAO::singleValueQuery($sql, $params);
181 }
182
183 /**
184 * @param string $contactAlias
185 *
186 * @return array
187 */
188 public static function cacheClause($contactAlias = 'contact_a') {
189 if (CRM_Core_Permission::check('view all contacts') ||
190 CRM_Core_Permission::check('edit all contacts')
191 ) {
192 if (is_array($contactAlias)) {
193 $wheres = array();
194 foreach ($contactAlias as $alias) {
195 // CRM-6181
196 $wheres[] = "$alias.is_deleted = 0";
197 }
198 return array(NULL, '(' . implode(' AND ', $wheres) . ')');
199 }
200 else {
201 // CRM-6181
202 return array(NULL, "$contactAlias.is_deleted = 0");
203 }
204 }
205
206 $contactID = (int) CRM_Core_Session::getLoggedInContactID();
207 self::cache($contactID);
208
209 if (is_array($contactAlias) && !empty($contactAlias)) {
210 //More than one contact alias
211 $clauses = array();
212 foreach ($contactAlias as $k => $alias) {
213 $clauses[] = " INNER JOIN civicrm_acl_contact_cache aclContactCache_{$k} ON {$alias}.id = aclContactCache_{$k}.contact_id AND aclContactCache_{$k}.user_id = $contactID ";
214 }
215
216 $fromClause = implode(" ", $clauses);
217 $whereClase = NULL;
218 }
219 else {
220 $fromClause = " INNER JOIN civicrm_acl_contact_cache aclContactCache ON {$contactAlias}.id = aclContactCache.contact_id ";
221 $whereClase = " aclContactCache.user_id = $contactID AND $contactAlias.is_deleted = 0";
222 }
223
224 return array($fromClause, $whereClase);
225 }
226
227 /**
228 * Generate acl subquery that can be placed in the WHERE clause of a query or the ON clause of a JOIN
229 *
230 * @return string|null
231 */
232 public static function cacheSubquery() {
233 if (!CRM_Core_Permission::check(array(array('view all contacts', 'edit all contacts')))) {
234 $contactID = (int) CRM_Core_Session::getLoggedInContactID();
235 self::cache($contactID);
236 return "IN (SELECT contact_id FROM civicrm_acl_contact_cache WHERE user_id = $contactID)";
237 }
238 return NULL;
239 }
240
241 /**
242 * Get the permission base on its relationship.
243 *
244 * @param int $selectedContactID
245 * Contact id of selected contact.
246 * @param int $contactID
247 * Contact id of the current contact.
248 *
249 * @return bool
250 * true if logged in user has permission to view
251 * selected contact record else false
252 */
253 public static function relationship($selectedContactID, $contactID = NULL) {
254 $session = CRM_Core_Session::singleton();
255 $config = CRM_Core_Config::singleton();
256 if (!$contactID) {
257 $contactID = $session->get('userID');
258 if (!$contactID) {
259 return FALSE;
260 }
261 }
262 if ($contactID == $selectedContactID &&
263 (CRM_Core_Permission::check('edit my contact'))
264 ) {
265 return TRUE;
266 }
267 else {
268 if ($config->secondDegRelPermissions) {
269 $query = "
270 SELECT firstdeg.id
271 FROM civicrm_relationship firstdeg
272 LEFT JOIN civicrm_relationship seconddegaa
273 on firstdeg.contact_id_a = seconddegaa.contact_id_b
274 and seconddegaa.is_permission_b_a = 1
275 and firstdeg.is_permission_b_a = 1
276 and seconddegaa.is_active = 1
277 LEFT JOIN civicrm_relationship seconddegab
278 on firstdeg.contact_id_a = seconddegab.contact_id_a
279 and seconddegab.is_permission_a_b = 1
280 and firstdeg.is_permission_b_a = 1
281 and seconddegab.is_active = 1
282 LEFT JOIN civicrm_relationship seconddegba
283 on firstdeg.contact_id_b = seconddegba.contact_id_b
284 and seconddegba.is_permission_b_a = 1
285 and firstdeg.is_permission_a_b = 1
286 and seconddegba.is_active = 1
287 LEFT JOIN civicrm_relationship seconddegbb
288 on firstdeg.contact_id_b = seconddegbb.contact_id_a
289 and seconddegbb.is_permission_a_b = 1
290 and firstdeg.is_permission_a_b = 1
291 and seconddegbb.is_active = 1
292 WHERE
293 (
294 ( firstdeg.contact_id_a = %1 AND firstdeg.contact_id_b = %2 AND firstdeg.is_permission_a_b = 1 )
295 OR ( firstdeg.contact_id_a = %2 AND firstdeg.contact_id_b = %1 AND firstdeg.is_permission_b_a = 1 )
296 OR (
297 firstdeg.contact_id_a = %1 AND seconddegba.contact_id_a = %2
298 AND (seconddegba.contact_id_a NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1))
299 )
300 OR (
301 firstdeg.contact_id_a = %1 AND seconddegbb.contact_id_b = %2
302 AND (seconddegbb.contact_id_b NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1))
303 )
304 OR (
305 firstdeg.contact_id_b = %1 AND seconddegab.contact_id_b = %2
306 AND (seconddegab.contact_id_b NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1))
307 )
308 OR (
309 firstdeg.contact_id_b = %1 AND seconddegaa.contact_id_a = %2 AND (seconddegaa.contact_id_a NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1))
310 )
311 )
312 AND (firstdeg.contact_id_a NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1))
313 AND (firstdeg.contact_id_b NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1))
314 AND ( firstdeg.is_active = 1)
315 ";
316 }
317 else {
318 $query = "
319 SELECT id
320 FROM civicrm_relationship
321 WHERE (( contact_id_a = %1 AND contact_id_b = %2 AND is_permission_a_b = 1 ) OR
322 ( contact_id_a = %2 AND contact_id_b = %1 AND is_permission_b_a = 1 )) AND
323 (contact_id_a NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)) AND
324 (contact_id_b NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1))
325 AND ( civicrm_relationship.is_active = 1 )
326 ";
327 }
328 $params = array(
329 1 => array($contactID, 'Integer'),
330 2 => array($selectedContactID, 'Integer'),
331 );
332 return CRM_Core_DAO::singleValueQuery($query, $params);
333 }
334 }
335
336
337 /**
338 * @param int $contactID
339 * @param CRM_Core_Form $form
340 * @param bool $redirect
341 *
342 * @return bool
343 */
344 public static function validateOnlyChecksum($contactID, &$form, $redirect = TRUE) {
345 // check if this is of the format cs=XXX
346 if (!CRM_Contact_BAO_Contact_Utils::validChecksum($contactID,
347 CRM_Utils_Request::retrieve('cs', 'String', $form, FALSE)
348 )
349 ) {
350 if ($redirect) {
351 // also set a message in the UF framework
352 $message = ts('You do not have permission to edit this contact record. Contact the site administrator if you need assistance.');
353 CRM_Utils_System::setUFMessage($message);
354
355 $config = CRM_Core_Config::singleton();
356 CRM_Core_Error::statusBounce($message,
357 $config->userFrameworkBaseURL
358 );
359 // does not come here, we redirect in the above statement
360 }
361 return FALSE;
362 }
363
364 // set appropriate AUTH source
365 self::initChecksumAuthSrc(TRUE, $form);
366
367 // so here the contact is posing as $contactID, lets set the logging contact ID variable
368 // CRM-8965
369 CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1',
370 array(1 => array($contactID, 'Integer'))
371 );
372
373 return TRUE;
374 }
375
376 /**
377 * @param bool $checkSumValidationResult
378 * @param null $form
379 */
380 public static function initChecksumAuthSrc($checkSumValidationResult = FALSE, $form = NULL) {
381 $session = CRM_Core_Session::singleton();
382 if ($checkSumValidationResult && $form && CRM_Utils_Request::retrieve('cs', 'String', $form, FALSE)) {
383 // if result is already validated, and url has cs, set the flag.
384 $session->set('authSrc', CRM_Core_Permission::AUTH_SRC_CHECKSUM);
385 }
386 elseif (($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM) == CRM_Core_Permission::AUTH_SRC_CHECKSUM) {
387 // if checksum wasn't present in REQUEST OR checksum result validated as FALSE,
388 // and flag was already set exactly as AUTH_SRC_CHECKSUM, unset it.
389 $session->set('authSrc', CRM_Core_Permission::AUTH_SRC_UNKNOWN);
390 }
391 }
392
393 /**
394 * @param int $contactID
395 * @param CRM_Core_Form $form
396 * @param bool $redirect
397 *
398 * @return bool
399 */
400 public static function validateChecksumContact($contactID, &$form, $redirect = TRUE) {
401 if (!self::allow($contactID, CRM_Core_Permission::EDIT)) {
402 // check if this is of the format cs=XXX
403 return self::validateOnlyChecksum($contactID, $form, $redirect);
404 }
405 return TRUE;
406 }
407
408 }