Merge pull request #21384 from mattwire/groupcontactcache
[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 use Civi\API\Request;
13 use Civi\Api4\Group;
14 use Civi\Api4\Query\Api4SelectQuery;
15 use Civi\Api4\Query\SqlExpression;
16 use Civi\Api4\SavedSearch;
17
18 /**
19 *
20 * @package CRM
21 * @copyright CiviCRM LLC https://civicrm.org/licensing
22 */
23 class CRM_Contact_BAO_GroupContactCache extends CRM_Contact_DAO_GroupContactCache {
24
25 /**
26 * Get a list of caching modes.
27 *
28 * @return array
29 */
30 public static function getModes(): array {
31 return [
32 // Flush expired caches in response to user actions.
33 'opportunistic' => ts('Opportunistic Flush'),
34 // Flush expired caches via background cron jobs.
35 'deterministic' => ts('Cron Flush'),
36 ];
37 }
38
39 /**
40 * Check to see if we have cache entries for this group.
41 *
42 * If not, regenerate, else return.
43 *
44 * @param array $groupIDs
45 * Of group that we are checking against.
46 *
47 * @return bool
48 * TRUE if we did not regenerate, FALSE if we did
49 */
50 public static function check($groupIDs): bool {
51 if (empty($groupIDs)) {
52 return TRUE;
53 }
54
55 return self::loadAll($groupIDs);
56 }
57
58 /**
59 * Formulate the query to see which groups needs to be refreshed.
60 *
61 * The calculation is based on their cache date and the smartGroupCacheTimeOut
62 *
63 * @param string $groupIDClause
64 * The clause which limits which groups we need to evaluate.
65 * @param bool $includeHiddenGroups
66 * Hidden groups are excluded by default.
67 *
68 * @return string
69 * the sql query which lists the groups that need to be refreshed
70 */
71 protected static function groupRefreshedClause($groupIDClause = NULL, $includeHiddenGroups = FALSE): string {
72 $smartGroupCacheTimeoutDateTime = self::getCacheInvalidDateTime();
73
74 $query = "
75 SELECT g.id
76 FROM civicrm_group g
77 WHERE ( g.saved_search_id IS NOT NULL OR g.children IS NOT NULL )
78 AND g.is_active = 1
79 AND (
80 g.cache_date IS NULL
81 OR cache_date <= $smartGroupCacheTimeoutDateTime
82 )";
83
84 if (!$includeHiddenGroups) {
85 $query .= "AND (g.is_hidden = 0 OR g.is_hidden IS NULL)";
86 }
87
88 if (!empty($groupIDClause)) {
89 $query .= " AND ( $groupIDClause ) ";
90 }
91
92 return $query;
93 }
94
95 /**
96 * Check to see if a group has been refreshed recently.
97 *
98 * This is primarily used in a locking scenario when some other process might have refreshed things underneath
99 * this process
100 *
101 * @param int $groupID
102 * The group ID.
103 *
104 * @return bool
105 */
106 public static function shouldGroupBeRefreshed($groupID): bool {
107 $query = self::groupRefreshedClause('g.id = %1');
108 $params = [1 => [$groupID, 'Integer']];
109
110 // if the query returns the group ID, it means the group is a valid candidate for refreshing
111 return (bool) CRM_Core_DAO::singleValueQuery($query, $params);
112 }
113
114 /**
115 * Check to see if we have cache entries for this group.
116 *
117 * if not, regenerate, else return
118 *
119 * @param array|null $groupIDs groupIDs 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 bool
125 * TRUE if we did not regenerate, FALSE if we did
126 */
127 public static function loadAll($groupIDs = NULL, $limit = 0) {
128 if ($groupIDs) {
129 // Passing a single value is deprecated.
130 $groupIDs = (array) $groupIDs;
131 }
132
133 // Treat the default help text in Scheduled Jobs as equivalent to no limit.
134 $limit = (int) $limit;
135 $processGroupIDs = self::getGroupsNeedingRefreshing($groupIDs, $limit);
136
137 if (!empty($processGroupIDs)) {
138 self::add($processGroupIDs);
139 }
140 return TRUE;
141 }
142
143 /**
144 * Build the smart group cache for given groups.
145 *
146 * @param array $groupIDs
147 */
148 public static function add($groupIDs) {
149 $groupIDs = (array) $groupIDs;
150
151 foreach ($groupIDs as $groupID) {
152 // first delete the current cache
153 $params = [['group', 'IN', [$groupID], 0, 0]];
154 // the below call updates the cache table as a byproduct of the query
155 CRM_Contact_BAO_Query::apiQuery($params, ['contact_id'], NULL, NULL, 0, 0, FALSE);
156 }
157 }
158
159 /**
160 * Store values into the group contact cache.
161 *
162 * @todo review use of INSERT IGNORE. This function appears to be slower that inserting
163 * with a left join. Also, 200 at once seems too little.
164 *
165 * @param array $groupID
166 * @param array $values
167 */
168 protected static function store($groupID, &$values) {
169 $processed = FALSE;
170
171 // sort the values so we put group IDs in front and hence optimize
172 // mysql storage (or so we think) CRM-9493
173 sort($values);
174
175 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
176 while (!empty($values)) {
177 $processed = TRUE;
178 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
179 $str = implode(',', $input);
180 $sql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) VALUES $str;";
181 CRM_Core_DAO::executeQuery($sql);
182 }
183 self::updateCacheTime($groupID, $processed);
184 }
185
186 /**
187 * Change the cache_date.
188 *
189 * @param array $groupID
190 * @param bool $processed
191 * Whether the cache data was recently modified.
192 */
193 protected static function updateCacheTime($groupID, $processed) {
194 // only update cache entry if we had any values
195 if ($processed) {
196 // also update the group with cache date information
197 $now = date('YmdHis');
198 }
199 else {
200 $now = 'null';
201 }
202
203 $groupIDs = implode(',', $groupID);
204 $sql = "
205 UPDATE civicrm_group
206 SET cache_date = $now
207 WHERE id IN ( $groupIDs )
208 ";
209 CRM_Core_DAO::executeQuery($sql);
210 }
211
212 /**
213 * Function to clear group contact cache
214 *
215 * @param array $groupIDs
216 *
217 */
218 protected static function clearGroupContactCache($groupIDs): void {
219 $clearCacheQuery = '
220 DELETE g
221 FROM civicrm_group_contact_cache g
222 WHERE g.group_id IN (%1) ';
223 $params = [
224 1 => [implode(',', $groupIDs), 'CommaSeparatedIntegers'],
225 ];
226 CRM_Core_DAO::executeQuery($clearCacheQuery, $params);
227 }
228
229 /**
230 * Refresh the smart group cache tables.
231 *
232 * This involves clearing out any aged entries (based on the site timeout setting) and resetting the time outs.
233 *
234 * This function should be called via the opportunistic or deterministic cache refresh function to make the intent
235 * clear.
236 */
237 protected static function flushCaches() {
238 if (!CRM_Core_Config::isPermitCacheFlushMode()) {
239 return;
240 }
241
242 try {
243 $lock = self::getLockForRefresh();
244 }
245 catch (CRM_Core_Exception $e) {
246 // Someone else is kindly doing the refresh for us right now.
247 return;
248 }
249 $params = [1 => [self::getCacheInvalidDateTime(), 'String']];
250 $groupsDAO = CRM_Core_DAO::executeQuery("SELECT id FROM civicrm_group WHERE cache_date <= %1", $params);
251 $expiredGroups = [];
252 while ($groupsDAO->fetch()) {
253 $expiredGroups[] = $groupsDAO->id;
254 }
255 if (!empty($expiredGroups)) {
256 $expiredGroups = implode(',', $expiredGroups);
257 CRM_Core_DAO::executeQuery("DELETE FROM civicrm_group_contact_cache WHERE group_id IN ({$expiredGroups})");
258
259 // Clear these out without resetting them because we are not building caches here, only clearing them,
260 // so the state is 'as if they had never been built'.
261 CRM_Core_DAO::executeQuery("UPDATE civicrm_group SET cache_date = NULL WHERE id IN ({$expiredGroups})");
262 }
263 $lock->release();
264 }
265
266 /**
267 * Check if the refresh is already initiated.
268 *
269 * We have 2 imperfect methods for this:
270 * 1) a static variable in the function. This works fine within a request
271 * 2) a mysql lock. This works fine as long as CiviMail is not running, or if mysql is version 5.7+
272 *
273 * Where these 2 locks fail we get 2 processes running at the same time, but we have at least minimised that.
274 *
275 * @return \Civi\Core\Lock\LockInterface
276 * @throws \CRM_Core_Exception
277 */
278 protected static function getLockForRefresh() {
279 if (!isset(Civi::$statics[__CLASS__]['is_refresh_init'])) {
280 Civi::$statics[__CLASS__] = ['is_refresh_init' => FALSE];
281 }
282
283 if (Civi::$statics[__CLASS__]['is_refresh_init']) {
284 throw new CRM_Core_Exception('A refresh has already run in this process');
285 }
286 $lock = Civi::lockManager()->acquire('data.core.group.refresh');
287 if ($lock->isAcquired()) {
288 Civi::$statics[__CLASS__]['is_refresh_init'] = TRUE;
289 return $lock;
290 }
291 throw new CRM_Core_Exception('Mysql lock unavailable');
292 }
293
294 /**
295 * Do an opportunistic cache refresh if the site is configured for these.
296 *
297 * Sites that do not run the smart group clearing cron job should refresh the
298 * caches on demand. The user session will be forced to wait so it is less
299 * ideal.
300 */
301 public static function opportunisticCacheFlush(): void {
302 if (Civi::settings()->get('smart_group_cache_refresh_mode') === 'opportunistic') {
303 self::flushCaches();
304 }
305 }
306
307 /**
308 * Do a forced cache refresh.
309 *
310 * This function is appropriate to be called by system jobs & non-user sessions.
311 */
312 public static function deterministicCacheFlush() {
313 if (self::smartGroupCacheTimeout() == 0) {
314 CRM_Core_DAO::executeQuery("TRUNCATE civicrm_group_contact_cache");
315 CRM_Core_DAO::executeQuery("UPDATE civicrm_group SET cache_date = NULL");
316 }
317 else {
318 self::flushCaches();
319 }
320 }
321
322 /**
323 * Remove one or more contacts from the smart group cache.
324 *
325 * @param int|array $cid
326 * @param null $groupId
327 *
328 * @return bool
329 * TRUE if successful.
330 * @throws \CRM_Core_Exception
331 */
332 public static function removeContact($cid, $groupId = NULL) {
333 $cids = [];
334 // sanitize input
335 foreach ((array) $cid as $c) {
336 $cids[] = CRM_Utils_Type::escape($c, 'Integer');
337 }
338 if ($cids) {
339 $condition = count($cids) == 1 ? "= {$cids[0]}" : "IN (" . implode(',', $cids) . ")";
340 if ($groupId) {
341 $condition .= " AND group_id = " . CRM_Utils_Type::escape($groupId, 'Integer');
342 }
343 $sql = "DELETE FROM civicrm_group_contact_cache WHERE contact_id $condition";
344 CRM_Core_DAO::executeQuery($sql);
345 return TRUE;
346 }
347 return FALSE;
348 }
349
350 /**
351 * Load the smart group cache for a saved search.
352 *
353 * @param object $group
354 * The smart group that needs to be loaded.
355 * @param bool $force
356 * deprecated parameter = Should we force a search through.
357 *
358 * @throws \API_Exception
359 * @throws \CRM_Core_Exception
360 * @throws \CiviCRM_API3_Exception
361 */
362 public static function load($group, $force = FALSE) {
363 $groupID = (int) $group->id;
364 if ($force) {
365 CRM_Core_Error::deprecatedWarning('use invalidate group contact cache first.');
366 self::invalidateGroupContactCache($group->id);
367 }
368
369 $lockedGroups = self::getLocksForRefreshableGroupsTo([$groupID]);
370 foreach ($lockedGroups as $groupID) {
371 $groupContactsTempTable = CRM_Utils_SQL_TempTable::build()
372 ->setCategory('gccache')
373 ->setMemory();
374 self::buildGroupContactTempTable([$groupID], $groupContactsTempTable);
375 self::clearGroupContactCache([$groupID]);
376 self::updateCacheFromTempTable($groupContactsTempTable, [$groupID]);
377 self::releaseGroupLocks([$groupID]);
378 }
379 }
380
381 /**
382 * Get an array of locks for all the refreshable groups in the array.
383 *
384 * The groups are refreshable if both the following conditions are met:
385 * 1) the cache date in the database is null or stale
386 * 2) a mysql lock can be aquired for the group.
387 *
388 * @param array $groupIDs
389 *
390 * @return array
391 * @throws \CRM_Core_Exception
392 */
393 protected static function getLocksForRefreshableGroupsTo(array $groupIDs): array {
394 $locks = [];
395 $groupIDs = self::getGroupsNeedingRefreshing($groupIDs);
396 foreach ($groupIDs as $groupID) {
397 if (self::getGroupLock($groupID)) {
398 $locks[] = $groupID;
399 }
400 }
401 return $locks;
402 }
403
404 /**
405 * Retrieve the smart group cache timeout in minutes.
406 *
407 * This checks if a timeout has been configured. If one has then smart groups should not
408 * be refreshed more frequently than the time out. If a group was recently refreshed it should not
409 * refresh again within that period.
410 *
411 * @return int
412 */
413 protected static function smartGroupCacheTimeout() {
414 $config = CRM_Core_Config::singleton();
415
416 if (
417 isset($config->smartGroupCacheTimeout) &&
418 is_numeric($config->smartGroupCacheTimeout)
419 ) {
420 return $config->smartGroupCacheTimeout;
421 }
422
423 // Default to 5 minutes.
424 return 5;
425 }
426
427 /**
428 * Get all the smart groups that this contact belongs to.
429 *
430 * Note that this could potentially be a super slow function since
431 * it ensure that all contact groups are loaded in the cache
432 *
433 * @param int $contactID
434 *
435 * @return array
436 * an array of groups that this contact belongs to
437 */
438 public static function contactGroup(int $contactID): array {
439
440 self::loadAll();
441
442 $sql = "
443 SELECT gc.group_id, gc.contact_id, g.title, g.children, g.description
444 FROM civicrm_group_contact_cache gc
445 INNER JOIN civicrm_group g ON g.id = gc.group_id
446 WHERE gc.contact_id = $contactID
447 AND (g.is_hidden = 0 OR g.is_hidden IS NULL)
448 ORDER BY gc.contact_id, g.children
449 ";
450
451 $dao = CRM_Core_DAO::executeQuery($sql);
452 $contactGroup = [];
453 $prevContactID = NULL;
454 while ($dao->fetch()) {
455 if (
456 $prevContactID &&
457 $prevContactID != $dao->contact_id
458 ) {
459 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
460 }
461 $prevContactID = $dao->contact_id;
462 if (!array_key_exists($dao->contact_id, $contactGroup)) {
463 $contactGroup[$dao->contact_id]
464 = ['group' => [], 'groupTitle' => []];
465 }
466
467 $contactGroup[$dao->contact_id]['group'][]
468 = [
469 'id' => $dao->group_id,
470 'title' => $dao->title,
471 'description' => $dao->description,
472 'children' => $dao->children,
473 ];
474 $contactGroup[$dao->contact_id]['groupTitle'][] = $dao->title;
475 }
476
477 if ($prevContactID) {
478 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
479 }
480
481 if ((!empty($contactGroup[$contactID]))) {
482 return $contactGroup[$contactID];
483 }
484 return $contactGroup;
485 }
486
487 /**
488 * Get the datetime from which the cache should be considered invalid.
489 *
490 * Ie if the smartgroup cache timeout is 5 minutes ago then the cache is invalid if it was
491 * refreshed 6 minutes ago, but not if it was refreshed 4 minutes ago.
492 *
493 * @return string
494 */
495 public static function getCacheInvalidDateTime(): string {
496 return date('YmdHis', strtotime("-" . self::smartGroupCacheTimeout() . " Minutes"));
497 }
498
499 /**
500 * Invalidates the smart group cache for a particular group
501 * @param int $groupID - Group to invalidate
502 */
503 public static function invalidateGroupContactCache($groupID): void {
504 CRM_Core_DAO::executeQuery('UPDATE civicrm_group
505 SET cache_date = NULL
506 WHERE id = %1 AND (saved_search_id IS NOT NULL OR children IS NOT NULL)', [
507 1 => [$groupID, 'Positive'],
508 ]);
509 }
510
511 /**
512 * @param array $savedSearch
513 * @param int $groupID
514 *
515 * @return string
516 * @throws API_Exception
517 * @throws \Civi\API\Exception\NotImplementedException
518 * @throws CRM_Core_Exception
519 */
520 protected static function getApiSQL(array $savedSearch, int $groupID): string {
521 $excludeClause = "NOT IN (
522 SELECT contact_id FROM civicrm_group_contact
523 WHERE civicrm_group_contact.status = 'Removed'
524 AND civicrm_group_contact.group_id = $groupID )";
525 $addSelect = "$groupID AS group_id";
526
527 $apiParams = $savedSearch['api_params'] + ['select' => ['id'], 'checkPermissions' => FALSE];
528 $idField = SqlExpression::convert($apiParams['select'][0], TRUE)->getAlias();
529 // Unless there's a HAVING clause, we don't care about other columns
530 if (empty($apiParams['having'])) {
531 $apiParams['select'] = array_slice($apiParams['select'], 0, 1);
532 }
533 // Order is irrelevant unless using limit or offset
534 if (empty($apiParams['limit']) && empty($apiParams['offset'])) {
535 unset($apiParams['orderBy']);
536 }
537 /* @var $api \Civi\Api4\Generic\DAOGetAction */
538 $api = Request::create($savedSearch['api_entity'], 'get', $apiParams);
539 $query = new Api4SelectQuery($api);
540 $query->forceSelectId = FALSE;
541 $query->getQuery()->having("$idField $excludeClause");
542 $sql = $query->getSql();
543 // Place sql in a nested sub-query, otherwise HAVING is impossible on any field other than contact_id
544 return "SELECT $addSelect, `$idField` AS contact_id FROM ($sql) api_query";
545 }
546
547 /**
548 * Get sql from a custom search.
549 *
550 * We split it up and store custom class
551 * so temp tables are not destroyed if they are used
552 *
553 * @param array $savedSearch
554 * @param int $groupID
555 *
556 * @return string
557 * @throws \CRM_Core_Exception
558 * @throws \CiviCRM_API3_Exception
559 */
560 protected static function getCustomSearchSQL(array $savedSearch, int $groupID) {
561 $savedSearchID = $savedSearch['id'];
562 $excludeClause = "NOT IN (
563 SELECT contact_id FROM civicrm_group_contact
564 WHERE civicrm_group_contact.status = 'Removed'
565 AND civicrm_group_contact.group_id = $groupID )";
566 $addSelect = "$groupID AS group_id";
567 $ssParams = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
568 // CRM-7021 rectify params to what proximity search expects if there is a value for prox_distance
569 if (!empty($ssParams)) {
570 CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams);
571 }
572 $searchSQL = CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID)->contactIDs();
573 $searchSQL = str_replace('ORDER BY contact_a.id ASC', '', $searchSQL);
574 if (strpos($searchSQL, 'WHERE') === FALSE) {
575 $searchSQL .= " WHERE contact_a.id $excludeClause";
576 }
577 else {
578 $searchSQL .= " AND contact_a.id $excludeClause";
579 }
580 return preg_replace("/^\s*SELECT /", "SELECT $addSelect, ", $searchSQL);
581 }
582
583 /**
584 * Get array of sql from a saved query object group.
585 *
586 * @param array $savedSearch
587 * @param int $groupID
588 *
589 * @return string
590 * @throws \CRM_Core_Exception
591 * @throws \CiviCRM_API3_Exception
592 */
593 protected static function getQueryObjectSQL(array $savedSearch, int $groupID): string {
594 $savedSearchID = $savedSearch['id'];
595 $excludeClause = "NOT IN (
596 SELECT contact_id FROM civicrm_group_contact
597 WHERE civicrm_group_contact.status = 'Removed'
598 AND civicrm_group_contact.group_id = $groupID )";
599 $addSelect = "$groupID AS group_id";
600 $fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
601 //check if the saved search has mapping id
602 if ($savedSearch['mapping_id']) {
603 $ssParams = CRM_Core_BAO_Mapping::formattedFields($fv);
604 }
605 else {
606 $ssParams = CRM_Contact_BAO_Query::convertFormValues($fv);
607 }
608 // CRM-7021 rectify params to what proximity search expects if there is a value for prox_distance
609 if (!empty($ssParams)) {
610 CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams);
611 }
612
613 $returnProperties = NULL;
614 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) {
615 $fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
616 $returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv);
617 }
618 $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
619 // CRM-17075 using the formValues in this way imposes extra logic and complexity.
620 // we have the where_clause and where tables stored in the saved_search table
621 // and should use these rather than re-processing the form criteria (which over-works
622 // the link between the form layer & the query layer too).
623 // It's hard to think of when you would want to use anything other than return
624 // properties = array('contact_id' => 1) here as the point would appear to be to
625 // generate the list of contact ids in the group.
626 // @todo review this to use values in saved_search table (preferably for 4.8).
627 $query
628 = new CRM_Contact_BAO_Query(
629 $ssParams, $returnProperties, NULL,
630 FALSE, FALSE, 1,
631 TRUE, TRUE,
632 FALSE,
633 $formValues['display_relationship_type'] ?? NULL,
634 $formValues['operator'] ?? 'AND'
635 );
636 $query->_useDistinct = FALSE;
637 $query->_useGroupBy = FALSE;
638 $sqlParts = $query->getSearchSQLParts(
639 0, 0, NULL,
640 FALSE, FALSE,
641 FALSE, TRUE,
642 "contact_a.id $excludeClause"
643 );
644 $select = preg_replace("/^\s*SELECT /", "SELECT $addSelect, ", $sqlParts['select']);
645
646 return "$select {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['group_by']} {$sqlParts['having']}";
647 }
648
649 /**
650 * Build a temporary table for the contacts in the specified group.
651 *
652 * @param array $groupIDs
653 * Currently only one id is build but this has been written
654 * to make it easy to switch to multiple.
655 * @param CRM_Utils_SQL_TempTable $tempTableObject
656 *
657 * @throws \API_Exception
658 * @throws \CRM_Core_Exception
659 * @throws \CiviCRM_API3_Exception
660 */
661 protected static function buildGroupContactTempTable(array $groupIDs, $tempTableObject): void {
662 $groups = Group::get(FALSE)->addWhere('id', 'IN', $groupIDs)
663 ->setSelect(['saved_search_id', 'children', 'id'])->execute();
664 $tempTableName = $tempTableObject->getName();
665 $tempTableObject->createWithColumns('contact_id int, group_id int, UNIQUE UI_contact_group (contact_id,group_id)');
666 foreach ($groups as $group) {
667 self::insertGroupContactsIntoTempTable($tempTableName, $group['id'], $group['saved_search_id'], $group['children']);
668 }
669 }
670
671 /**
672 * [Internal core function] Populate a temporary table with group ids and contact ids.
673 *
674 * Do not call this outside of core tested code - it WILL change.
675 *
676 * @param array[int] $groupIDs
677 * @param string $temporaryTable
678 *
679 * @throws \API_Exception
680 * @throws \CRM_Core_Exception
681 * @throws \CiviCRM_API3_Exception
682 */
683 public static function populateTemporaryTableWithContactsInGroups(array $groupIDs, string $temporaryTable): void {
684 $childAndParentGroupIDs = array_merge($groupIDs, CRM_Contact_BAO_GroupNesting::getDescendentGroupIds($groupIDs));
685 $groups = civicrm_api3('Group', 'get', [
686 'is_active' => 1,
687 'id' => ['IN' => $childAndParentGroupIDs],
688 'saved_search_id' => ['>' => 0],
689 'return' => 'id',
690 ]);
691 $smartGroups = array_keys($groups['values']);
692
693 $query = '
694 SELECT DISTINCT group_contact.contact_id as contact_id
695 FROM civicrm_group_contact group_contact
696 WHERE group_contact.group_id IN (' . implode(', ', $childAndParentGroupIDs) . ")
697 AND group_contact.status = 'Added' ";
698
699 if (!empty($smartGroups)) {
700 $groupContactsTempTable = CRM_Utils_SQL_TempTable::build()
701 ->setCategory('gccache')
702 ->setMemory();
703 $lockedGroups = self::getLocksForRefreshableGroupsTo($smartGroups);
704 if (!empty($lockedGroups)) {
705 self::buildGroupContactTempTable($lockedGroups, $groupContactsTempTable);
706 // Note in theory we could do this transfer from the temp
707 // table to the group_contact_cache table out-of-process - possibly by
708 // continuing on after the browser is released (which seems to be
709 // possibly possible https://stackoverflow.com/questions/15273570/continue-processing-php-after-sending-http-response
710 // or by making the table durable and using a cron to process it (or an ajax call
711 // at the end to process out of the queue.
712 // if we did that we would union in DISTINCT contact_id FROM
713 // $groupContactsTempTable->getName()
714 // but still use the last union for array_diff_key($smartGroups, $locks)
715 // as that would hold the already-cached groups (if any).
716 // Also - if we switched to the 'triple union' approach described above
717 // we could throw a try-catch around this line since best-effort would
718 // be good enough & potentially improve user experience.
719 self::clearGroupContactCache($lockedGroups);
720 self::updateCacheFromTempTable($groupContactsTempTable, $lockedGroups);
721 self::releaseGroupLocks($lockedGroups);
722 }
723
724 $smartGroups = implode(',', $smartGroups);
725 $query .= "
726 UNION DISTINCT
727 SELECT smartgroup_contact.contact_id as contact_id
728 FROM civicrm_group_contact_cache smartgroup_contact
729 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
730 }
731 CRM_Core_DAO::executeQuery('INSERT INTO ' . $temporaryTable . ' ' . $query);
732 }
733
734 /**
735 * @param array|null $groupIDs
736 * @param int $limit
737 *
738 * @return array
739 */
740 protected static function getGroupsNeedingRefreshing(?array $groupIDs, int $limit = 0): array {
741 $groupIDClause = NULL;
742 // ensure that all the smart groups are loaded
743 // this function is expensive and should be sparingly used if groupIDs is empty
744 if (!empty($groupIDs)) {
745 // note escapeString is a must here and we can't send the imploded value as second argument to
746 // the executeQuery(), since that would put single quote around the string and such a string
747 // of comma separated integers would not work.
748 $groupIDString = CRM_Core_DAO::escapeString(implode(', ', $groupIDs));
749 $groupIDClause = "g.id IN ({$groupIDString})";
750 }
751
752 $query = self::groupRefreshedClause($groupIDClause, !empty($groupIDs));
753
754 $limitClause = $orderClause = NULL;
755 if ($limit > 0) {
756 $limitClause = " LIMIT 0, $limit";
757 $orderClause = " ORDER BY g.cache_date";
758 }
759 // We ignore hidden groups and disabled groups
760 $query .= "
761 $orderClause
762 $limitClause
763 ";
764
765 $dao = CRM_Core_DAO::executeQuery($query);
766 $processGroupIDs = [];
767 while ($dao->fetch()) {
768 $processGroupIDs[] = $dao->id;
769 }
770 return $processGroupIDs;
771 }
772
773 /**
774 * Transfer the contact ids to the group cache table and update the cache time.
775 *
776 * @param \CRM_Utils_SQL_TempTable $groupContactsTempTable
777 * @param array $groupIDs
778 */
779 private static function updateCacheFromTempTable(CRM_Utils_SQL_TempTable $groupContactsTempTable, array $groupIDs): void {
780 $tempTable = $groupContactsTempTable->getName();
781
782 CRM_Core_DAO::executeQuery(
783 "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)
784 SELECT DISTINCT contact_id, group_id FROM $tempTable
785 ");
786 $groupContactsTempTable->drop();
787 foreach ($groupIDs as $groupID) {
788 self::updateCacheTime([$groupID], TRUE);
789 }
790 }
791
792 /**
793 * Inserts all the contacts in the group into a temp table.
794 *
795 * This is the worker function for building the list of contacts in the
796 * group.
797 *
798 * @param string $tempTableName
799 * @param int $groupID
800 * @param int|null $savedSearchID
801 * @param string|null $children
802 *
803 * @return void
804 * @throws \API_Exception
805 * @throws \CRM_Core_Exception
806 * @throws \CiviCRM_API3_Exception
807 */
808 protected static function insertGroupContactsIntoTempTable(string $tempTableName, int $groupID, ?int $savedSearchID, ?string $children): void {
809 if ($savedSearchID) {
810 $savedSearch = SavedSearch::get(FALSE)
811 ->addWhere('id', '=', $savedSearchID)
812 ->addSelect('*')
813 ->execute()
814 ->first();
815
816 if ($savedSearch['api_entity']) {
817 $sql = self::getApiSQL($savedSearch, $groupID);
818 }
819 elseif (!empty($savedSearch['form_values']['customSearchID'])) {
820 $sql = self::getCustomSearchSQL($savedSearch, $groupID);
821 }
822 else {
823 $sql = self::getQueryObjectSQL($savedSearch, $groupID);
824 }
825 }
826
827 if (!empty($sql)) {
828 $contactQueries[] = $sql;
829 }
830 // lets also store the records that are explicitly added to the group
831 // this allows us to skip the group contact LEFT JOIN
832 $contactQueries[] =
833 "SELECT $groupID as group_id, contact_id as contact_id
834 FROM civicrm_group_contact
835 WHERE civicrm_group_contact.status = 'Added' AND civicrm_group_contact.group_id = $groupID ";
836
837 foreach ($contactQueries as $contactQuery) {
838 CRM_Core_DAO::executeQuery("INSERT IGNORE INTO $tempTableName (group_id, contact_id) {$contactQuery}");
839 }
840
841 CRM_Core_DAO::reenableFullGroupByMode();
842
843 if ($children) {
844
845 // Store a list of contacts who are removed from the parent group
846 $sqlContactsRemovedFromGroup = "
847 SELECT contact_id
848 FROM civicrm_group_contact
849 WHERE civicrm_group_contact.status = 'Removed'
850 AND civicrm_group_contact.group_id = $groupID ";
851 $dao = CRM_Core_DAO::executeQuery($sqlContactsRemovedFromGroup);
852 $removed_contacts = [];
853 while ($dao->fetch()) {
854 $removed_contacts[] = $dao->contact_id;
855 }
856
857 $childrenIDs = explode(',', $children);
858 foreach ($childrenIDs as $childID) {
859 $contactIDs = CRM_Contact_BAO_Group::getMember($childID, FALSE);
860 // Unset each contact that is removed from the parent group
861 foreach ($removed_contacts as $removed_contact) {
862 unset($contactIDs[$removed_contact]);
863 }
864 if (empty($contactIDs)) {
865 // This child group has no contact IDs so we don't need to add them to
866 continue;
867 }
868 $values = [];
869 foreach ($contactIDs as $contactID => $dontCare) {
870 $values[] = "({$groupID},{$contactID})";
871 }
872 $str = implode(',', $values);
873 CRM_Core_DAO::executeQuery("INSERT IGNORE INTO $tempTableName (group_id, contact_id) VALUES $str");
874 }
875 }
876 }
877
878 /**
879 * Get a lock, if available, for the given group.
880 *
881 * @param int $groupID
882 *
883 * @return bool
884 * @throws \CRM_Core_Exception
885 */
886 protected static function getGroupLock(int $groupID): bool {
887 $cacheKey = "data.core.group.$groupID";
888 if (isset(Civi::$statics["data.core.group.$groupID"])) {
889 // Loop avoidance for a circular parent-child situation.
890 // This would occur where the parent is a criteria of the child
891 // but needs to resolve the child to resolve itself.
892 // This has a unit test - testGroupWithParentInCriteria
893 return FALSE;
894 }
895 $lock = Civi::lockManager()->acquire($cacheKey);
896 if ($lock->isAcquired()) {
897 Civi::$statics["data.core.group.$groupID"] = $lock;
898 return TRUE;
899 }
900 return FALSE;
901 }
902
903 /**
904 * Release locks on the groups.
905 *
906 * @param array $groupIDs
907 */
908 protected static function releaseGroupLocks(array $groupIDs): void {
909 foreach ($groupIDs as $groupID) {
910 $lock = Civi::$statics["data.core.group.$groupID"];
911 $lock->release();
912 unset(Civi::$statics["data.core.group.$groupID"]);
913 }
914 }
915
916 }