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