Merge pull request #11199 from twomice/CRM-21348_joomla_edit_link
[civicrm-core.git] / CRM / Contact / BAO / GroupContactCache.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33class CRM_Contact_BAO_GroupContactCache extends CRM_Contact_DAO_GroupContactCache {
34
35 static $_alreadyLoaded = array();
36
a8eb1fe6
TO
37 /**
38 * Get a list of caching modes.
39 *
40 * @return array
41 */
42 public static function getModes() {
43 return array(
44 // Flush expired caches in response to user actions.
45 'opportunistic' => ts('Opportunistic Flush'),
46
47 // Flush expired caches via background cron jobs.
48 'deterministic' => ts('Cron Flush'),
49 );
50 }
51
6a488035 52 /**
67d19299 53 * Check to see if we have cache entries for this group.
54 *
55 * If not, regenerate, else return.
6a488035 56 *
adf28ffd 57 * @param array $groupIDs
77c5b619 58 * Of group that we are checking against.
6a488035 59 *
5396af74 60 * @return bool
a6c01b45 61 * TRUE if we did not regenerate, FALSE if we did
6a488035 62 */
00be9182 63 public static function check($groupIDs) {
6a488035
TO
64 if (empty($groupIDs)) {
65 return TRUE;
66 }
67
68 return self::loadAll($groupIDs);
69 }
70
abdb2607 71 /**
adf28ffd 72 * Formulate the query to see which groups needs to be refreshed.
73 *
74 * The calculation is based on their cache date and the smartGroupCacheTimeOut
abdb2607 75 *
77c5b619
TO
76 * @param string $groupIDClause
77 * The clause which limits which groups we need to evaluate.
78 * @param bool $includeHiddenGroups
79 * Hidden groups are excluded by default.
abdb2607 80 *
a6c01b45
CW
81 * @return string
82 * the sql query which lists the groups that need to be refreshed
abdb2607 83 */
e60f24eb 84 public static function groupRefreshedClause($groupIDClause = NULL, $includeHiddenGroups = FALSE) {
4052239b 85 $smartGroupCacheTimeoutDateTime = self::getCacheInvalidDateTime();
abdb2607
DL
86
87 $query = "
88SELECT g.id
89FROM civicrm_group g
90WHERE ( g.saved_search_id IS NOT NULL OR g.children IS NOT NULL )
91AND g.is_active = 1
4052239b 92AND (
93 g.cache_date IS NULL
94 OR cache_date <= $smartGroupCacheTimeoutDateTime
95 OR NOW() >= g.refresh_date
96)";
abdb2607
DL
97
98 if (!$includeHiddenGroups) {
99 $query .= "AND (g.is_hidden = 0 OR g.is_hidden IS NULL)";
100 }
101
102 if (!empty($groupIDClause)) {
103 $query .= " AND ( $groupIDClause ) ";
104 }
105
106 return $query;
107 }
108
109 /**
adf28ffd 110 * Check to see if a group has been refreshed recently.
111 *
112 * This is primarily used in a locking scenario when some other process might have refreshed things underneath
abdb2607
DL
113 * this process
114 *
77c5b619
TO
115 * @param int $groupID
116 * The group ID.
117 * @param bool $includeHiddenGroups
118 * Hidden groups are excluded by default.
abdb2607 119 *
a6c01b45
CW
120 * @return string
121 * the sql query which lists the groups that need to be refreshed
abdb2607 122 */
00be9182 123 public static function shouldGroupBeRefreshed($groupID, $includeHiddenGroups = FALSE) {
abdb2607
DL
124 $query = self::groupRefreshedClause("g.id = %1", $includeHiddenGroups);
125 $params = array(1 => array($groupID, 'Integer'));
126
4f53db5a 127 // if the query returns the group ID, it means the group is a valid candidate for refreshing
abdb2607
DL
128 return CRM_Core_DAO::singleValueQuery($query, $params);
129 }
130
6a488035 131 /**
adf28ffd 132 * Check to see if we have cache entries for this group.
133 *
6a488035
TO
134 * if not, regenerate, else return
135 *
adf28ffd 136 * @param int|array $groupIDs groupIDs of group that we are checking against
6a488035 137 * if empty, all groups are checked
77c5b619
TO
138 * @param int $limit
139 * Limits the number of groups we evaluate.
6a488035 140 *
5396af74 141 * @return bool
a6c01b45 142 * TRUE if we did not regenerate, FALSE if we did
6a488035 143 */
e60f24eb 144 public static function loadAll($groupIDs = NULL, $limit = 0) {
6a488035
TO
145 // ensure that all the smart groups are loaded
146 // this function is expensive and should be sparingly used if groupIDs is empty
6a488035 147 if (empty($groupIDs)) {
e60f24eb 148 $groupIDClause = NULL;
481a74f4 149 $groupIDs = array();
6a488035
TO
150 }
151 else {
152 if (!is_array($groupIDs)) {
153 $groupIDs = array($groupIDs);
154 }
155
b44e3f84 156 // note escapeString is a must here and we can't send the imploded value as second argument to
6a488035
TO
157 // the executeQuery(), since that would put single quote around the string and such a string
158 // of comma separated integers would not work.
0e4e5a49 159 $groupIDString = CRM_Core_DAO::escapeString(implode(', ', $groupIDs));
6a488035 160
abdb2607 161 $groupIDClause = "g.id IN ({$groupIDString})";
6a488035
TO
162 }
163
abdb2607 164 $query = self::groupRefreshedClause($groupIDClause);
6a488035
TO
165
166 $limitClause = $orderClause = NULL;
167 if ($limit > 0) {
168 $limitClause = " LIMIT 0, $limit";
169 $orderClause = " ORDER BY g.cache_date, g.refresh_date";
170 }
e2422b8f 171 // We ignore hidden groups and disabled groups
abdb2607 172 $query .= "
6a488035 173 $orderClause
f9e16e9a 174 $limitClause
6a488035
TO
175";
176
177 $dao = CRM_Core_DAO::executeQuery($query);
178 $processGroupIDs = array();
179 $refreshGroupIDs = $groupIDs;
180 while ($dao->fetch()) {
181 $processGroupIDs[] = $dao->id;
182
183 // remove this id from refreshGroupIDs
184 foreach ($refreshGroupIDs as $idx => $gid) {
185 if ($gid == $dao->id) {
186 unset($refreshGroupIDs[$idx]);
187 break;
188 }
189 }
190 }
191
192 if (!empty($refreshGroupIDs)) {
82a837e9 193 $refreshGroupIDString = CRM_Core_DAO::escapeString(implode(', ', $refreshGroupIDs));
a986056d 194 $time = self::getRefreshDateTime();
6a488035
TO
195 $query = "
196UPDATE civicrm_group g
197SET g.refresh_date = $time
198WHERE g.id IN ( {$refreshGroupIDString} )
199AND g.refresh_date IS NULL
200";
82a837e9 201 CRM_Core_DAO::executeQuery($query);
6a488035
TO
202 }
203
204 if (empty($processGroupIDs)) {
205 return TRUE;
206 }
207 else {
208 self::add($processGroupIDs);
209 return FALSE;
210 }
211 }
212
86538308 213 /**
6b05374e 214 * Build the smart group cache for given groups.
adf28ffd 215 *
6b05374e 216 * @param array $groupIDs
86538308 217 */
6b05374e 218 public static function add($groupIDs) {
219 $groupIDs = (array) $groupIDs;
6a488035 220
6b05374e 221 foreach ($groupIDs as $groupID) {
222 // first delete the current cache
223 self::clearGroupContactCache($groupID);
224 $params = array(array('group', 'IN', array($groupID), 0, 0));
abdb2607 225 // the below call updates the cache table as a byproduct of the query
6b05374e 226 CRM_Contact_BAO_Query::apiQuery($params, array('contact_id'), NULL, NULL, 0, 0, FALSE);
6a488035
TO
227 }
228 }
229
86538308 230 /**
adf28ffd 231 * Store values into the group contact cache.
232 *
233 * @todo review use of INSERT IGNORE. This function appears to be slower that inserting
234 * with a left join. Also, 200 at once seems too little.
235 *
6b05374e 236 * @param array $groupID
adf28ffd 237 * @param array $values
86538308 238 */
6b05374e 239 public static function store($groupID, &$values) {
6a488035
TO
240 $processed = FALSE;
241
242 // sort the values so we put group IDs in front and hence optimize
243 // mysql storage (or so we think) CRM-9493
244 sort($values);
eb917190 245
6a488035
TO
246 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
247 while (!empty($values)) {
248 $processed = TRUE;
353ffa53
TO
249 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
250 $str = implode(',', $input);
251 $sql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) VALUES $str;";
6a488035
TO
252 CRM_Core_DAO::executeQuery($sql);
253 }
254 self::updateCacheTime($groupID, $processed);
255 }
256
257 /**
fe482240 258 * Change the cache_date.
6a488035 259 *
5a4f6742
CW
260 * @param array $groupID
261 * @param bool $processed
262 * Whether the cache data was recently modified.
6a488035 263 */
00be9182 264 public static function updateCacheTime($groupID, $processed) {
6a488035
TO
265 // only update cache entry if we had any values
266 if ($processed) {
267 // also update the group with cache date information
a986056d 268 $now = date('YmdHis');
6a488035
TO
269 $refresh = 'null';
270 }
271 else {
353ffa53 272 $now = 'null';
6a488035
TO
273 $refresh = 'null';
274 }
275
276 $groupIDs = implode(',', $groupID);
277 $sql = "
278UPDATE civicrm_group
279SET cache_date = $now, refresh_date = $refresh
280WHERE id IN ( $groupIDs )
281";
282 CRM_Core_DAO::executeQuery($sql);
283 }
284
cee4f6a1 285 /**
6b05374e 286 * @deprecated function - the best function to call is
287 * CRM_Contact_BAO_Contact::updateContactCache at the moment, or api job.group_cache_flush
288 * to really force a flush.
cee4f6a1 289 *
6b05374e 290 * Remove this function altogether by mid 2018.
cc7b1cd9 291 *
6b05374e 292 * However, if updating code outside core to use this (or any BAO function) it is recommended that
293 * you add an api call to lock in into our contract. Currently there is not really a supported
294 * method for non core functions.
cee4f6a1 295 */
6b05374e 296 public static function remove() {
297 Civi::log()
298 ->warning('Deprecated code. This function should not be called without groupIDs. Extensions can use the api job.group_cache_flush for a hard flush or add an api option for soft flush', array('civi.tag' => 'deprecated'));
299 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
4ebc8d27 300 }
6a488035 301
4ebc8d27 302 /**
303 * Function to clear group contact cache and reset the corresponding
304 * group's cache and refresh date
305 *
ffb47ce2 306 * @param int $groupID
4ebc8d27 307 *
308 */
309 public static function clearGroupContactCache($groupID) {
310 $transaction = new CRM_Core_Transaction();
311 $query = "
312 DELETE g
313 FROM civicrm_group_contact_cache g
314 WHERE g.group_id = %1 ";
6a488035 315
4ebc8d27 316 $update = "
317 UPDATE civicrm_group g
318 SET cache_date = null, refresh_date = null
319 WHERE id = %1 ";
320
321 $params = array(
322 1 => array($groupID, 'Integer'),
323 );
6a488035 324
4ebc8d27 325 CRM_Core_DAO::executeQuery($query, $params);
6a488035
TO
326 // also update the cache_date for these groups
327 CRM_Core_DAO::executeQuery($update, $params);
6b05374e 328 unset(self::$_alreadyLoaded[$groupID]);
4ebc8d27 329
330 $transaction->commit();
6a488035
TO
331 }
332
801bafd7 333 /**
334 * Refresh the smart group cache tables.
335 *
336 * This involves clearing out any aged entries (based on the site timeout setting) and resetting the time outs.
337 *
338 * This function should be called via the opportunistic or deterministic cache refresh function to make the intent
339 * clear.
340 */
2b68a50c 341 protected static function flushCaches() {
cc7b1cd9 342 try {
343 $lock = self::getLockForRefresh();
344 }
345 catch (CRM_Core_Exception $e) {
346 // Someone else is kindly doing the refresh for us right now.
801bafd7 347 return;
348 }
801bafd7 349 $params = array(1 => array(self::getCacheInvalidDateTime(), 'String'));
cc7b1cd9 350 // @todo this is consistent with previous behaviour but as the first query could take several seconds the second
351 // could become inaccurate. It seems to make more sense to fetch them first & delete from an array (which would
352 // also reduce joins). If we do this we should also consider how best to iterate the groups. If we do them one at
353 // a time we could call a hook, allowing people to manage the frequency on their groups, or possibly custom searches
354 // might do that too. However, for 2000 groups that's 2000 iterations. If we do all once we potentially create a
355 // slow query. It's worth noting the speed issue generally relates to the size of the group but if one slow group
356 // is in a query with 500 fast ones all 500 get locked. One approach might be to calculate group size or the
357 // number of groups & then process all at once or many query runs depending on what is found. Of course those
358 // preliminary queries would need speed testing.
801bafd7 359 CRM_Core_DAO::executeQuery(
360 "
361 DELETE gc
362 FROM civicrm_group_contact_cache gc
363 INNER JOIN civicrm_group g ON g.id = gc.group_id
364 WHERE g.cache_date <= %1
365 ",
366 $params
367 );
368
cc7b1cd9 369 // Clear these out without resetting them because we are not building caches here, only clearing them,
370 // so the state is 'as if they had never been built'.
801bafd7 371 CRM_Core_DAO::executeQuery(
372 "
373 UPDATE civicrm_group g
cc7b1cd9 374 SET cache_date = NULL,
375 refresh_date = NULL
801bafd7 376 WHERE g.cache_date <= %1
377 ",
378 $params
379 );
cc7b1cd9 380 $lock->release();
801bafd7 381 }
382
383 /**
384 * Check if the refresh is already initiated.
385 *
386 * We have 2 imperfect methods for this:
387 * 1) a static variable in the function. This works fine within a request
388 * 2) a mysql lock. This works fine as long as CiviMail is not running, or if mysql is version 5.7+
389 *
390 * Where these 2 locks fail we get 2 processes running at the same time, but we have at least minimised that.
cc7b1cd9 391 *
392 * @return \Civi\Core\Lock\LockInterface
393 * @throws \CRM_Core_Exception
801bafd7 394 */
cc7b1cd9 395 protected static function getLockForRefresh() {
0626851e 396 if (!isset(Civi::$statics[__CLASS__]['is_refresh_init'])) {
cc7b1cd9 397 Civi::$statics[__CLASS__] = array('is_refresh_init' => FALSE);
398 }
399
400 if (Civi::$statics[__CLASS__]['is_refresh_init']) {
401 throw new CRM_Core_Exception('A refresh has already run in this process');
801bafd7 402 }
403 $lock = Civi::lockManager()->acquire('data.core.group.refresh');
cc7b1cd9 404 if ($lock->isAcquired()) {
405 Civi::$statics[__CLASS__]['is_refresh_init'] = TRUE;
406 return $lock;
801bafd7 407 }
cc7b1cd9 408 throw new CRM_Core_Exception('Mysql lock unavailable');
801bafd7 409 }
410
411 /**
412 * Do an opportunistic cache refresh if the site is configured for these.
413 *
e047612e
CB
414 * Sites that do not run the smart group clearing cron job should refresh the
415 * caches on demand. The user session will be forced to wait so it is less
416 * ideal.
801bafd7 417 */
2b68a50c 418 public static function opportunisticCacheFlush() {
cc7b1cd9 419 if (Civi::settings()->get('smart_group_cache_refresh_mode') == 'opportunistic') {
2b68a50c 420 self::flushCaches();
801bafd7 421 }
422 }
423
424 /**
425 * Do a forced cache refresh.
426 *
427 * This function is appropriate to be called by system jobs & non-user sessions.
801bafd7 428 */
2b68a50c 429 public static function deterministicCacheFlush() {
801bafd7 430 if (self::smartGroupCacheTimeout() == 0) {
431 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_group_contact_cache");
432 CRM_Core_DAO::executeQuery("
433 UPDATE civicrm_group g
434 SET cache_date = null, refresh_date = null");
435 }
436 else {
2b68a50c 437 self::flushCaches();
801bafd7 438 }
439 }
440
2c6bbd06 441 /**
adf28ffd 442 * Remove one or more contacts from the smart group cache.
443 *
2c6bbd06
CW
444 * @param int|array $cid
445 * @param int $groupId
adf28ffd 446 *
4eeb9a5b
TO
447 * @return bool
448 * TRUE if successful.
2c6bbd06 449 */
00be9182 450 public static function removeContact($cid, $groupId = NULL) {
2c6bbd06
CW
451 $cids = array();
452 // sanitize input
453 foreach ((array) $cid as $c) {
454 $cids[] = CRM_Utils_Type::escape($c, 'Integer');
455 }
456 if ($cids) {
457 $condition = count($cids) == 1 ? "= {$cids[0]}" : "IN (" . implode(',', $cids) . ")";
458 if ($groupId) {
459 $condition .= " AND group_id = " . CRM_Utils_Type::escape($groupId, 'Integer');
460 }
461 $sql = "DELETE FROM civicrm_group_contact_cache WHERE contact_id $condition";
462 CRM_Core_DAO::executeQuery($sql);
463 return TRUE;
464 }
465 return FALSE;
466 }
467
6a488035 468 /**
fe482240 469 * Load the smart group cache for a saved search.
abdb2607 470 *
77c5b619
TO
471 * @param object $group
472 * The smart group that needs to be loaded.
473 * @param bool $force
474 * Should we force a search through.
6a488035 475 */
00be9182 476 public static function load(&$group, $force = FALSE) {
6a488035
TO
477 $groupID = $group->id;
478 $savedSearchID = $group->saved_search_id;
abdb2607 479 if (array_key_exists($groupID, self::$_alreadyLoaded) && !$force) {
6a488035
TO
480 return;
481 }
cc13551d 482
4052239b 483 // grab a lock so other processes don't compete and do the same query
83617886 484 $lock = Civi::lockManager()->acquire("data.core.group.{$groupID}");
cc13551d 485 if (!$lock->isAcquired()) {
4052239b 486 // this can cause inconsistent results since we don't know if the other process
cc13551d
DL
487 // will fill up the cache before our calling routine needs it.
488 // however this routine does not return the status either, so basically
489 // its a "lets return and hope for the best"
490 return;
491 }
492
6a488035 493 self::$_alreadyLoaded[$groupID] = 1;
abdb2607 494
b44e3f84 495 // we now have the lock, but some other process could have actually done the work
abdb2607
DL
496 // before we got here, so before we do any work, lets ensure that work needs to be
497 // done
498 // we allow hidden groups here since we dont know if the caller wants to evaluate an
499 // hidden group
3cd86345 500 if (!$force && !self::shouldGroupBeRefreshed($groupID, TRUE)) {
abdb2607
DL
501 $lock->release();
502 return;
503 }
504
353ffa53
TO
505 $sql = NULL;
506 $idName = 'id';
6a488035
TO
507 $customClass = NULL;
508 if ($savedSearchID) {
509 $ssParams = CRM_Contact_BAO_SavedSearch::getSearchParams($savedSearchID);
510
511 // rectify params to what proximity search expects if there is a value for prox_distance
512 // CRM-7021
513 if (!empty($ssParams)) {
514 CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams);
515 }
516
6a488035
TO
517 $returnProperties = array();
518 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) {
519 $fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
520 $returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv);
521 }
522
523 if (isset($ssParams['customSearchID'])) {
524 // if custom search
525
526 // we split it up and store custom class
527 // so temp tables are not destroyed if they are used
528 // hence customClass is defined above at top of function
5396af74 529 $customClass = CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID);
6a488035 530 $searchSQL = $customClass->contactIDs();
26a9b6ab 531 $searchSQL = str_replace('ORDER BY contact_a.id ASC', '', $searchSQL);
d02c030f 532 if (!strstr($searchSQL, 'WHERE')) {
533 $searchSQL .= " WHERE ( 1 ) ";
534 }
6a488035
TO
535 $idName = 'contact_id';
536 }
537 else {
538 $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
beccb90f 539 // CRM-17075 using the formValues in this way imposes extra logic and complexity.
540 // we have the where_clause and where tables stored in the saved_search table
541 // and should use these rather than re-processing the form criteria (which over-works
542 // the link between the form layer & the query layer too).
543 // It's hard to think of when you would want to use anything other than return
544 // properties = array('contact_id' => 1) here as the point would appear to be to
545 // generate the list of contact ids in the group.
546 // @todo review this to use values in saved_search table (preferably for 4.8).
5396af74 547 $query
548 = new CRM_Contact_BAO_Query(
6a488035 549 $ssParams, $returnProperties, NULL,
cc13551d
DL
550 FALSE, FALSE, 1,
551 TRUE, TRUE,
552 FALSE,
6a488035
TO
553 CRM_Utils_Array::value('display_relationship_type', $formValues),
554 CRM_Utils_Array::value('operator', $formValues, 'AND')
353ffa53 555 );
6a488035 556 $query->_useDistinct = FALSE;
353ffa53 557 $query->_useGroupBy = FALSE;
5396af74 558 $searchSQL
559 = $query->searchQuery(
6a488035 560 0, 0, NULL,
353ffa53
TO
561 FALSE, FALSE,
562 FALSE, TRUE,
563 TRUE,
564 NULL, NULL, NULL,
565 TRUE
566 );
6a488035
TO
567 }
568 $groupID = CRM_Utils_Type::escape($groupID, 'Integer');
569 $sql = $searchSQL . " AND contact_a.id NOT IN (
570 SELECT contact_id FROM civicrm_group_contact
571 WHERE civicrm_group_contact.status = 'Removed'
572 AND civicrm_group_contact.group_id = $groupID ) ";
573 }
574
575 if ($sql) {
576 $sql = preg_replace("/^\s*SELECT/", "SELECT $groupID as group_id, ", $sql);
577 }
578
579 // lets also store the records that are explicitly added to the group
580 // this allows us to skip the group contact LEFT JOIN
581 $sqlB = "
582SELECT $groupID as group_id, contact_id as $idName
583FROM civicrm_group_contact
584WHERE civicrm_group_contact.status = 'Added'
585 AND civicrm_group_contact.group_id = $groupID ";
586
6b05374e 587 self::clearGroupContactCache($groupID);
588
abdb2607 589 $processed = FALSE;
353ffa53 590 $tempTable = 'civicrm_temp_group_contact_cache' . rand(0, 2000);
6a488035
TO
591 foreach (array($sql, $sqlB) as $selectSql) {
592 if (!$selectSql) {
593 continue;
594 }
b8eae4bd 595 $insertSql = "CREATE TEMPORARY TABLE $tempTable ($selectSql);";
eb917190 596 $processed = TRUE;
801bafd7 597 CRM_Core_DAO::executeQuery($insertSql);
b8eae4bd 598 CRM_Core_DAO::executeQuery(
599 "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)
eab13399 600 SELECT DISTINCT $idName, group_id FROM $tempTable
b8eae4bd 601 ");
5467c9fb 602 CRM_Core_DAO::executeQuery(" DROP TEMPORARY TABLE $tempTable");
6a488035 603 }
b8eae4bd 604
6b05374e 605 self::updateCacheTime(array($groupID), $processed);
6a488035
TO
606
607 if ($group->children) {
608
609 //Store a list of contacts who are removed from the parent group
610 $sql = "
611SELECT contact_id
612FROM civicrm_group_contact
613WHERE civicrm_group_contact.status = 'Removed'
614AND civicrm_group_contact.group_id = $groupID ";
615 $dao = CRM_Core_DAO::executeQuery($sql);
616 $removed_contacts = array();
617 while ($dao->fetch()) {
618 $removed_contacts[] = $dao->contact_id;
619 }
620
621 $childrenIDs = explode(',', $group->children);
622 foreach ($childrenIDs as $childID) {
623 $contactIDs = CRM_Contact_BAO_Group::getMember($childID, FALSE);
624 //Unset each contact that is removed from the parent group
625 foreach ($removed_contacts as $removed_contact) {
626 unset($contactIDs[$removed_contact]);
627 }
628 $values = array();
629 foreach ($contactIDs as $contactID => $dontCare) {
630 $values[] = "({$groupID},{$contactID})";
631 }
632
6b05374e 633 self::store(array($groupID), $values);
6a488035
TO
634 }
635 }
cc13551d
DL
636
637 $lock->release();
6a488035
TO
638 }
639
86538308 640 /**
adf28ffd 641 * Retrieve the smart group cache timeout in minutes.
642 *
643 * This checks if a timeout has been configured. If one has then smart groups should not
644 * be refreshed more frequently than the time out. If a group was recently refreshed it should not
645 * refresh again within that period.
646 *
86538308
EM
647 * @return int
648 */
00be9182 649 public static function smartGroupCacheTimeout() {
6a488035
TO
650 $config = CRM_Core_Config::singleton();
651
652 if (
653 isset($config->smartGroupCacheTimeout) &&
9bdcddd7 654 is_numeric($config->smartGroupCacheTimeout)
353ffa53 655 ) {
6a488035
TO
656 return $config->smartGroupCacheTimeout;
657 }
658
adf28ffd 659 // Default to 5 minutes.
6a488035
TO
660 return 5;
661 }
662
9be31c7a 663 /**
fe482240 664 * Get all the smart groups that this contact belongs to.
adf28ffd 665 *
9be31c7a
DL
666 * Note that this could potentially be a super slow function since
667 * it ensure that all contact groups are loaded in the cache
668 *
77c5b619
TO
669 * @param int $contactID
670 * @param bool $showHidden
671 * Hidden groups are shown only if this flag is set.
9be31c7a 672 *
a6c01b45
CW
673 * @return array
674 * an array of groups that this contact belongs to
9be31c7a 675 */
00be9182 676 public static function contactGroup($contactID, $showHidden = FALSE) {
6a488035 677 if (empty($contactID)) {
5396af74 678 return NULL;
6a488035
TO
679 }
680
681 if (is_array($contactID)) {
682 $contactIDs = $contactID;
683 }
684 else {
685 $contactIDs = array($contactID);
686 }
687
688 self::loadAll();
689
9be31c7a
DL
690 $hiddenClause = '';
691 if (!$showHidden) {
692 $hiddenClause = ' AND (g.is_hidden = 0 OR g.is_hidden IS NULL) ';
693 }
694
6a488035
TO
695 $contactIDString = CRM_Core_DAO::escapeString(implode(', ', $contactIDs));
696 $sql = "
697SELECT gc.group_id, gc.contact_id, g.title, g.children, g.description
698FROM civicrm_group_contact_cache gc
699INNER JOIN civicrm_group g ON g.id = gc.group_id
700WHERE gc.contact_id IN ($contactIDString)
9be31c7a 701 $hiddenClause
6a488035
TO
702ORDER BY gc.contact_id, g.children
703";
704
705 $dao = CRM_Core_DAO::executeQuery($sql);
706 $contactGroup = array();
e60f24eb 707 $prevContactID = NULL;
6a488035
TO
708 while ($dao->fetch()) {
709 if (
710 $prevContactID &&
711 $prevContactID != $dao->contact_id
712 ) {
713 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
714 }
715 $prevContactID = $dao->contact_id;
716 if (!array_key_exists($dao->contact_id, $contactGroup)) {
5396af74 717 $contactGroup[$dao->contact_id]
718 = array('group' => array(), 'groupTitle' => array());
6a488035
TO
719 }
720
5396af74 721 $contactGroup[$dao->contact_id]['group'][]
722 = array(
6a488035
TO
723 'id' => $dao->group_id,
724 'title' => $dao->title,
725 'description' => $dao->description,
21dfd5f5 726 'children' => $dao->children,
6a488035
TO
727 );
728 $contactGroup[$dao->contact_id]['groupTitle'][] = $dao->title;
729 }
730
731 if ($prevContactID) {
732 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
733 }
734
13982f7b 735 if ((!empty($contactGroup[$contactID]) && is_numeric($contactID))) {
6a488035
TO
736 return $contactGroup[$contactID];
737 }
738 else {
739 return $contactGroup;
740 }
741 }
742
4052239b 743 /**
744 * Get the datetime from which the cache should be considered invalid.
745 *
746 * Ie if the smartgroup cache timeout is 5 minutes ago then the cache is invalid if it was
747 * refreshed 6 minutes ago, but not if it was refreshed 4 minutes ago.
748 *
749 * @return string
750 */
751 public static function getCacheInvalidDateTime() {
8b6074a7 752 return date('YmdHis', strtotime("-" . self::smartGroupCacheTimeout() . " Minutes"));
4052239b 753 }
754
a986056d 755 /**
756 * Get the date when the cache should be refreshed from.
757 *
758 * Ie. now + the offset & we will delete anything prior to then.
759 *
760 * @return string
761 */
4052239b 762 public static function getRefreshDateTime() {
8b6074a7 763 return date('YmdHis', strtotime("+ " . self::smartGroupCacheTimeout() . " Minutes"));
a986056d 764 }
765
6a488035 766}