e05bd90938ae7de26ef804b9927f4d9c9ab29415
[civicrm-core.git] / CRM / Contact / BAO / GroupContactCache.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33 class CRM_Contact_BAO_GroupContactCache extends CRM_Contact_DAO_GroupContactCache {
34
35 static $_alreadyLoaded = [];
36
37 /**
38 * Get a list of caching modes.
39 *
40 * @return array
41 */
42 public static function getModes() {
43 return [
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
52 /**
53 * Check to see if we have cache entries for this group.
54 *
55 * If not, regenerate, else return.
56 *
57 * @param array $groupIDs
58 * Of group that we are checking against.
59 *
60 * @return bool
61 * TRUE if we did not regenerate, FALSE if we did
62 */
63 public static function check($groupIDs) {
64 if (empty($groupIDs)) {
65 return TRUE;
66 }
67
68 return self::loadAll($groupIDs);
69 }
70
71 /**
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
75 *
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.
80 *
81 * @return string
82 * the sql query which lists the groups that need to be refreshed
83 */
84 public static function groupRefreshedClause($groupIDClause = NULL, $includeHiddenGroups = FALSE) {
85 $smartGroupCacheTimeoutDateTime = self::getCacheInvalidDateTime();
86
87 $query = "
88 SELECT g.id
89 FROM civicrm_group g
90 WHERE ( g.saved_search_id IS NOT NULL OR g.children IS NOT NULL )
91 AND g.is_active = 1
92 AND (
93 g.cache_date IS NULL
94 OR cache_date <= $smartGroupCacheTimeoutDateTime
95 OR NOW() >= g.refresh_date
96 )";
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 /**
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
113 * this process
114 *
115 * @param int $groupID
116 * The group ID.
117 * @param bool $includeHiddenGroups
118 * Hidden groups are excluded by default.
119 *
120 * @return string
121 * the sql query which lists the groups that need to be refreshed
122 */
123 public static function shouldGroupBeRefreshed($groupID, $includeHiddenGroups = FALSE) {
124 $query = self::groupRefreshedClause("g.id = %1", $includeHiddenGroups);
125 $params = [1 => [$groupID, 'Integer']];
126
127 // if the query returns the group ID, it means the group is a valid candidate for refreshing
128 return CRM_Core_DAO::singleValueQuery($query, $params);
129 }
130
131 /**
132 * Check to see if we have cache entries for this group.
133 *
134 * if not, regenerate, else return
135 *
136 * @param int|array $groupIDs groupIDs of group that we are checking against
137 * if empty, all groups are checked
138 * @param int $limit
139 * Limits the number of groups we evaluate.
140 *
141 * @return bool
142 * TRUE if we did not regenerate, FALSE if we did
143 */
144 public static function loadAll($groupIDs = NULL, $limit = 0) {
145 // ensure that all the smart groups are loaded
146 // this function is expensive and should be sparingly used if groupIDs is empty
147 if (empty($groupIDs)) {
148 $groupIDClause = NULL;
149 $groupIDs = [];
150 }
151 else {
152 if (!is_array($groupIDs)) {
153 $groupIDs = [$groupIDs];
154 }
155
156 // note escapeString is a must here and we can't send the imploded value as second argument 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.
159 $groupIDString = CRM_Core_DAO::escapeString(implode(', ', $groupIDs));
160
161 $groupIDClause = "g.id IN ({$groupIDString})";
162 }
163
164 $query = self::groupRefreshedClause($groupIDClause);
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 }
171 // We ignore hidden groups and disabled groups
172 $query .= "
173 $orderClause
174 $limitClause
175 ";
176
177 $dao = CRM_Core_DAO::executeQuery($query);
178 $processGroupIDs = [];
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)) {
193 $refreshGroupIDString = CRM_Core_DAO::escapeString(implode(', ', $refreshGroupIDs));
194 $time = self::getRefreshDateTime();
195 $query = "
196 UPDATE civicrm_group g
197 SET g.refresh_date = $time
198 WHERE g.id IN ( {$refreshGroupIDString} )
199 AND g.refresh_date IS NULL
200 ";
201 CRM_Core_DAO::executeQuery($query);
202 }
203
204 if (empty($processGroupIDs)) {
205 return TRUE;
206 }
207 else {
208 self::add($processGroupIDs);
209 return FALSE;
210 }
211 }
212
213 /**
214 * Build the smart group cache for given groups.
215 *
216 * @param array $groupIDs
217 */
218 public static function add($groupIDs) {
219 $groupIDs = (array) $groupIDs;
220
221 foreach ($groupIDs as $groupID) {
222 // first delete the current cache
223 self::clearGroupContactCache($groupID);
224 $params = [['group', 'IN', [$groupID], 0, 0]];
225 // the below call updates the cache table as a byproduct of the query
226 CRM_Contact_BAO_Query::apiQuery($params, ['contact_id'], NULL, NULL, 0, 0, FALSE);
227 }
228 }
229
230 /**
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 *
236 * @param array $groupID
237 * @param array $values
238 */
239 public static function store($groupID, &$values) {
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);
245
246 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
247 while (!empty($values)) {
248 $processed = TRUE;
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;";
252 CRM_Core_DAO::executeQuery($sql);
253 }
254 self::updateCacheTime($groupID, $processed);
255 }
256
257 /**
258 * Change the cache_date.
259 *
260 * @param array $groupID
261 * @param bool $processed
262 * Whether the cache data was recently modified.
263 */
264 public static function updateCacheTime($groupID, $processed) {
265 // only update cache entry if we had any values
266 if ($processed) {
267 // also update the group with cache date information
268 $now = date('YmdHis');
269 $refresh = 'null';
270 }
271 else {
272 $now = 'null';
273 $refresh = 'null';
274 }
275
276 $groupIDs = implode(',', $groupID);
277 $sql = "
278 UPDATE civicrm_group
279 SET cache_date = $now, refresh_date = $refresh
280 WHERE id IN ( $groupIDs )
281 ";
282 CRM_Core_DAO::executeQuery($sql);
283 }
284
285 /**
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.
289 *
290 * Remove this function altogether by mid 2018.
291 *
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.
295 */
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', ['civi.tag' => 'deprecated']);
299 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
300 }
301
302 /**
303 * Function to clear group contact cache and reset the corresponding
304 * group's cache and refresh date
305 *
306 * @param int $groupID
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 ";
315
316 $update = "
317 UPDATE civicrm_group g
318 SET cache_date = null, refresh_date = null
319 WHERE id = %1 ";
320
321 $params = [
322 1 => [$groupID, 'Integer'],
323 ];
324
325 CRM_Core_DAO::executeQuery($query, $params);
326 // also update the cache_date for these groups
327 CRM_Core_DAO::executeQuery($update, $params);
328 unset(self::$_alreadyLoaded[$groupID]);
329
330 $transaction->commit();
331 }
332
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 */
341 protected static function flushCaches() {
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.
347 return;
348 }
349 $params = [1 => [self::getCacheInvalidDateTime(), 'String']];
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.
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
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'.
371 CRM_Core_DAO::executeQuery(
372 "
373 UPDATE civicrm_group g
374 SET cache_date = NULL,
375 refresh_date = NULL
376 WHERE g.cache_date <= %1
377 ",
378 $params
379 );
380 $lock->release();
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.
391 *
392 * @return \Civi\Core\Lock\LockInterface
393 * @throws \CRM_Core_Exception
394 */
395 protected static function getLockForRefresh() {
396 if (!isset(Civi::$statics[__CLASS__]['is_refresh_init'])) {
397 Civi::$statics[__CLASS__] = ['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');
402 }
403 $lock = Civi::lockManager()->acquire('data.core.group.refresh');
404 if ($lock->isAcquired()) {
405 Civi::$statics[__CLASS__]['is_refresh_init'] = TRUE;
406 return $lock;
407 }
408 throw new CRM_Core_Exception('Mysql lock unavailable');
409 }
410
411 /**
412 * Do an opportunistic cache refresh if the site is configured for these.
413 *
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.
417 */
418 public static function opportunisticCacheFlush() {
419 if (Civi::settings()->get('smart_group_cache_refresh_mode') == 'opportunistic') {
420 self::flushCaches();
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.
428 */
429 public static function deterministicCacheFlush() {
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 {
437 self::flushCaches();
438 }
439 }
440
441 /**
442 * Remove one or more contacts from the smart group cache.
443 *
444 * @param int|array $cid
445 * @param int $groupId
446 *
447 * @return bool
448 * TRUE if successful.
449 */
450 public static function removeContact($cid, $groupId = NULL) {
451 $cids = [];
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
468 /**
469 * Load the smart group cache for a saved search.
470 *
471 * @param object $group
472 * The smart group that needs to be loaded.
473 * @param bool $force
474 * Should we force a search through.
475 */
476 public static function load(&$group, $force = FALSE) {
477 $groupID = $group->id;
478 $savedSearchID = $group->saved_search_id;
479 if (array_key_exists($groupID, self::$_alreadyLoaded) && !$force) {
480 return;
481 }
482
483 // grab a lock so other processes don't compete and do the same query
484 $lock = Civi::lockManager()->acquire("data.core.group.{$groupID}");
485 if (!$lock->isAcquired()) {
486 // this can cause inconsistent results since we don't know if the other process
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
493 self::$_alreadyLoaded[$groupID] = 1;
494
495 // we now have the lock, but some other process could have actually done the work
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
500 if (!$force && !self::shouldGroupBeRefreshed($groupID, TRUE)) {
501 $lock->release();
502 return;
503 }
504
505 $sql = NULL;
506 $idName = 'id';
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
517 $returnProperties = [];
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
529 $customClass = CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID);
530 $searchSQL = $customClass->contactIDs();
531 $searchSQL = str_replace('ORDER BY contact_a.id ASC', '', $searchSQL);
532 if (!strstr($searchSQL, 'WHERE')) {
533 $searchSQL .= " WHERE ( 1 ) ";
534 }
535 $idName = 'contact_id';
536 }
537 else {
538 $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
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).
547 $query
548 = new CRM_Contact_BAO_Query(
549 $ssParams, $returnProperties, NULL,
550 FALSE, FALSE, 1,
551 TRUE, TRUE,
552 FALSE,
553 CRM_Utils_Array::value('display_relationship_type', $formValues),
554 CRM_Utils_Array::value('operator', $formValues, 'AND')
555 );
556 $query->_useDistinct = FALSE;
557 $query->_useGroupBy = FALSE;
558 $sqlParts = $query->getSearchSQLParts(
559 0, 0, NULL,
560 FALSE, FALSE,
561 FALSE, TRUE
562 );
563 $searchSQL = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}";
564 }
565 $groupID = CRM_Utils_Type::escape($groupID, 'Integer');
566 $sql = $searchSQL . " AND contact_a.id NOT IN (
567 SELECT contact_id FROM civicrm_group_contact
568 WHERE civicrm_group_contact.status = 'Removed'
569 AND civicrm_group_contact.group_id = $groupID ) ";
570 }
571
572 if ($sql) {
573 $sql = preg_replace("/^\s*SELECT/", "SELECT $groupID as group_id, ", $sql);
574 }
575
576 // lets also store the records that are explicitly added to the group
577 // this allows us to skip the group contact LEFT JOIN
578 $sqlB = "
579 SELECT $groupID as group_id, contact_id as $idName
580 FROM civicrm_group_contact
581 WHERE civicrm_group_contact.status = 'Added'
582 AND civicrm_group_contact.group_id = $groupID ";
583
584 self::clearGroupContactCache($groupID);
585
586 $processed = FALSE;
587 $tempTable = 'civicrm_temp_group_contact_cache' . rand(0, 2000);
588 foreach ([$sql, $sqlB] as $selectSql) {
589 if (!$selectSql) {
590 continue;
591 }
592 $insertSql = "CREATE TEMPORARY TABLE $tempTable ($selectSql);";
593 $processed = TRUE;
594 CRM_Core_DAO::executeQuery($insertSql);
595 CRM_Core_DAO::executeQuery(
596 "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)
597 SELECT DISTINCT $idName, group_id FROM $tempTable
598 ");
599 CRM_Core_DAO::executeQuery(" DROP TEMPORARY TABLE $tempTable");
600 }
601
602 self::updateCacheTime([$groupID], $processed);
603
604 if ($group->children) {
605
606 //Store a list of contacts who are removed from the parent group
607 $sql = "
608 SELECT contact_id
609 FROM civicrm_group_contact
610 WHERE civicrm_group_contact.status = 'Removed'
611 AND civicrm_group_contact.group_id = $groupID ";
612 $dao = CRM_Core_DAO::executeQuery($sql);
613 $removed_contacts = [];
614 while ($dao->fetch()) {
615 $removed_contacts[] = $dao->contact_id;
616 }
617
618 $childrenIDs = explode(',', $group->children);
619 foreach ($childrenIDs as $childID) {
620 $contactIDs = CRM_Contact_BAO_Group::getMember($childID, FALSE);
621 //Unset each contact that is removed from the parent group
622 foreach ($removed_contacts as $removed_contact) {
623 unset($contactIDs[$removed_contact]);
624 }
625 $values = [];
626 foreach ($contactIDs as $contactID => $dontCare) {
627 $values[] = "({$groupID},{$contactID})";
628 }
629
630 self::store([$groupID], $values);
631 }
632 }
633
634 $lock->release();
635 }
636
637 /**
638 * Retrieve the smart group cache timeout in minutes.
639 *
640 * This checks if a timeout has been configured. If one has then smart groups should not
641 * be refreshed more frequently than the time out. If a group was recently refreshed it should not
642 * refresh again within that period.
643 *
644 * @return int
645 */
646 public static function smartGroupCacheTimeout() {
647 $config = CRM_Core_Config::singleton();
648
649 if (
650 isset($config->smartGroupCacheTimeout) &&
651 is_numeric($config->smartGroupCacheTimeout)
652 ) {
653 return $config->smartGroupCacheTimeout;
654 }
655
656 // Default to 5 minutes.
657 return 5;
658 }
659
660 /**
661 * Get all the smart groups that this contact belongs to.
662 *
663 * Note that this could potentially be a super slow function since
664 * it ensure that all contact groups are loaded in the cache
665 *
666 * @param int $contactID
667 * @param bool $showHidden
668 * Hidden groups are shown only if this flag is set.
669 *
670 * @return array
671 * an array of groups that this contact belongs to
672 */
673 public static function contactGroup($contactID, $showHidden = FALSE) {
674 if (empty($contactID)) {
675 return NULL;
676 }
677
678 if (is_array($contactID)) {
679 $contactIDs = $contactID;
680 }
681 else {
682 $contactIDs = [$contactID];
683 }
684
685 self::loadAll();
686
687 $hiddenClause = '';
688 if (!$showHidden) {
689 $hiddenClause = ' AND (g.is_hidden = 0 OR g.is_hidden IS NULL) ';
690 }
691
692 $contactIDString = CRM_Core_DAO::escapeString(implode(', ', $contactIDs));
693 $sql = "
694 SELECT gc.group_id, gc.contact_id, g.title, g.children, g.description
695 FROM civicrm_group_contact_cache gc
696 INNER JOIN civicrm_group g ON g.id = gc.group_id
697 WHERE gc.contact_id IN ($contactIDString)
698 $hiddenClause
699 ORDER BY gc.contact_id, g.children
700 ";
701
702 $dao = CRM_Core_DAO::executeQuery($sql);
703 $contactGroup = [];
704 $prevContactID = NULL;
705 while ($dao->fetch()) {
706 if (
707 $prevContactID &&
708 $prevContactID != $dao->contact_id
709 ) {
710 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
711 }
712 $prevContactID = $dao->contact_id;
713 if (!array_key_exists($dao->contact_id, $contactGroup)) {
714 $contactGroup[$dao->contact_id]
715 = ['group' => [], 'groupTitle' => []];
716 }
717
718 $contactGroup[$dao->contact_id]['group'][]
719 = [
720 'id' => $dao->group_id,
721 'title' => $dao->title,
722 'description' => $dao->description,
723 'children' => $dao->children,
724 ];
725 $contactGroup[$dao->contact_id]['groupTitle'][] = $dao->title;
726 }
727
728 if ($prevContactID) {
729 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
730 }
731
732 if ((!empty($contactGroup[$contactID]) && is_numeric($contactID))) {
733 return $contactGroup[$contactID];
734 }
735 else {
736 return $contactGroup;
737 }
738 }
739
740 /**
741 * Get the datetime from which the cache should be considered invalid.
742 *
743 * Ie if the smartgroup cache timeout is 5 minutes ago then the cache is invalid if it was
744 * refreshed 6 minutes ago, but not if it was refreshed 4 minutes ago.
745 *
746 * @return string
747 */
748 public static function getCacheInvalidDateTime() {
749 return date('YmdHis', strtotime("-" . self::smartGroupCacheTimeout() . " Minutes"));
750 }
751
752 /**
753 * Get the date when the cache should be refreshed from.
754 *
755 * Ie. now + the offset & we will delete anything prior to then.
756 *
757 * @return string
758 */
759 public static function getRefreshDateTime() {
760 return date('YmdHis', strtotime("+ " . self::smartGroupCacheTimeout() . " Minutes"));
761 }
762
763 }