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 * Store values into the group contact cache.
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.
165 * @param array $groupID
166 * @param array $values
168 protected static function store($groupID, &$values) {
171 // sort the values so we put group IDs in front and hence optimize
172 // mysql storage (or so we think) CRM-9493
175 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
176 while (!empty($values)) {
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);
183 self
::updateCacheTime($groupID, $processed);
187 * Change the cache_date.
189 * @param array $groupID
190 * @param bool $processed
191 * Whether the cache data was recently modified.
193 protected static function updateCacheTime($groupID, $processed) {
194 // only update cache entry if we had any values
196 // also update the group with cache date information
197 $now = date('YmdHis');
203 $groupIDs = implode(',', $groupID);
206 SET cache_date = $now
207 WHERE id IN ( $groupIDs )
209 CRM_Core_DAO
::executeQuery($sql);
213 * Function to clear group contact cache
215 * @param array $groupIDs
218 protected static function clearGroupContactCache($groupIDs): void
{
221 FROM civicrm_group_contact_cache g
222 WHERE g.group_id IN (%1) ';
224 1 => [implode(',', $groupIDs), 'CommaSeparatedIntegers'],
226 CRM_Core_DAO
::executeQuery($clearCacheQuery, $params);
230 * Refresh the smart group cache tables.
232 * This involves clearing out any aged entries (based on the site timeout setting) and resetting the time outs.
234 * This function should be called via the opportunistic or deterministic cache refresh function to make the intent
237 protected static function flushCaches() {
238 if (!CRM_Core_Config
::isPermitCacheFlushMode()) {
243 $lock = self
::getLockForRefresh();
245 catch (CRM_Core_Exception
$e) {
246 // Someone else is kindly doing the refresh for us right now.
249 $params = [1 => [self
::getCacheInvalidDateTime(), 'String']];
250 $groupsDAO = CRM_Core_DAO
::executeQuery("SELECT id FROM civicrm_group WHERE cache_date <= %1", $params);
252 while ($groupsDAO->fetch()) {
253 $expiredGroups[] = $groupsDAO->id
;
255 if (!empty($expiredGroups)) {
256 $expiredGroups = implode(',', $expiredGroups);
257 CRM_Core_DAO
::executeQuery("DELETE FROM civicrm_group_contact_cache WHERE group_id IN ({$expiredGroups})");
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})");
267 * Check if the refresh is already initiated.
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+
273 * Where these 2 locks fail we get 2 processes running at the same time, but we have at least minimised that.
275 * @return \Civi\Core\Lock\LockInterface
276 * @throws \CRM_Core_Exception
278 protected static function getLockForRefresh() {
279 if (!isset(Civi
::$statics[__CLASS__
]['is_refresh_init'])) {
280 Civi
::$statics[__CLASS__
] = ['is_refresh_init' => FALSE];
283 if (Civi
::$statics[__CLASS__
]['is_refresh_init']) {
284 throw new CRM_Core_Exception('A refresh has already run in this process');
286 $lock = Civi
::lockManager()->acquire('data.core.group.refresh');
287 if ($lock->isAcquired()) {
288 Civi
::$statics[__CLASS__
]['is_refresh_init'] = TRUE;
291 throw new CRM_Core_Exception('Mysql lock unavailable');
295 * Do an opportunistic cache refresh if the site is configured for these.
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
301 public static function opportunisticCacheFlush(): void
{
302 if (Civi
::settings()->get('smart_group_cache_refresh_mode') === 'opportunistic') {
308 * Do a forced cache refresh.
310 * This function is appropriate to be called by system jobs & non-user sessions.
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");
323 * Remove one or more contacts from the smart group cache.
325 * @param int|array $cid
326 * @param null $groupId
329 * TRUE if successful.
330 * @throws \CRM_Core_Exception
332 public static function removeContact($cid, $groupId = NULL) {
335 foreach ((array) $cid as $c) {
336 $cids[] = CRM_Utils_Type
::escape($c, 'Integer');
339 $condition = count($cids) == 1 ?
"= {$cids[0]}" : "IN (" . implode(',', $cids) . ")";
341 $condition .= " AND group_id = " . CRM_Utils_Type
::escape($groupId, 'Integer');
343 $sql = "DELETE FROM civicrm_group_contact_cache WHERE contact_id $condition";
344 CRM_Core_DAO
::executeQuery($sql);
351 * Load the smart group cache for a saved search.
353 * @param object $group
354 * The smart group that needs to be loaded.
356 * deprecated parameter = Should we force a search through.
358 * @throws \API_Exception
359 * @throws \CRM_Core_Exception
360 * @throws \CiviCRM_API3_Exception
362 public static function load($group, $force = FALSE) {
363 $groupID = (int) $group->id
;
365 CRM_Core_Error
::deprecatedWarning('use invalidate group contact cache first.');
366 self
::invalidateGroupContactCache($group->id
);
369 $lockedGroups = self
::getLocksForRefreshableGroupsTo([$groupID]);
370 foreach ($lockedGroups as $groupID) {
371 $groupContactsTempTable = CRM_Utils_SQL_TempTable
::build()
372 ->setCategory('gccache')
374 self
::buildGroupContactTempTable([$groupID], $groupContactsTempTable);
375 self
::clearGroupContactCache([$groupID]);
376 self
::updateCacheFromTempTable($groupContactsTempTable, [$groupID]);
377 self
::releaseGroupLocks([$groupID]);
382 * Get an array of locks for all the refreshable groups in the array.
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.
388 * @param array $groupIDs
391 * @throws \CRM_Core_Exception
393 protected static function getLocksForRefreshableGroupsTo(array $groupIDs): array {
395 $groupIDs = self
::getGroupsNeedingRefreshing($groupIDs);
396 foreach ($groupIDs as $groupID) {
397 if (self
::getGroupLock($groupID)) {
405 * Retrieve the smart group cache timeout in minutes.
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.
413 protected static function smartGroupCacheTimeout() {
414 $config = CRM_Core_Config
::singleton();
417 isset($config->smartGroupCacheTimeout
) &&
418 is_numeric($config->smartGroupCacheTimeout
)
420 return $config->smartGroupCacheTimeout
;
423 // Default to 5 minutes.
428 * Get all the smart groups that this contact belongs to.
430 * Note that this could potentially be a super slow function since
431 * it ensure that all contact groups are loaded in the cache
433 * @param int $contactID
436 * an array of groups that this contact belongs to
438 public static function contactGroup(int $contactID): array {
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
451 $dao = CRM_Core_DAO
::executeQuery($sql);
453 $prevContactID = NULL;
454 while ($dao->fetch()) {
457 $prevContactID != $dao->contact_id
459 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
461 $prevContactID = $dao->contact_id
;
462 if (!array_key_exists($dao->contact_id
, $contactGroup)) {
463 $contactGroup[$dao->contact_id
]
464 = ['group' => [], 'groupTitle' => []];
467 $contactGroup[$dao->contact_id
]['group'][]
469 'id' => $dao->group_id
,
470 'title' => $dao->title
,
471 'description' => $dao->description
,
472 'children' => $dao->children
,
474 $contactGroup[$dao->contact_id
]['groupTitle'][] = $dao->title
;
477 if ($prevContactID) {
478 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
481 if ((!empty($contactGroup[$contactID]))) {
482 return $contactGroup[$contactID];
484 return $contactGroup;
488 * Get the datetime from which the cache should be considered invalid.
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.
495 public static function getCacheInvalidDateTime(): string {
496 return date('YmdHis', strtotime("-" . self
::smartGroupCacheTimeout() . " Minutes"));
500 * Invalidates the smart group cache for a particular group
501 * @param int $groupID - Group to invalidate
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'],
512 * @param array $savedSearch
513 * @param int $groupID
516 * @throws API_Exception
517 * @throws \Civi\API\Exception\NotImplementedException
518 * @throws CRM_Core_Exception
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";
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);
533 // Order is irrelevant unless using limit or offset
534 if (empty($apiParams['limit']) && empty($apiParams['offset'])) {
535 unset($apiParams['orderBy']);
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";
548 * Get sql from a custom search.
550 * We split it up and store custom class
551 * so temp tables are not destroyed if they are used
553 * @param array $savedSearch
554 * @param int $groupID
557 * @throws \CRM_Core_Exception
558 * @throws \CiviCRM_API3_Exception
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);
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";
578 $searchSQL .= " AND contact_a.id $excludeClause";
580 return preg_replace("/^\s*SELECT /", "SELECT $addSelect, ", $searchSQL);
584 * Get array of sql from a saved query object group.
586 * @param array $savedSearch
587 * @param int $groupID
590 * @throws \CRM_Core_Exception
591 * @throws \CiviCRM_API3_Exception
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);
606 $ssParams = CRM_Contact_BAO_Query
::convertFormValues($fv);
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);
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);
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).
628 = new CRM_Contact_BAO_Query(
629 $ssParams, $returnProperties, NULL,
633 $formValues['display_relationship_type'] ??
NULL,
634 $formValues['operator'] ??
'AND'
636 $query->_useDistinct
= FALSE;
637 $query->_useGroupBy
= FALSE;
638 $sqlParts = $query->getSearchSQLParts(
642 "contact_a.id $excludeClause"
644 $select = preg_replace("/^\s*SELECT /", "SELECT $addSelect, ", $sqlParts['select']);
646 return "$select {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['group_by']} {$sqlParts['having']}";
650 * Build a temporary table for the contacts in the specified group.
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
657 * @throws \API_Exception
658 * @throws \CRM_Core_Exception
659 * @throws \CiviCRM_API3_Exception
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']);
672 * [Internal core function] Populate a temporary table with group ids and contact ids.
674 * Do not call this outside of core tested code - it WILL change.
676 * @param array[int] $groupIDs
677 * @param string $temporaryTable
679 * @throws \API_Exception
680 * @throws \CRM_Core_Exception
681 * @throws \CiviCRM_API3_Exception
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', [
687 'id' => ['IN' => $childAndParentGroupIDs],
688 'saved_search_id' => ['>' => 0],
691 $smartGroups = array_keys($groups['values']);
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' ";
699 if (!empty($smartGroups)) {
700 $groupContactsTempTable = CRM_Utils_SQL_TempTable
::build()
701 ->setCategory('gccache')
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);
724 $smartGroups = implode(',', $smartGroups);
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}) ";
731 CRM_Core_DAO
::executeQuery('INSERT INTO ' . $temporaryTable . ' ' . $query);
735 * @param array|null $groupIDs
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})";
752 $query = self
::groupRefreshedClause($groupIDClause, !empty($groupIDs));
754 $limitClause = $orderClause = NULL;
756 $limitClause = " LIMIT 0, $limit";
757 $orderClause = " ORDER BY g.cache_date";
759 // We ignore hidden groups and disabled groups
765 $dao = CRM_Core_DAO
::executeQuery($query);
766 $processGroupIDs = [];
767 while ($dao->fetch()) {
768 $processGroupIDs[] = $dao->id
;
770 return $processGroupIDs;
774 * Transfer the contact ids to the group cache table and update the cache time.
776 * @param \CRM_Utils_SQL_TempTable $groupContactsTempTable
777 * @param array $groupIDs
779 private static function updateCacheFromTempTable(CRM_Utils_SQL_TempTable
$groupContactsTempTable, array $groupIDs): void
{
780 $tempTable = $groupContactsTempTable->getName();
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
786 $groupContactsTempTable->drop();
787 foreach ($groupIDs as $groupID) {
788 self
::updateCacheTime([$groupID], TRUE);
793 * Inserts all the contacts in the group into a temp table.
795 * This is the worker function for building the list of contacts in the
798 * @param string $tempTableName
799 * @param int $groupID
800 * @param int|null $savedSearchID
801 * @param string|null $children
804 * @throws \API_Exception
805 * @throws \CRM_Core_Exception
806 * @throws \CiviCRM_API3_Exception
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)
816 if ($savedSearch['api_entity']) {
817 $sql = self
::getApiSQL($savedSearch, $groupID);
819 elseif (!empty($savedSearch['form_values']['customSearchID'])) {
820 $sql = self
::getCustomSearchSQL($savedSearch, $groupID);
823 $sql = self
::getQueryObjectSQL($savedSearch, $groupID);
828 $contactQueries[] = $sql;
830 // lets also store the records that are explicitly added to the group
831 // this allows us to skip the group contact LEFT JOIN
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 ";
837 foreach ($contactQueries as $contactQuery) {
838 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO $tempTableName (group_id, contact_id) {$contactQuery}");
841 CRM_Core_DAO
::reenableFullGroupByMode();
845 // Store a list of contacts who are removed from the parent group
846 $sqlContactsRemovedFromGroup = "
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
;
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]);
864 if (empty($contactIDs)) {
865 // This child group has no contact IDs so we don't need to add them to
869 foreach ($contactIDs as $contactID => $dontCare) {
870 $values[] = "({$groupID},{$contactID})";
872 $str = implode(',', $values);
873 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO $tempTableName (group_id, contact_id) VALUES $str");
879 * Get a lock, if available, for the given group.
881 * @param int $groupID
884 * @throws \CRM_Core_Exception
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
895 $lock = Civi
::lockManager()->acquire($cacheKey);
896 if ($lock->isAcquired()) {
897 Civi
::$statics["data.core.group.$groupID"] = $lock;
904 * Release locks on the groups.
906 * @param array $groupIDs
908 protected static function releaseGroupLocks(array $groupIDs): void
{
909 foreach ($groupIDs as $groupID) {
910 $lock = Civi
::$statics["data.core.group.$groupID"];
912 unset(Civi
::$statics["data.core.group.$groupID"]);