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