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