3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
14 use Civi\Api4\Query\Api4SelectQuery
;
15 use Civi\Api4\Query\SqlExpression
;
16 use Civi\Api4\SavedSearch
;
21 * @copyright CiviCRM LLC https://civicrm.org/licensing
23 class CRM_Contact_BAO_GroupContactCache
extends CRM_Contact_DAO_GroupContactCache
{
26 * Get a list of caching modes.
30 public static function getModes(): array {
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'),
40 * Check to see if we have cache entries for this group.
42 * If not, regenerate, else return.
44 * @param array $groupIDs
45 * Of group that we are checking against.
48 * TRUE if we did not regenerate, FALSE if we did
50 public static function check($groupIDs): bool {
51 if (empty($groupIDs)) {
55 return self
::loadAll($groupIDs);
59 * Formulate the query to see which groups needs to be refreshed.
61 * The calculation is based on their cache date and the smartGroupCacheTimeOut
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.
69 * the sql query which lists the groups that need to be refreshed
71 protected static function groupRefreshedClause($groupIDClause = NULL, $includeHiddenGroups = FALSE): string {
72 $smartGroupCacheTimeoutDateTime = self
::getCacheInvalidDateTime();
77 WHERE ( g.saved_search_id IS NOT NULL OR g.children IS NOT NULL )
81 OR cache_date <= $smartGroupCacheTimeoutDateTime
84 if (!$includeHiddenGroups) {
85 $query .= "AND (g.is_hidden = 0 OR g.is_hidden IS NULL)";
88 if (!empty($groupIDClause)) {
89 $query .= " AND ( $groupIDClause ) ";
96 * Check to see if a group has been refreshed recently.
98 * This is primarily used in a locking scenario when some other process might have refreshed things underneath
101 * @param int $groupID
106 public static function shouldGroupBeRefreshed($groupID): bool {
107 $query = self
::groupRefreshedClause('g.id = %1');
108 $params = [1 => [$groupID, 'Integer']];
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);
115 * Check to see if we have cache entries for this group.
117 * if not, regenerate, else return
119 * @param array|null $groupIDs groupIDs of group that we are checking against
120 * if empty, all groups are checked
122 * Limits the number of groups we evaluate.
125 * TRUE if we did not regenerate, FALSE if we did
127 public static function loadAll($groupIDs = NULL, $limit = 0) {
129 // Passing a single value is deprecated.
130 $groupIDs = (array) $groupIDs;
133 // Treat the default help text in Scheduled Jobs as equivalent to no limit.
134 $limit = (int) $limit;
135 $processGroupIDs = self
::getGroupsNeedingRefreshing($groupIDs, $limit);
137 if (!empty($processGroupIDs)) {
138 self
::add($processGroupIDs);
144 * Build the smart group cache for given groups.
146 * @param array $groupIDs
148 public static function add($groupIDs) {
149 $groupIDs = (array) $groupIDs;
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);
160 * Change the cache_date.
162 * @param array $groupID
163 * @param bool $processed
164 * Whether the cache data was recently modified.
166 protected static function updateCacheTime($groupID, $processed) {
167 // only update cache entry if we had any values
169 // also update the group with cache date information
170 $now = date('YmdHis');
176 $groupIDs = implode(',', $groupID);
179 SET cache_date = $now
180 WHERE id IN ( $groupIDs )
182 CRM_Core_DAO
::executeQuery($sql);
186 * Function to clear group contact cache
188 * @param array $groupIDs
191 protected static function clearGroupContactCache($groupIDs): void
{
194 FROM civicrm_group_contact_cache g
195 WHERE g.group_id IN (%1) ';
197 1 => [implode(',', $groupIDs), 'CommaSeparatedIntegers'],
199 CRM_Core_DAO
::executeQuery($clearCacheQuery, $params);
203 * Refresh the smart group cache tables.
205 * This involves clearing out any aged entries (based on the site timeout setting) and resetting the time outs.
207 * This function should be called via the opportunistic or deterministic cache refresh function to make the intent
210 protected static function flushCaches() {
211 if (!CRM_Core_Config
::isPermitCacheFlushMode()) {
216 $lock = self
::getLockForRefresh();
218 catch (CRM_Core_Exception
$e) {
219 // Someone else is kindly doing the refresh for us right now.
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);
228 while ($groupsDAO->fetch()) {
229 $expiredGroups[] = $groupsDAO->id
;
231 if (empty($expiredGroups)) {
232 // There are no expired smart groups to flush
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);
242 if ($groupsHaveEntriesToFlush) {
243 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_group_contact_cache WHERE group_id IN (%1)", [1 => [$expiredGroupsCSV, 'CommaSeparatedIntegers']]);
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']]);
253 * Check if the refresh is already initiated.
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+
259 * Where these 2 locks fail we get 2 processes running at the same time, but we have at least minimised that.
261 * @return \Civi\Core\Lock\LockInterface
262 * @throws \CRM_Core_Exception
264 protected static function getLockForRefresh() {
265 if (!isset(Civi
::$statics[__CLASS__
]['is_refresh_init'])) {
266 Civi
::$statics[__CLASS__
] = ['is_refresh_init' => FALSE];
269 if (Civi
::$statics[__CLASS__
]['is_refresh_init']) {
270 throw new CRM_Core_Exception('A refresh has already run in this process');
272 $lock = Civi
::lockManager()->acquire('data.core.group.refresh');
273 if ($lock->isAcquired()) {
274 Civi
::$statics[__CLASS__
]['is_refresh_init'] = TRUE;
277 throw new CRM_Core_Exception('Mysql lock unavailable');
281 * Do an opportunistic cache refresh if the site is configured for these.
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
287 public static function opportunisticCacheFlush(): void
{
288 if (Civi
::settings()->get('smart_group_cache_refresh_mode') === 'opportunistic') {
294 * Do a forced cache refresh.
296 * This function is appropriate to be called by system jobs & non-user sessions.
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");
309 * Remove one or more contacts from the smart group cache.
311 * @param int|array $cid
312 * @param int|null $groupId
315 * TRUE if successful.
316 * @throws \CRM_Core_Exception
318 public static function removeContact($cid, $groupId = NULL) {
321 foreach ((array) $cid as $c) {
322 $cids[] = CRM_Utils_Type
::escape($c, 'Integer');
325 $condition = count($cids) == 1 ?
"= {$cids[0]}" : "IN (" . implode(',', $cids) . ")";
327 $condition .= " AND group_id = " . CRM_Utils_Type
::escape($groupId, 'Integer');
329 $sql = "DELETE FROM civicrm_group_contact_cache WHERE contact_id $condition";
330 CRM_Core_DAO
::executeQuery($sql);
337 * Load the smart group cache for a saved search.
339 * @param object $group
340 * The smart group that needs to be loaded.
342 * deprecated parameter = Should we force a search through.
344 * @throws \API_Exception
345 * @throws \CRM_Core_Exception
346 * @throws \CiviCRM_API3_Exception
348 public static function load($group, $force = FALSE) {
349 $groupID = (int) $group->id
;
351 CRM_Core_Error
::deprecatedWarning('use invalidate group contact cache first.');
352 self
::invalidateGroupContactCache($group->id
);
355 $lockedGroups = self
::getLocksForRefreshableGroupsTo([$groupID]);
356 foreach ($lockedGroups as $groupID) {
357 $groupContactsTempTable = CRM_Utils_SQL_TempTable
::build()
358 ->setCategory('gccache')
360 self
::buildGroupContactTempTable([$groupID], $groupContactsTempTable);
361 self
::clearGroupContactCache([$groupID]);
362 self
::updateCacheFromTempTable($groupContactsTempTable, [$groupID]);
363 self
::releaseGroupLocks([$groupID]);
364 $groupContactsTempTable->drop();
369 * Get an array of locks for all the refreshable groups in the array.
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 aquired for the group.
375 * @param array $groupIDs
378 * @throws \CRM_Core_Exception
380 protected static function getLocksForRefreshableGroupsTo(array $groupIDs): array {
382 $groupIDs = self
::getGroupsNeedingRefreshing($groupIDs);
383 foreach ($groupIDs as $groupID) {
384 if (self
::getGroupLock($groupID)) {
392 * Retrieve the smart group cache timeout in minutes.
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.
400 protected static function smartGroupCacheTimeout() {
401 $config = CRM_Core_Config
::singleton();
404 isset($config->smartGroupCacheTimeout
) &&
405 is_numeric($config->smartGroupCacheTimeout
)
407 return $config->smartGroupCacheTimeout
;
410 // Default to 5 minutes.
415 * Get all the smart groups that this contact belongs to.
417 * Note that this could potentially be a super slow function since
418 * it ensure that all contact groups are loaded in the cache
420 * @param int $contactID
423 * an array of groups that this contact belongs to
425 public static function contactGroup(int $contactID): array {
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
438 $dao = CRM_Core_DAO
::executeQuery($sql);
440 $prevContactID = NULL;
441 while ($dao->fetch()) {
444 $prevContactID != $dao->contact_id
446 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
448 $prevContactID = $dao->contact_id
;
449 if (!array_key_exists($dao->contact_id
, $contactGroup)) {
450 $contactGroup[$dao->contact_id
]
451 = ['group' => [], 'groupTitle' => []];
454 $contactGroup[$dao->contact_id
]['group'][]
456 'id' => $dao->group_id
,
457 'title' => $dao->title
,
458 'description' => $dao->description
,
459 'children' => $dao->children
,
461 $contactGroup[$dao->contact_id
]['groupTitle'][] = $dao->title
;
464 if ($prevContactID) {
465 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
468 if ((!empty($contactGroup[$contactID]))) {
469 return $contactGroup[$contactID];
471 return $contactGroup;
475 * Get the datetime from which the cache should be considered invalid.
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.
482 public static function getCacheInvalidDateTime(): string {
483 return date('YmdHis', strtotime("-" . self
::smartGroupCacheTimeout() . " Minutes"));
487 * Invalidates the smart group cache for a particular group
488 * @param int $groupID - Group to invalidate
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'],
499 * @param array $savedSearch
500 * @param int $groupID
503 * @throws API_Exception
504 * @throws \Civi\API\Exception\NotImplementedException
505 * @throws CRM_Core_Exception
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";
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);
520 // Order is irrelevant unless using limit or offset
521 if (empty($apiParams['limit']) && empty($apiParams['offset'])) {
522 unset($apiParams['orderBy']);
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";
535 * Get sql from a custom search.
537 * We split it up and store custom class
538 * so temp tables are not destroyed if they are used
540 * @param array $savedSearch
541 * @param int $groupID
544 * @throws \CRM_Core_Exception
545 * @throws \CiviCRM_API3_Exception
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);
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";
565 $searchSQL .= " AND contact_a.id $excludeClause";
567 return preg_replace("/^\s*SELECT /", "SELECT $addSelect, ", $searchSQL);
571 * Get array of sql from a saved query object group.
573 * @param array $savedSearch
574 * @param int $groupID
577 * @throws \CRM_Core_Exception
578 * @throws \CiviCRM_API3_Exception
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);
593 $ssParams = CRM_Contact_BAO_Query
::convertFormValues($fv);
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);
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);
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).
615 = new CRM_Contact_BAO_Query(
616 $ssParams, $returnProperties, NULL,
620 $formValues['display_relationship_type'] ??
NULL,
621 $formValues['operator'] ??
'AND'
623 $query->_useDistinct
= FALSE;
624 $query->_useGroupBy
= FALSE;
625 $sqlParts = $query->getSearchSQLParts(
629 "contact_a.id $excludeClause"
631 $select = preg_replace("/^\s*SELECT /", "SELECT $addSelect, ", $sqlParts['select']);
633 return "$select {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['group_by']} {$sqlParts['having']}";
637 * Build a temporary table for the contacts in the specified group.
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
644 * @throws \API_Exception
645 * @throws \CRM_Core_Exception
646 * @throws \CiviCRM_API3_Exception
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']);
659 * [Internal core function] Populate a temporary table with group ids and contact ids.
661 * Do not call this outside of core tested code - it WILL change.
663 * @param array[int] $groupIDs
664 * @param string $temporaryTable
666 * @throws \API_Exception
667 * @throws \CRM_Core_Exception
668 * @throws \CiviCRM_API3_Exception
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', [
674 'id' => ['IN' => $childAndParentGroupIDs],
675 'saved_search_id' => ['>' => 0],
678 $smartGroups = array_keys($groups['values']);
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' ";
686 if (!empty($smartGroups)) {
687 $groupContactsTempTable = CRM_Utils_SQL_TempTable
::build()
688 ->setCategory('gccache')
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();
712 $smartGroups = implode(',', $smartGroups);
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}) ";
719 CRM_Core_DAO
::executeQuery('INSERT INTO ' . $temporaryTable . ' ' . $query);
723 * @param array|null $groupIDs
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})";
740 $query = self
::groupRefreshedClause($groupIDClause, !empty($groupIDs));
742 $limitClause = $orderClause = NULL;
744 $limitClause = " LIMIT 0, $limit";
745 $orderClause = " ORDER BY g.cache_date";
747 // We ignore hidden groups and disabled groups
753 $dao = CRM_Core_DAO
::executeQuery($query);
754 $processGroupIDs = [];
755 while ($dao->fetch()) {
756 $processGroupIDs[] = $dao->id
;
758 return $processGroupIDs;
762 * Transfer the contact ids to the group cache table and update the cache time.
764 * @param \CRM_Utils_SQL_TempTable $groupContactsTempTable
765 * @param array $groupIDs
767 private static function updateCacheFromTempTable(CRM_Utils_SQL_TempTable
$groupContactsTempTable, array $groupIDs): void
{
768 $tempTable = $groupContactsTempTable->getName();
770 CRM_Core_DAO
::executeQuery(
771 "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)
772 SELECT DISTINCT contact_id, group_id FROM $tempTable
774 foreach ($groupIDs as $groupID) {
775 self
::updateCacheTime([$groupID], TRUE);
780 * Inserts all the contacts in the group into a temp table.
782 * This is the worker function for building the list of contacts in the
785 * @param string $tempTableName
786 * @param int $groupID
787 * @param int|null $savedSearchID
788 * @param string|null $children
791 * @throws \API_Exception
792 * @throws \CRM_Core_Exception
793 * @throws \CiviCRM_API3_Exception
795 protected static function insertGroupContactsIntoTempTable(string $tempTableName, int $groupID, ?
int $savedSearchID, ?
string $children): void
{
796 if ($savedSearchID) {
797 $savedSearch = SavedSearch
::get(FALSE)
798 ->addWhere('id', '=', $savedSearchID)
803 if ($savedSearch['api_entity']) {
804 $sql = self
::getApiSQL($savedSearch, $groupID);
806 elseif (!empty($savedSearch['search_custom_id'])) {
807 $sql = self
::getCustomSearchSQL($savedSearch, $groupID);
810 $sql = self
::getQueryObjectSQL($savedSearch, $groupID);
815 $contactQueries[] = $sql;
817 // lets also store the records that are explicitly added to the group
818 // this allows us to skip the group contact LEFT JOIN
820 "SELECT $groupID as group_id, contact_id as contact_id
821 FROM civicrm_group_contact
822 WHERE civicrm_group_contact.status = 'Added' AND civicrm_group_contact.group_id = $groupID ";
824 foreach ($contactQueries as $contactQuery) {
825 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO $tempTableName (group_id, contact_id) {$contactQuery}");
828 CRM_Core_DAO
::reenableFullGroupByMode();
832 // Store a list of contacts who are removed from the parent group
833 $sqlContactsRemovedFromGroup = "
835 FROM civicrm_group_contact
836 WHERE civicrm_group_contact.status = 'Removed'
837 AND civicrm_group_contact.group_id = $groupID ";
838 $dao = CRM_Core_DAO
::executeQuery($sqlContactsRemovedFromGroup);
839 $removed_contacts = [];
840 while ($dao->fetch()) {
841 $removed_contacts[] = $dao->contact_id
;
844 $childrenIDs = explode(',', $children);
845 foreach ($childrenIDs as $childID) {
846 $contactIDs = CRM_Contact_BAO_Group
::getMember($childID, FALSE);
847 // Unset each contact that is removed from the parent group
848 foreach ($removed_contacts as $removed_contact) {
849 unset($contactIDs[$removed_contact]);
851 if (empty($contactIDs)) {
852 // This child group has no contact IDs so we don't need to add them to
856 foreach ($contactIDs as $contactID => $dontCare) {
857 $values[] = "({$groupID},{$contactID})";
859 $str = implode(',', $values);
860 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO $tempTableName (group_id, contact_id) VALUES $str");
866 * Get a lock, if available, for the given group.
868 * @param int $groupID
871 * @throws \CRM_Core_Exception
873 protected static function getGroupLock(int $groupID): bool {
874 $cacheKey = "data.core.group.$groupID";
875 if (isset(Civi
::$statics["data.core.group.$groupID"])) {
876 // Loop avoidance for a circular parent-child situation.
877 // This would occur where the parent is a criteria of the child
878 // but needs to resolve the child to resolve itself.
879 // This has a unit test - testGroupWithParentInCriteria
882 $lock = Civi
::lockManager()->acquire($cacheKey);
883 if ($lock->isAcquired()) {
884 Civi
::$statics["data.core.group.$groupID"] = $lock;
891 * Release locks on the groups.
893 * @param array $groupIDs
895 protected static function releaseGroupLocks(array $groupIDs): void
{
896 foreach ($groupIDs as $groupID) {
897 $lock = Civi
::$statics["data.core.group.$groupID"];
899 unset(Civi
::$statics["data.core.group.$groupID"]);