Merge pull request #4866 from totten/master-phpcs
[civicrm-core.git] / CRM / Contact / BAO / GroupContactCache.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_GroupContactCache extends CRM_Contact_DAO_GroupContactCache {
36
37 static $_alreadyLoaded = array();
38
39 /**
40 * Check to see if we have cache entries for this group
41 * if not, regenerate, else return
42 *
43 * @param $groupIDs
44 * Of group that we are checking against.
45 *
46 * @return boolean true if we did not regenerate, false if we did
47 */
48 public static function check($groupIDs) {
49 if (empty($groupIDs)) {
50 return TRUE;
51 }
52
53 return self::loadAll($groupIDs);
54 }
55
56 /**
57 * Common function that formulates the query to see which groups needs to be refreshed
58 * based on their cache date and the smartGroupCacheTimeOut
59 *
60 * @param string $groupIDClause
61 * The clause which limits which groups we need to evaluate.
62 * @param bool $includeHiddenGroups
63 * Hidden groups are excluded by default.
64 *
65 * @return string the sql query which lists the groups that need to be refreshed
66 * @static
67 */
68 public static function groupRefreshedClause($groupIDClause = null, $includeHiddenGroups = FALSE) {
69 $smartGroupCacheTimeout = self::smartGroupCacheTimeout();
70 $now = CRM_Utils_Date::getUTCTime();
71
72 $query = "
73 SELECT g.id
74 FROM civicrm_group g
75 WHERE ( g.saved_search_id IS NOT NULL OR g.children IS NOT NULL )
76 AND g.is_active = 1
77 AND ( g.cache_date IS NULL OR
78 ( TIMESTAMPDIFF(MINUTE, g.cache_date, $now) >= $smartGroupCacheTimeout ) OR
79 ( $now >= g.refresh_date )
80 )
81 ";
82
83 if (!$includeHiddenGroups) {
84 $query .= "AND (g.is_hidden = 0 OR g.is_hidden IS NULL)";
85 }
86
87 if (!empty($groupIDClause)) {
88 $query .= " AND ( $groupIDClause ) ";
89 }
90
91 return $query;
92 }
93
94 /**
95 * Checks to see if a group has been refreshed recently. This is primarily used
96 * in a locking scenario when some other process might have refreshed things underneath
97 * this process
98 *
99 * @param int $groupID
100 * The group ID.
101 * @param bool $includeHiddenGroups
102 * Hidden groups are excluded by default.
103 *
104 * @return string the sql query which lists the groups that need to be refreshed
105 * @static
106 */
107 public static function shouldGroupBeRefreshed($groupID, $includeHiddenGroups = FALSE) {
108 $query = self::groupRefreshedClause("g.id = %1", $includeHiddenGroups);
109 $params = array(1 => array($groupID, 'Integer'));
110
111 // if the query returns the group ID, it means the group is a valid candidate for refreshing
112 return CRM_Core_DAO::singleValueQuery($query, $params);
113 }
114
115 /**
116 * Check to see if we have cache entries for this group
117 * if not, regenerate, else return
118 *
119 * @param int/array $groupID groupID of group that we are checking against
120 * if empty, all groups are checked
121 * @param int $limit
122 * Limits the number of groups we evaluate.
123 *
124 * @return boolean true if we did not regenerate, false if we did
125 */
126 public static function loadAll($groupIDs = null, $limit = 0) {
127 // ensure that all the smart groups are loaded
128 // this function is expensive and should be sparingly used if groupIDs is empty
129 if (empty($groupIDs)) {
130 $groupIDClause = null;
131 $groupIDs = array();
132 }
133 else {
134 if (!is_array($groupIDs)) {
135 $groupIDs = array($groupIDs);
136 }
137
138 // note escapeString is a must here and we can't send the imploded value as second arguement to
139 // the executeQuery(), since that would put single quote around the string and such a string
140 // of comma separated integers would not work.
141 $groupIDString = CRM_Core_DAO::escapeString(implode(', ', $groupIDs));
142
143 $groupIDClause = "g.id IN ({$groupIDString})";
144 }
145
146 $query = self::groupRefreshedClause($groupIDClause);
147
148 $limitClause = $orderClause = NULL;
149 if ($limit > 0) {
150 $limitClause = " LIMIT 0, $limit";
151 $orderClause = " ORDER BY g.cache_date, g.refresh_date";
152 }
153 // We ignore hidden groups and disabled groups
154 $query .= "
155 $orderClause
156 $limitClause
157 ";
158
159 $dao = CRM_Core_DAO::executeQuery($query);
160 $processGroupIDs = array();
161 $refreshGroupIDs = $groupIDs;
162 while ($dao->fetch()) {
163 $processGroupIDs[] = $dao->id;
164
165 // remove this id from refreshGroupIDs
166 foreach ($refreshGroupIDs as $idx => $gid) {
167 if ($gid == $dao->id) {
168 unset($refreshGroupIDs[$idx]);
169 break;
170 }
171 }
172 }
173
174 if (!empty($refreshGroupIDs)) {
175 $refreshGroupIDString = CRM_Core_DAO::escapeString(implode(', ', $refreshGroupIDs));
176 $time = CRM_Utils_Date::getUTCTime(self::smartGroupCacheTimeout() * 60);
177 $query = "
178 UPDATE civicrm_group g
179 SET g.refresh_date = $time
180 WHERE g.id IN ( {$refreshGroupIDString} )
181 AND g.refresh_date IS NULL
182 ";
183 CRM_Core_DAO::executeQuery($query);
184 }
185
186 if (empty($processGroupIDs)) {
187 return TRUE;
188 }
189 else {
190 self::add($processGroupIDs);
191 return FALSE;
192 }
193 }
194
195 /**
196 * FIXME: This function should not be needed, because the cache table should not be getting truncated
197 */
198 public static function fillIfEmpty() {
199 if (!CRM_Core_DAO::singleValueQuery("SELECT COUNT(id) FROM civicrm_group_contact_cache")) {
200 self::loadAll();
201 }
202 }
203
204 /**
205 * @param int $groupID
206 */
207 public static function add($groupID) {
208 // first delete the current cache
209 self::remove($groupID);
210 if (!is_array($groupID)) {
211 $groupID = array($groupID);
212 }
213
214 $returnProperties = array('contact_id');
215 foreach ($groupID as $gid) {
216 $params = array(array('group', 'IN', array($gid => 1), 0, 0));
217 // the below call updates the cache table as a byproduct of the query
218 CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, FALSE);
219 }
220 }
221
222 /**
223 * @param int $groupID
224 * @param $values
225 */
226 public static function store(&$groupID, &$values) {
227 $processed = FALSE;
228
229 // sort the values so we put group IDs in front and hence optimize
230 // mysql storage (or so we think) CRM-9493
231 sort($values);
232
233 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
234 while (!empty($values)) {
235 $processed = TRUE;
236 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
237 $str = implode(',', $input);
238 $sql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) VALUES $str;";
239 CRM_Core_DAO::executeQuery($sql);
240 }
241 self::updateCacheTime($groupID, $processed);
242 }
243
244 /**
245 * Change the cache_date
246 *
247 * @param $groupID
248 * Array(int).
249 * @param $processed
250 * Bool, whether the cache data was recently modified.
251 */
252 public static function updateCacheTime($groupID, $processed) {
253 // only update cache entry if we had any values
254 if ($processed) {
255 // also update the group with cache date information
256 //make sure to give original timezone settings again.
257 $now = CRM_Utils_Date::getUTCTime();
258 $refresh = 'null';
259 }
260 else {
261 $now = 'null';
262 $refresh = 'null';
263 }
264
265 $groupIDs = implode(',', $groupID);
266 $sql = "
267 UPDATE civicrm_group
268 SET cache_date = $now, refresh_date = $refresh
269 WHERE id IN ( $groupIDs )
270 ";
271 CRM_Core_DAO::executeQuery($sql);
272 }
273
274 /**
275 * Removes all the cache entries pertaining to a specific group
276 * If no groupID is passed in, removes cache entries for all groups
277 * Has an optimization to bypass repeated invocations of this function.
278 * Note that this function is an advisory, i.e. the removal respects the
279 * cache date, i.e. the removal is not done if the group was recently
280 * loaded into the cache.
281 *
282 * @param $groupID
283 * Int the groupID to delete cache entries, NULL for all groups.
284 * @param $onceOnly
285 * Boolean run the function exactly once for all groups.
286 *
287 * @return void
288 * @static
289 */
290 public static function remove($groupID = NULL, $onceOnly = TRUE) {
291 static $invoked = FALSE;
292
293 // typically this needs to happy only once per instance
294 // this is especially true in import, where we dont need
295 // to do this all the time
296 // this optimization is done only when no groupID is passed
297 // i.e. cache is reset for all groups
298 if (
299 $onceOnly &&
300 $invoked &&
301 $groupID == NULL
302 ) {
303 return;
304 }
305
306 if ($groupID == NULL) {
307 $invoked = TRUE;
308 }
309 elseif (is_array($groupID)) {
310 foreach ($groupID as $gid) {
311 unset(self::$_alreadyLoaded[$gid]);
312 }
313 }
314 elseif ($groupID && array_key_exists($groupID, self::$_alreadyLoaded)) {
315 unset(self::$_alreadyLoaded[$groupID]);
316 }
317
318 $refresh = null;
319 $params = array();
320 $smartGroupCacheTimeout = self::smartGroupCacheTimeout();
321
322 $now = CRM_Utils_Date::getUTCTime();
323 $refreshTime = CRM_Utils_Date::getUTCTime($smartGroupCacheTimeout * 60);
324
325 if (!isset($groupID)) {
326 if ($smartGroupCacheTimeout == 0) {
327 $query = "
328 TRUNCATE civicrm_group_contact_cache
329 ";
330 $update = "
331 UPDATE civicrm_group g
332 SET cache_date = null,
333 refresh_date = null
334 ";
335 }
336 else {
337 $query = "
338 DELETE gc
339 FROM civicrm_group_contact_cache gc
340 INNER JOIN civicrm_group g ON g.id = gc.group_id
341 WHERE TIMESTAMPDIFF(MINUTE, g.cache_date, $now) >= $smartGroupCacheTimeout
342 ";
343 $update = "
344 UPDATE civicrm_group g
345 SET cache_date = null,
346 refresh_date = null
347 WHERE TIMESTAMPDIFF(MINUTE, cache_date, $now) >= $smartGroupCacheTimeout
348 ";
349 $refresh = "
350 UPDATE civicrm_group g
351 SET refresh_date = $refreshTime
352 WHERE TIMESTAMPDIFF(MINUTE, cache_date, $now) < $smartGroupCacheTimeout
353 AND refresh_date IS NULL
354 ";
355 }
356 }
357 elseif (is_array($groupID)) {
358 $groupIDs = implode(', ', $groupID);
359 $query = "
360 DELETE g
361 FROM civicrm_group_contact_cache g
362 WHERE g.group_id IN ( $groupIDs )
363 ";
364 $update = "
365 UPDATE civicrm_group g
366 SET cache_date = null,
367 refresh_date = null
368 WHERE id IN ( $groupIDs )
369 ";
370 }
371 else {
372 $query = "
373 DELETE g
374 FROM civicrm_group_contact_cache g
375 WHERE g.group_id = %1
376 ";
377 $update = "
378 UPDATE civicrm_group g
379 SET cache_date = null,
380 refresh_date = null
381 WHERE id = %1
382 ";
383 $params = array(1 => array($groupID, 'Integer'));
384 }
385
386 CRM_Core_DAO::executeQuery($query, $params);
387
388 if ($refresh) {
389 CRM_Core_DAO::executeQuery($refresh, $params);
390 }
391
392 // also update the cache_date for these groups
393 CRM_Core_DAO::executeQuery($update, $params);
394 }
395
396 /**
397 * Removes one or more contacts from the smart group cache
398 * @param int|array $cid
399 * @param int $groupId
400 * @return bool - true if successful
401 */
402 public static function removeContact($cid, $groupId = NULL) {
403 $cids = array();
404 // sanitize input
405 foreach ((array) $cid as $c) {
406 $cids[] = CRM_Utils_Type::escape($c, 'Integer');
407 }
408 if ($cids) {
409 $condition = count($cids) == 1 ? "= {$cids[0]}" : "IN (" . implode(',', $cids) . ")";
410 if ($groupId) {
411 $condition .= " AND group_id = " . CRM_Utils_Type::escape($groupId, 'Integer');
412 }
413 $sql = "DELETE FROM civicrm_group_contact_cache WHERE contact_id $condition";
414 CRM_Core_DAO::executeQuery($sql);
415 return TRUE;
416 }
417 return FALSE;
418 }
419
420 /**
421 * Load the smart group cache for a saved search
422 *
423 * @param object $group
424 * The smart group that needs to be loaded.
425 * @param bool $force
426 * Should we force a search through.
427 *
428 */
429 public static function load(&$group, $force = FALSE) {
430 $groupID = $group->id;
431 $savedSearchID = $group->saved_search_id;
432 if (array_key_exists($groupID, self::$_alreadyLoaded) && !$force) {
433 return;
434 }
435
436 // grab a lock so other processes dont compete and do the same query
437 $lockName = "civicrm.group.{$groupID}";
438 $lock = new CRM_Core_Lock($lockName);
439 if (!$lock->isAcquired()) {
440 // this can cause inconsistent results since we dont know if the other process
441 // will fill up the cache before our calling routine needs it.
442 // however this routine does not return the status either, so basically
443 // its a "lets return and hope for the best"
444 return;
445 }
446
447 self::$_alreadyLoaded[$groupID] = 1;
448
449 // we now have the lock, but some other proces could have actually done the work
450 // before we got here, so before we do any work, lets ensure that work needs to be
451 // done
452 // we allow hidden groups here since we dont know if the caller wants to evaluate an
453 // hidden group
454 if (!$force && !self::shouldGroupBeRefreshed($groupID, TRUE)) {
455 $lock->release();
456 return;
457 }
458
459 $sql = NULL;
460 $idName = 'id';
461 $customClass = NULL;
462 if ($savedSearchID) {
463 $ssParams = CRM_Contact_BAO_SavedSearch::getSearchParams($savedSearchID);
464
465 // rectify params to what proximity search expects if there is a value for prox_distance
466 // CRM-7021
467 if (!empty($ssParams)) {
468 CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams);
469 }
470
471
472 $returnProperties = array();
473 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) {
474 $fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
475 $returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv);
476 }
477
478 if (isset($ssParams['customSearchID'])) {
479 // if custom search
480
481 // we split it up and store custom class
482 // so temp tables are not destroyed if they are used
483 // hence customClass is defined above at top of function
484 $customClass =
485 CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID);
486 $searchSQL = $customClass->contactIDs();
487 $searchSQL = str_replace('ORDER BY contact_a.id ASC', '', $searchSQL);
488 $idName = 'contact_id';
489 }
490 else {
491 $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
492
493 $query =
494 new CRM_Contact_BAO_Query(
495 $ssParams, $returnProperties, NULL,
496 FALSE, FALSE, 1,
497 TRUE, TRUE,
498 FALSE,
499 CRM_Utils_Array::value('display_relationship_type', $formValues),
500 CRM_Utils_Array::value('operator', $formValues, 'AND')
501 );
502 $query->_useDistinct = FALSE;
503 $query->_useGroupBy = FALSE;
504 $searchSQL =
505 $query->searchQuery(
506 0, 0, NULL,
507 FALSE, FALSE,
508 FALSE, TRUE,
509 TRUE,
510 NULL, NULL, NULL,
511 TRUE
512 );
513 }
514 $groupID = CRM_Utils_Type::escape($groupID, 'Integer');
515 $sql = $searchSQL . " AND contact_a.id NOT IN (
516 SELECT contact_id FROM civicrm_group_contact
517 WHERE civicrm_group_contact.status = 'Removed'
518 AND civicrm_group_contact.group_id = $groupID ) ";
519 }
520
521 if ($sql) {
522 $sql = preg_replace("/^\s*SELECT/", "SELECT $groupID as group_id, ", $sql);
523 }
524
525 // lets also store the records that are explicitly added to the group
526 // this allows us to skip the group contact LEFT JOIN
527 $sqlB = "
528 SELECT $groupID as group_id, contact_id as $idName
529 FROM civicrm_group_contact
530 WHERE civicrm_group_contact.status = 'Added'
531 AND civicrm_group_contact.group_id = $groupID ";
532
533 $groupIDs = array($groupID);
534 self::remove($groupIDs);
535 $processed = FALSE;
536 $tempTable = 'civicrm_temp_group_contact_cache' . rand(0,2000);
537 foreach (array($sql, $sqlB) as $selectSql) {
538 if (!$selectSql) {
539 continue;
540 }
541 $insertSql = "CREATE TEMPORARY TABLE $tempTable ($selectSql);";
542 $processed = TRUE;
543 $result = CRM_Core_DAO::executeQuery($insertSql);
544 CRM_Core_DAO::executeQuery(
545 "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)
546 SELECT DISTINCT $idName, group_id FROM $tempTable
547 ");
548 CRM_Core_DAO::executeQuery(" DROP TABLE $tempTable");
549 }
550
551 self::updateCacheTime($groupIDs, $processed);
552
553 if ($group->children) {
554
555 //Store a list of contacts who are removed from the parent group
556 $sql = "
557 SELECT contact_id
558 FROM civicrm_group_contact
559 WHERE civicrm_group_contact.status = 'Removed'
560 AND civicrm_group_contact.group_id = $groupID ";
561 $dao = CRM_Core_DAO::executeQuery($sql);
562 $removed_contacts = array();
563 while ($dao->fetch()) {
564 $removed_contacts[] = $dao->contact_id;
565 }
566
567 $childrenIDs = explode(',', $group->children);
568 foreach ($childrenIDs as $childID) {
569 $contactIDs = CRM_Contact_BAO_Group::getMember($childID, FALSE);
570 //Unset each contact that is removed from the parent group
571 foreach ($removed_contacts as $removed_contact) {
572 unset($contactIDs[$removed_contact]);
573 }
574 $values = array();
575 foreach ($contactIDs as $contactID => $dontCare) {
576 $values[] = "({$groupID},{$contactID})";
577 }
578
579 self::store($groupIDs, $values);
580 }
581 }
582
583 $lock->release();
584 }
585
586 /**
587 * @return int
588 */
589 public static function smartGroupCacheTimeout() {
590 $config = CRM_Core_Config::singleton();
591
592 if (
593 isset($config->smartGroupCacheTimeout) &&
594 is_numeric($config->smartGroupCacheTimeout) &&
595 $config->smartGroupCacheTimeout > 0) {
596 return $config->smartGroupCacheTimeout;
597 }
598
599 // lets have a min cache time of 5 mins if not set
600 return 5;
601 }
602
603 /**
604 * Get all the smart groups that this contact belongs to
605 * Note that this could potentially be a super slow function since
606 * it ensure that all contact groups are loaded in the cache
607 *
608 * @param int $contactID
609 * @param bool $showHidden
610 * Hidden groups are shown only if this flag is set.
611 *
612 * @return array an array of groups that this contact belongs to
613 */
614 public static function contactGroup($contactID, $showHidden = FALSE) {
615 if (empty($contactID)) {
616 return;
617 }
618
619 if (is_array($contactID)) {
620 $contactIDs = $contactID;
621 }
622 else {
623 $contactIDs = array($contactID);
624 }
625
626 self::loadAll();
627
628 $hiddenClause = '';
629 if (!$showHidden) {
630 $hiddenClause = ' AND (g.is_hidden = 0 OR g.is_hidden IS NULL) ';
631 }
632
633 $contactIDString = CRM_Core_DAO::escapeString(implode(', ', $contactIDs));
634 $sql = "
635 SELECT gc.group_id, gc.contact_id, g.title, g.children, g.description
636 FROM civicrm_group_contact_cache gc
637 INNER JOIN civicrm_group g ON g.id = gc.group_id
638 WHERE gc.contact_id IN ($contactIDString)
639 $hiddenClause
640 ORDER BY gc.contact_id, g.children
641 ";
642
643 $dao = CRM_Core_DAO::executeQuery($sql);
644 $contactGroup = array();
645 $prevContactID = null;
646 while ($dao->fetch()) {
647 if (
648 $prevContactID &&
649 $prevContactID != $dao->contact_id
650 ) {
651 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
652 }
653 $prevContactID = $dao->contact_id;
654 if (!array_key_exists($dao->contact_id, $contactGroup)) {
655 $contactGroup[$dao->contact_id] =
656 array('group' => array(), 'groupTitle' => array());
657 }
658
659 $contactGroup[$dao->contact_id]['group'][] =
660 array(
661 'id' => $dao->group_id,
662 'title' => $dao->title,
663 'description' => $dao->description,
664 'children' => $dao->children
665 );
666 $contactGroup[$dao->contact_id]['groupTitle'][] = $dao->title;
667 }
668
669 if ($prevContactID) {
670 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
671 }
672
673 if ((!empty($contactGroup[$contactID]) && is_numeric($contactID))) {
674 return $contactGroup[$contactID];
675 }
676 else {
677 return $contactGroup;
678 }
679 }
680
681 }