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