Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
fee14197 | 4 | | CiviCRM version 5 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
6b83d5bd | 6 | | Copyright CiviCRM LLC (c) 2004-2019 | |
6a488035 TO |
7 | +--------------------------------------------------------------------+ |
8 | | This file is a part of CiviCRM. | | |
9 | | | | |
10 | | CiviCRM is free software; you can copy, modify, and distribute it | | |
11 | | under the terms of the GNU Affero General Public License | | |
12 | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | |
13 | | | | |
14 | | CiviCRM is distributed in the hope that it will be useful, but | | |
15 | | WITHOUT ANY WARRANTY; without even the implied warranty of | | |
16 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | |
17 | | See the GNU Affero General Public License for more details. | | |
18 | | | | |
19 | | You should have received a copy of the GNU Affero General Public | | |
20 | | License and the CiviCRM Licensing Exception along | | |
21 | | with this program; if not, contact CiviCRM LLC | | |
22 | | at info[AT]civicrm[DOT]org. If you have questions about the | | |
23 | | GNU Affero General Public License or the licensing of CiviCRM, | | |
24 | | see the CiviCRM license FAQ at http://civicrm.org/licensing | | |
25 | +--------------------------------------------------------------------+ | |
d25dd0ee | 26 | */ |
6a488035 TO |
27 | |
28 | /** | |
29 | * | |
30 | * @package CRM | |
6b83d5bd | 31 | * @copyright CiviCRM LLC (c) 2004-2019 |
6a488035 TO |
32 | */ |
33 | class CRM_Contact_BAO_GroupContactCache extends CRM_Contact_DAO_GroupContactCache { | |
34 | ||
69078420 | 35 | public static $_alreadyLoaded = []; |
6a488035 | 36 | |
a8eb1fe6 TO |
37 | /** |
38 | * Get a list of caching modes. | |
39 | * | |
40 | * @return array | |
41 | */ | |
42 | public static function getModes() { | |
be2fb01f | 43 | return [ |
a8eb1fe6 TO |
44 | // Flush expired caches in response to user actions. |
45 | 'opportunistic' => ts('Opportunistic Flush'), | |
46 | ||
47 | // Flush expired caches via background cron jobs. | |
48 | 'deterministic' => ts('Cron Flush'), | |
be2fb01f | 49 | ]; |
a8eb1fe6 TO |
50 | } |
51 | ||
6a488035 | 52 | /** |
67d19299 | 53 | * Check to see if we have cache entries for this group. |
54 | * | |
55 | * If not, regenerate, else return. | |
6a488035 | 56 | * |
adf28ffd | 57 | * @param array $groupIDs |
77c5b619 | 58 | * Of group that we are checking against. |
6a488035 | 59 | * |
5396af74 | 60 | * @return bool |
a6c01b45 | 61 | * TRUE if we did not regenerate, FALSE if we did |
6a488035 | 62 | */ |
00be9182 | 63 | public static function check($groupIDs) { |
6a488035 TO |
64 | if (empty($groupIDs)) { |
65 | return TRUE; | |
66 | } | |
67 | ||
68 | return self::loadAll($groupIDs); | |
69 | } | |
70 | ||
abdb2607 | 71 | /** |
adf28ffd | 72 | * Formulate the query to see which groups needs to be refreshed. |
73 | * | |
74 | * The calculation is based on their cache date and the smartGroupCacheTimeOut | |
abdb2607 | 75 | * |
77c5b619 TO |
76 | * @param string $groupIDClause |
77 | * The clause which limits which groups we need to evaluate. | |
78 | * @param bool $includeHiddenGroups | |
79 | * Hidden groups are excluded by default. | |
abdb2607 | 80 | * |
a6c01b45 CW |
81 | * @return string |
82 | * the sql query which lists the groups that need to be refreshed | |
abdb2607 | 83 | */ |
e60f24eb | 84 | public static function groupRefreshedClause($groupIDClause = NULL, $includeHiddenGroups = FALSE) { |
4052239b | 85 | $smartGroupCacheTimeoutDateTime = self::getCacheInvalidDateTime(); |
abdb2607 DL |
86 | |
87 | $query = " | |
88 | SELECT g.id | |
89 | FROM civicrm_group g | |
90 | WHERE ( g.saved_search_id IS NOT NULL OR g.children IS NOT NULL ) | |
91 | AND g.is_active = 1 | |
4052239b | 92 | AND ( |
93 | g.cache_date IS NULL | |
94 | OR cache_date <= $smartGroupCacheTimeoutDateTime | |
95 | OR NOW() >= g.refresh_date | |
96 | )"; | |
abdb2607 DL |
97 | |
98 | if (!$includeHiddenGroups) { | |
99 | $query .= "AND (g.is_hidden = 0 OR g.is_hidden IS NULL)"; | |
100 | } | |
101 | ||
102 | if (!empty($groupIDClause)) { | |
103 | $query .= " AND ( $groupIDClause ) "; | |
104 | } | |
105 | ||
106 | return $query; | |
107 | } | |
108 | ||
109 | /** | |
adf28ffd | 110 | * Check to see if a group has been refreshed recently. |
111 | * | |
112 | * This is primarily used in a locking scenario when some other process might have refreshed things underneath | |
abdb2607 DL |
113 | * this process |
114 | * | |
77c5b619 TO |
115 | * @param int $groupID |
116 | * The group ID. | |
117 | * @param bool $includeHiddenGroups | |
118 | * Hidden groups are excluded by default. | |
abdb2607 | 119 | * |
a6c01b45 CW |
120 | * @return string |
121 | * the sql query which lists the groups that need to be refreshed | |
abdb2607 | 122 | */ |
00be9182 | 123 | public static function shouldGroupBeRefreshed($groupID, $includeHiddenGroups = FALSE) { |
abdb2607 | 124 | $query = self::groupRefreshedClause("g.id = %1", $includeHiddenGroups); |
be2fb01f | 125 | $params = [1 => [$groupID, 'Integer']]; |
abdb2607 | 126 | |
4f53db5a | 127 | // if the query returns the group ID, it means the group is a valid candidate for refreshing |
abdb2607 DL |
128 | return CRM_Core_DAO::singleValueQuery($query, $params); |
129 | } | |
130 | ||
6a488035 | 131 | /** |
adf28ffd | 132 | * Check to see if we have cache entries for this group. |
133 | * | |
6a488035 TO |
134 | * if not, regenerate, else return |
135 | * | |
adf28ffd | 136 | * @param int|array $groupIDs groupIDs of group that we are checking against |
6a488035 | 137 | * if empty, all groups are checked |
77c5b619 TO |
138 | * @param int $limit |
139 | * Limits the number of groups we evaluate. | |
6a488035 | 140 | * |
5396af74 | 141 | * @return bool |
a6c01b45 | 142 | * TRUE if we did not regenerate, FALSE if we did |
6a488035 | 143 | */ |
e60f24eb | 144 | public static function loadAll($groupIDs = NULL, $limit = 0) { |
6a488035 TO |
145 | // ensure that all the smart groups are loaded |
146 | // this function is expensive and should be sparingly used if groupIDs is empty | |
6a488035 | 147 | if (empty($groupIDs)) { |
e60f24eb | 148 | $groupIDClause = NULL; |
be2fb01f | 149 | $groupIDs = []; |
6a488035 TO |
150 | } |
151 | else { | |
152 | if (!is_array($groupIDs)) { | |
be2fb01f | 153 | $groupIDs = [$groupIDs]; |
6a488035 TO |
154 | } |
155 | ||
b44e3f84 | 156 | // note escapeString is a must here and we can't send the imploded value as second argument to |
6a488035 TO |
157 | // the executeQuery(), since that would put single quote around the string and such a string |
158 | // of comma separated integers would not work. | |
0e4e5a49 | 159 | $groupIDString = CRM_Core_DAO::escapeString(implode(', ', $groupIDs)); |
6a488035 | 160 | |
abdb2607 | 161 | $groupIDClause = "g.id IN ({$groupIDString})"; |
6a488035 TO |
162 | } |
163 | ||
abdb2607 | 164 | $query = self::groupRefreshedClause($groupIDClause); |
6a488035 TO |
165 | |
166 | $limitClause = $orderClause = NULL; | |
167 | if ($limit > 0) { | |
168 | $limitClause = " LIMIT 0, $limit"; | |
169 | $orderClause = " ORDER BY g.cache_date, g.refresh_date"; | |
170 | } | |
e2422b8f | 171 | // We ignore hidden groups and disabled groups |
abdb2607 | 172 | $query .= " |
6a488035 | 173 | $orderClause |
f9e16e9a | 174 | $limitClause |
6a488035 TO |
175 | "; |
176 | ||
177 | $dao = CRM_Core_DAO::executeQuery($query); | |
be2fb01f | 178 | $processGroupIDs = []; |
6a488035 TO |
179 | $refreshGroupIDs = $groupIDs; |
180 | while ($dao->fetch()) { | |
181 | $processGroupIDs[] = $dao->id; | |
182 | ||
183 | // remove this id from refreshGroupIDs | |
184 | foreach ($refreshGroupIDs as $idx => $gid) { | |
185 | if ($gid == $dao->id) { | |
186 | unset($refreshGroupIDs[$idx]); | |
187 | break; | |
188 | } | |
189 | } | |
190 | } | |
191 | ||
192 | if (!empty($refreshGroupIDs)) { | |
82a837e9 | 193 | $refreshGroupIDString = CRM_Core_DAO::escapeString(implode(', ', $refreshGroupIDs)); |
a986056d | 194 | $time = self::getRefreshDateTime(); |
6a488035 TO |
195 | $query = " |
196 | UPDATE civicrm_group g | |
197 | SET g.refresh_date = $time | |
198 | WHERE g.id IN ( {$refreshGroupIDString} ) | |
199 | AND g.refresh_date IS NULL | |
200 | "; | |
82a837e9 | 201 | CRM_Core_DAO::executeQuery($query); |
6a488035 TO |
202 | } |
203 | ||
204 | if (empty($processGroupIDs)) { | |
205 | return TRUE; | |
206 | } | |
207 | else { | |
208 | self::add($processGroupIDs); | |
209 | return FALSE; | |
210 | } | |
211 | } | |
212 | ||
86538308 | 213 | /** |
6b05374e | 214 | * Build the smart group cache for given groups. |
adf28ffd | 215 | * |
6b05374e | 216 | * @param array $groupIDs |
86538308 | 217 | */ |
6b05374e | 218 | public static function add($groupIDs) { |
219 | $groupIDs = (array) $groupIDs; | |
6a488035 | 220 | |
6b05374e | 221 | foreach ($groupIDs as $groupID) { |
222 | // first delete the current cache | |
223 | self::clearGroupContactCache($groupID); | |
be2fb01f | 224 | $params = [['group', 'IN', [$groupID], 0, 0]]; |
abdb2607 | 225 | // the below call updates the cache table as a byproduct of the query |
be2fb01f | 226 | CRM_Contact_BAO_Query::apiQuery($params, ['contact_id'], NULL, NULL, 0, 0, FALSE); |
6a488035 TO |
227 | } |
228 | } | |
229 | ||
86538308 | 230 | /** |
adf28ffd | 231 | * Store values into the group contact cache. |
232 | * | |
233 | * @todo review use of INSERT IGNORE. This function appears to be slower that inserting | |
234 | * with a left join. Also, 200 at once seems too little. | |
235 | * | |
6b05374e | 236 | * @param array $groupID |
adf28ffd | 237 | * @param array $values |
86538308 | 238 | */ |
6b05374e | 239 | public static function store($groupID, &$values) { |
6a488035 TO |
240 | $processed = FALSE; |
241 | ||
242 | // sort the values so we put group IDs in front and hence optimize | |
243 | // mysql storage (or so we think) CRM-9493 | |
244 | sort($values); | |
eb917190 | 245 | |
6a488035 TO |
246 | // to avoid long strings, lets do BULK_INSERT_COUNT values at a time |
247 | while (!empty($values)) { | |
248 | $processed = TRUE; | |
353ffa53 TO |
249 | $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT); |
250 | $str = implode(',', $input); | |
251 | $sql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) VALUES $str;"; | |
6a488035 TO |
252 | CRM_Core_DAO::executeQuery($sql); |
253 | } | |
254 | self::updateCacheTime($groupID, $processed); | |
255 | } | |
256 | ||
257 | /** | |
fe482240 | 258 | * Change the cache_date. |
6a488035 | 259 | * |
5a4f6742 CW |
260 | * @param array $groupID |
261 | * @param bool $processed | |
262 | * Whether the cache data was recently modified. | |
6a488035 | 263 | */ |
00be9182 | 264 | public static function updateCacheTime($groupID, $processed) { |
6a488035 TO |
265 | // only update cache entry if we had any values |
266 | if ($processed) { | |
267 | // also update the group with cache date information | |
a986056d | 268 | $now = date('YmdHis'); |
6a488035 TO |
269 | $refresh = 'null'; |
270 | } | |
271 | else { | |
353ffa53 | 272 | $now = 'null'; |
6a488035 TO |
273 | $refresh = 'null'; |
274 | } | |
275 | ||
276 | $groupIDs = implode(',', $groupID); | |
277 | $sql = " | |
278 | UPDATE civicrm_group | |
279 | SET cache_date = $now, refresh_date = $refresh | |
280 | WHERE id IN ( $groupIDs ) | |
281 | "; | |
282 | CRM_Core_DAO::executeQuery($sql); | |
283 | } | |
284 | ||
cee4f6a1 | 285 | /** |
6b05374e | 286 | * @deprecated function - the best function to call is |
287 | * CRM_Contact_BAO_Contact::updateContactCache at the moment, or api job.group_cache_flush | |
288 | * to really force a flush. | |
cee4f6a1 | 289 | * |
6b05374e | 290 | * Remove this function altogether by mid 2018. |
cc7b1cd9 | 291 | * |
6b05374e | 292 | * However, if updating code outside core to use this (or any BAO function) it is recommended that |
293 | * you add an api call to lock in into our contract. Currently there is not really a supported | |
294 | * method for non core functions. | |
cee4f6a1 | 295 | */ |
6b05374e | 296 | public static function remove() { |
297 | Civi::log() | |
be2fb01f | 298 | ->warning('Deprecated code. This function should not be called without groupIDs. Extensions can use the api job.group_cache_flush for a hard flush or add an api option for soft flush', ['civi.tag' => 'deprecated']); |
6b05374e | 299 | CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush(); |
4ebc8d27 | 300 | } |
6a488035 | 301 | |
4ebc8d27 | 302 | /** |
303 | * Function to clear group contact cache and reset the corresponding | |
304 | * group's cache and refresh date | |
305 | * | |
ffb47ce2 | 306 | * @param int $groupID |
4ebc8d27 | 307 | * |
308 | */ | |
309 | public static function clearGroupContactCache($groupID) { | |
310 | $transaction = new CRM_Core_Transaction(); | |
311 | $query = " | |
312 | DELETE g | |
313 | FROM civicrm_group_contact_cache g | |
314 | WHERE g.group_id = %1 "; | |
6a488035 | 315 | |
4ebc8d27 | 316 | $update = " |
317 | UPDATE civicrm_group g | |
318 | SET cache_date = null, refresh_date = null | |
319 | WHERE id = %1 "; | |
320 | ||
be2fb01f CW |
321 | $params = [ |
322 | 1 => [$groupID, 'Integer'], | |
323 | ]; | |
6a488035 | 324 | |
4ebc8d27 | 325 | CRM_Core_DAO::executeQuery($query, $params); |
6a488035 TO |
326 | // also update the cache_date for these groups |
327 | CRM_Core_DAO::executeQuery($update, $params); | |
6b05374e | 328 | unset(self::$_alreadyLoaded[$groupID]); |
4ebc8d27 | 329 | |
330 | $transaction->commit(); | |
6a488035 TO |
331 | } |
332 | ||
801bafd7 | 333 | /** |
334 | * Refresh the smart group cache tables. | |
335 | * | |
336 | * This involves clearing out any aged entries (based on the site timeout setting) and resetting the time outs. | |
337 | * | |
338 | * This function should be called via the opportunistic or deterministic cache refresh function to make the intent | |
339 | * clear. | |
340 | */ | |
2b68a50c | 341 | protected static function flushCaches() { |
cc7b1cd9 | 342 | try { |
343 | $lock = self::getLockForRefresh(); | |
344 | } | |
345 | catch (CRM_Core_Exception $e) { | |
346 | // Someone else is kindly doing the refresh for us right now. | |
801bafd7 | 347 | return; |
348 | } | |
be2fb01f | 349 | $params = [1 => [self::getCacheInvalidDateTime(), 'String']]; |
cc7b1cd9 | 350 | // @todo this is consistent with previous behaviour but as the first query could take several seconds the second |
351 | // could become inaccurate. It seems to make more sense to fetch them first & delete from an array (which would | |
352 | // also reduce joins). If we do this we should also consider how best to iterate the groups. If we do them one at | |
353 | // a time we could call a hook, allowing people to manage the frequency on their groups, or possibly custom searches | |
354 | // might do that too. However, for 2000 groups that's 2000 iterations. If we do all once we potentially create a | |
355 | // slow query. It's worth noting the speed issue generally relates to the size of the group but if one slow group | |
356 | // is in a query with 500 fast ones all 500 get locked. One approach might be to calculate group size or the | |
357 | // number of groups & then process all at once or many query runs depending on what is found. Of course those | |
358 | // preliminary queries would need speed testing. | |
801bafd7 | 359 | CRM_Core_DAO::executeQuery( |
360 | " | |
361 | DELETE gc | |
362 | FROM civicrm_group_contact_cache gc | |
363 | INNER JOIN civicrm_group g ON g.id = gc.group_id | |
364 | WHERE g.cache_date <= %1 | |
365 | ", | |
366 | $params | |
367 | ); | |
368 | ||
cc7b1cd9 | 369 | // Clear these out without resetting them because we are not building caches here, only clearing them, |
370 | // so the state is 'as if they had never been built'. | |
801bafd7 | 371 | CRM_Core_DAO::executeQuery( |
372 | " | |
373 | UPDATE civicrm_group g | |
cc7b1cd9 | 374 | SET cache_date = NULL, |
375 | refresh_date = NULL | |
801bafd7 | 376 | WHERE g.cache_date <= %1 |
377 | ", | |
378 | $params | |
379 | ); | |
cc7b1cd9 | 380 | $lock->release(); |
801bafd7 | 381 | } |
382 | ||
383 | /** | |
384 | * Check if the refresh is already initiated. | |
385 | * | |
386 | * We have 2 imperfect methods for this: | |
387 | * 1) a static variable in the function. This works fine within a request | |
388 | * 2) a mysql lock. This works fine as long as CiviMail is not running, or if mysql is version 5.7+ | |
389 | * | |
390 | * Where these 2 locks fail we get 2 processes running at the same time, but we have at least minimised that. | |
cc7b1cd9 | 391 | * |
392 | * @return \Civi\Core\Lock\LockInterface | |
393 | * @throws \CRM_Core_Exception | |
801bafd7 | 394 | */ |
cc7b1cd9 | 395 | protected static function getLockForRefresh() { |
0626851e | 396 | if (!isset(Civi::$statics[__CLASS__]['is_refresh_init'])) { |
be2fb01f | 397 | Civi::$statics[__CLASS__] = ['is_refresh_init' => FALSE]; |
cc7b1cd9 | 398 | } |
399 | ||
400 | if (Civi::$statics[__CLASS__]['is_refresh_init']) { | |
401 | throw new CRM_Core_Exception('A refresh has already run in this process'); | |
801bafd7 | 402 | } |
403 | $lock = Civi::lockManager()->acquire('data.core.group.refresh'); | |
cc7b1cd9 | 404 | if ($lock->isAcquired()) { |
405 | Civi::$statics[__CLASS__]['is_refresh_init'] = TRUE; | |
406 | return $lock; | |
801bafd7 | 407 | } |
cc7b1cd9 | 408 | throw new CRM_Core_Exception('Mysql lock unavailable'); |
801bafd7 | 409 | } |
410 | ||
411 | /** | |
412 | * Do an opportunistic cache refresh if the site is configured for these. | |
413 | * | |
e047612e CB |
414 | * Sites that do not run the smart group clearing cron job should refresh the |
415 | * caches on demand. The user session will be forced to wait so it is less | |
416 | * ideal. | |
801bafd7 | 417 | */ |
2b68a50c | 418 | public static function opportunisticCacheFlush() { |
cc7b1cd9 | 419 | if (Civi::settings()->get('smart_group_cache_refresh_mode') == 'opportunistic') { |
2b68a50c | 420 | self::flushCaches(); |
801bafd7 | 421 | } |
422 | } | |
423 | ||
424 | /** | |
425 | * Do a forced cache refresh. | |
426 | * | |
427 | * This function is appropriate to be called by system jobs & non-user sessions. | |
801bafd7 | 428 | */ |
2b68a50c | 429 | public static function deterministicCacheFlush() { |
801bafd7 | 430 | if (self::smartGroupCacheTimeout() == 0) { |
431 | CRM_Core_DAO::executeQuery("TRUNCATE civicrm_group_contact_cache"); | |
432 | CRM_Core_DAO::executeQuery(" | |
433 | UPDATE civicrm_group g | |
434 | SET cache_date = null, refresh_date = null"); | |
435 | } | |
436 | else { | |
2b68a50c | 437 | self::flushCaches(); |
801bafd7 | 438 | } |
439 | } | |
440 | ||
2c6bbd06 | 441 | /** |
adf28ffd | 442 | * Remove one or more contacts from the smart group cache. |
443 | * | |
2c6bbd06 CW |
444 | * @param int|array $cid |
445 | * @param int $groupId | |
adf28ffd | 446 | * |
4eeb9a5b TO |
447 | * @return bool |
448 | * TRUE if successful. | |
2c6bbd06 | 449 | */ |
00be9182 | 450 | public static function removeContact($cid, $groupId = NULL) { |
be2fb01f | 451 | $cids = []; |
2c6bbd06 CW |
452 | // sanitize input |
453 | foreach ((array) $cid as $c) { | |
454 | $cids[] = CRM_Utils_Type::escape($c, 'Integer'); | |
455 | } | |
456 | if ($cids) { | |
457 | $condition = count($cids) == 1 ? "= {$cids[0]}" : "IN (" . implode(',', $cids) . ")"; | |
458 | if ($groupId) { | |
459 | $condition .= " AND group_id = " . CRM_Utils_Type::escape($groupId, 'Integer'); | |
460 | } | |
461 | $sql = "DELETE FROM civicrm_group_contact_cache WHERE contact_id $condition"; | |
462 | CRM_Core_DAO::executeQuery($sql); | |
463 | return TRUE; | |
464 | } | |
465 | return FALSE; | |
466 | } | |
467 | ||
6a488035 | 468 | /** |
fe482240 | 469 | * Load the smart group cache for a saved search. |
abdb2607 | 470 | * |
77c5b619 TO |
471 | * @param object $group |
472 | * The smart group that needs to be loaded. | |
473 | * @param bool $force | |
474 | * Should we force a search through. | |
6a488035 | 475 | */ |
00be9182 | 476 | public static function load(&$group, $force = FALSE) { |
6a488035 TO |
477 | $groupID = $group->id; |
478 | $savedSearchID = $group->saved_search_id; | |
abdb2607 | 479 | if (array_key_exists($groupID, self::$_alreadyLoaded) && !$force) { |
6a488035 TO |
480 | return; |
481 | } | |
cc13551d | 482 | |
4052239b | 483 | // grab a lock so other processes don't compete and do the same query |
83617886 | 484 | $lock = Civi::lockManager()->acquire("data.core.group.{$groupID}"); |
cc13551d | 485 | if (!$lock->isAcquired()) { |
4052239b | 486 | // this can cause inconsistent results since we don't know if the other process |
cc13551d DL |
487 | // will fill up the cache before our calling routine needs it. |
488 | // however this routine does not return the status either, so basically | |
489 | // its a "lets return and hope for the best" | |
490 | return; | |
491 | } | |
492 | ||
6a488035 | 493 | self::$_alreadyLoaded[$groupID] = 1; |
abdb2607 | 494 | |
b44e3f84 | 495 | // we now have the lock, but some other process could have actually done the work |
abdb2607 DL |
496 | // before we got here, so before we do any work, lets ensure that work needs to be |
497 | // done | |
498 | // we allow hidden groups here since we dont know if the caller wants to evaluate an | |
499 | // hidden group | |
3cd86345 | 500 | if (!$force && !self::shouldGroupBeRefreshed($groupID, TRUE)) { |
abdb2607 DL |
501 | $lock->release(); |
502 | return; | |
503 | } | |
504 | ||
353ffa53 TO |
505 | $sql = NULL; |
506 | $idName = 'id'; | |
6a488035 TO |
507 | $customClass = NULL; |
508 | if ($savedSearchID) { | |
509 | $ssParams = CRM_Contact_BAO_SavedSearch::getSearchParams($savedSearchID); | |
510 | ||
511 | // rectify params to what proximity search expects if there is a value for prox_distance | |
512 | // CRM-7021 | |
513 | if (!empty($ssParams)) { | |
514 | CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams); | |
515 | } | |
516 | ||
be2fb01f | 517 | $returnProperties = []; |
6a488035 TO |
518 | if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) { |
519 | $fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID); | |
520 | $returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv); | |
521 | } | |
522 | ||
523 | if (isset($ssParams['customSearchID'])) { | |
524 | // if custom search | |
525 | ||
526 | // we split it up and store custom class | |
527 | // so temp tables are not destroyed if they are used | |
528 | // hence customClass is defined above at top of function | |
5396af74 | 529 | $customClass = CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID); |
6a488035 | 530 | $searchSQL = $customClass->contactIDs(); |
26a9b6ab | 531 | $searchSQL = str_replace('ORDER BY contact_a.id ASC', '', $searchSQL); |
d02c030f | 532 | if (!strstr($searchSQL, 'WHERE')) { |
533 | $searchSQL .= " WHERE ( 1 ) "; | |
534 | } | |
6a488035 TO |
535 | $idName = 'contact_id'; |
536 | } | |
537 | else { | |
538 | $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID); | |
beccb90f | 539 | // CRM-17075 using the formValues in this way imposes extra logic and complexity. |
540 | // we have the where_clause and where tables stored in the saved_search table | |
541 | // and should use these rather than re-processing the form criteria (which over-works | |
542 | // the link between the form layer & the query layer too). | |
543 | // It's hard to think of when you would want to use anything other than return | |
544 | // properties = array('contact_id' => 1) here as the point would appear to be to | |
545 | // generate the list of contact ids in the group. | |
546 | // @todo review this to use values in saved_search table (preferably for 4.8). | |
5396af74 | 547 | $query |
548 | = new CRM_Contact_BAO_Query( | |
6a488035 | 549 | $ssParams, $returnProperties, NULL, |
cc13551d DL |
550 | FALSE, FALSE, 1, |
551 | TRUE, TRUE, | |
552 | FALSE, | |
6a488035 TO |
553 | CRM_Utils_Array::value('display_relationship_type', $formValues), |
554 | CRM_Utils_Array::value('operator', $formValues, 'AND') | |
353ffa53 | 555 | ); |
6a488035 | 556 | $query->_useDistinct = FALSE; |
353ffa53 | 557 | $query->_useGroupBy = FALSE; |
0e7133be | 558 | $sqlParts = $query->getSearchSQLParts( |
6a488035 | 559 | 0, 0, NULL, |
353ffa53 | 560 | FALSE, FALSE, |
0e7133be | 561 | FALSE, TRUE |
353ffa53 | 562 | ); |
0e7133be | 563 | $searchSQL = "{$sqlParts['select']} {$sqlParts['from']} {$sqlParts['where']} {$sqlParts['having']} {$sqlParts['group_by']}"; |
6a488035 TO |
564 | } |
565 | $groupID = CRM_Utils_Type::escape($groupID, 'Integer'); | |
566 | $sql = $searchSQL . " AND contact_a.id NOT IN ( | |
567 | SELECT contact_id FROM civicrm_group_contact | |
568 | WHERE civicrm_group_contact.status = 'Removed' | |
569 | AND civicrm_group_contact.group_id = $groupID ) "; | |
570 | } | |
571 | ||
572 | if ($sql) { | |
573 | $sql = preg_replace("/^\s*SELECT/", "SELECT $groupID as group_id, ", $sql); | |
574 | } | |
575 | ||
576 | // lets also store the records that are explicitly added to the group | |
577 | // this allows us to skip the group contact LEFT JOIN | |
578 | $sqlB = " | |
579 | SELECT $groupID as group_id, contact_id as $idName | |
580 | FROM civicrm_group_contact | |
581 | WHERE civicrm_group_contact.status = 'Added' | |
582 | AND civicrm_group_contact.group_id = $groupID "; | |
583 | ||
6b05374e | 584 | self::clearGroupContactCache($groupID); |
585 | ||
abdb2607 | 586 | $processed = FALSE; |
353ffa53 | 587 | $tempTable = 'civicrm_temp_group_contact_cache' . rand(0, 2000); |
be2fb01f | 588 | foreach ([$sql, $sqlB] as $selectSql) { |
6a488035 TO |
589 | if (!$selectSql) { |
590 | continue; | |
591 | } | |
b8eae4bd | 592 | $insertSql = "CREATE TEMPORARY TABLE $tempTable ($selectSql);"; |
eb917190 | 593 | $processed = TRUE; |
801bafd7 | 594 | CRM_Core_DAO::executeQuery($insertSql); |
b8eae4bd | 595 | CRM_Core_DAO::executeQuery( |
596 | "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id) | |
eab13399 | 597 | SELECT DISTINCT $idName, group_id FROM $tempTable |
b8eae4bd | 598 | "); |
5467c9fb | 599 | CRM_Core_DAO::executeQuery(" DROP TEMPORARY TABLE $tempTable"); |
6a488035 | 600 | } |
b8eae4bd | 601 | |
be2fb01f | 602 | self::updateCacheTime([$groupID], $processed); |
6a488035 TO |
603 | |
604 | if ($group->children) { | |
605 | ||
606 | //Store a list of contacts who are removed from the parent group | |
607 | $sql = " | |
608 | SELECT contact_id | |
609 | FROM civicrm_group_contact | |
610 | WHERE civicrm_group_contact.status = 'Removed' | |
611 | AND civicrm_group_contact.group_id = $groupID "; | |
612 | $dao = CRM_Core_DAO::executeQuery($sql); | |
be2fb01f | 613 | $removed_contacts = []; |
6a488035 TO |
614 | while ($dao->fetch()) { |
615 | $removed_contacts[] = $dao->contact_id; | |
616 | } | |
617 | ||
618 | $childrenIDs = explode(',', $group->children); | |
619 | foreach ($childrenIDs as $childID) { | |
620 | $contactIDs = CRM_Contact_BAO_Group::getMember($childID, FALSE); | |
621 | //Unset each contact that is removed from the parent group | |
622 | foreach ($removed_contacts as $removed_contact) { | |
623 | unset($contactIDs[$removed_contact]); | |
624 | } | |
be2fb01f | 625 | $values = []; |
6a488035 TO |
626 | foreach ($contactIDs as $contactID => $dontCare) { |
627 | $values[] = "({$groupID},{$contactID})"; | |
628 | } | |
629 | ||
be2fb01f | 630 | self::store([$groupID], $values); |
6a488035 TO |
631 | } |
632 | } | |
cc13551d DL |
633 | |
634 | $lock->release(); | |
6a488035 TO |
635 | } |
636 | ||
86538308 | 637 | /** |
adf28ffd | 638 | * Retrieve the smart group cache timeout in minutes. |
639 | * | |
640 | * This checks if a timeout has been configured. If one has then smart groups should not | |
641 | * be refreshed more frequently than the time out. If a group was recently refreshed it should not | |
642 | * refresh again within that period. | |
643 | * | |
86538308 EM |
644 | * @return int |
645 | */ | |
00be9182 | 646 | public static function smartGroupCacheTimeout() { |
6a488035 TO |
647 | $config = CRM_Core_Config::singleton(); |
648 | ||
649 | if ( | |
650 | isset($config->smartGroupCacheTimeout) && | |
9bdcddd7 | 651 | is_numeric($config->smartGroupCacheTimeout) |
353ffa53 | 652 | ) { |
6a488035 TO |
653 | return $config->smartGroupCacheTimeout; |
654 | } | |
655 | ||
adf28ffd | 656 | // Default to 5 minutes. |
6a488035 TO |
657 | return 5; |
658 | } | |
659 | ||
9be31c7a | 660 | /** |
fe482240 | 661 | * Get all the smart groups that this contact belongs to. |
adf28ffd | 662 | * |
9be31c7a DL |
663 | * Note that this could potentially be a super slow function since |
664 | * it ensure that all contact groups are loaded in the cache | |
665 | * | |
77c5b619 TO |
666 | * @param int $contactID |
667 | * @param bool $showHidden | |
668 | * Hidden groups are shown only if this flag is set. | |
9be31c7a | 669 | * |
a6c01b45 CW |
670 | * @return array |
671 | * an array of groups that this contact belongs to | |
9be31c7a | 672 | */ |
00be9182 | 673 | public static function contactGroup($contactID, $showHidden = FALSE) { |
6a488035 | 674 | if (empty($contactID)) { |
5396af74 | 675 | return NULL; |
6a488035 TO |
676 | } |
677 | ||
678 | if (is_array($contactID)) { | |
679 | $contactIDs = $contactID; | |
680 | } | |
681 | else { | |
be2fb01f | 682 | $contactIDs = [$contactID]; |
6a488035 TO |
683 | } |
684 | ||
685 | self::loadAll(); | |
686 | ||
9be31c7a DL |
687 | $hiddenClause = ''; |
688 | if (!$showHidden) { | |
689 | $hiddenClause = ' AND (g.is_hidden = 0 OR g.is_hidden IS NULL) '; | |
690 | } | |
691 | ||
6a488035 TO |
692 | $contactIDString = CRM_Core_DAO::escapeString(implode(', ', $contactIDs)); |
693 | $sql = " | |
694 | SELECT gc.group_id, gc.contact_id, g.title, g.children, g.description | |
695 | FROM civicrm_group_contact_cache gc | |
696 | INNER JOIN civicrm_group g ON g.id = gc.group_id | |
697 | WHERE gc.contact_id IN ($contactIDString) | |
9be31c7a | 698 | $hiddenClause |
6a488035 TO |
699 | ORDER BY gc.contact_id, g.children |
700 | "; | |
701 | ||
702 | $dao = CRM_Core_DAO::executeQuery($sql); | |
be2fb01f | 703 | $contactGroup = []; |
e60f24eb | 704 | $prevContactID = NULL; |
6a488035 TO |
705 | while ($dao->fetch()) { |
706 | if ( | |
707 | $prevContactID && | |
708 | $prevContactID != $dao->contact_id | |
709 | ) { | |
710 | $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']); | |
711 | } | |
712 | $prevContactID = $dao->contact_id; | |
713 | if (!array_key_exists($dao->contact_id, $contactGroup)) { | |
5396af74 | 714 | $contactGroup[$dao->contact_id] |
be2fb01f | 715 | = ['group' => [], 'groupTitle' => []]; |
6a488035 TO |
716 | } |
717 | ||
5396af74 | 718 | $contactGroup[$dao->contact_id]['group'][] |
be2fb01f | 719 | = [ |
6a488035 TO |
720 | 'id' => $dao->group_id, |
721 | 'title' => $dao->title, | |
722 | 'description' => $dao->description, | |
21dfd5f5 | 723 | 'children' => $dao->children, |
be2fb01f | 724 | ]; |
6a488035 TO |
725 | $contactGroup[$dao->contact_id]['groupTitle'][] = $dao->title; |
726 | } | |
727 | ||
728 | if ($prevContactID) { | |
729 | $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']); | |
730 | } | |
731 | ||
13982f7b | 732 | if ((!empty($contactGroup[$contactID]) && is_numeric($contactID))) { |
6a488035 TO |
733 | return $contactGroup[$contactID]; |
734 | } | |
735 | else { | |
736 | return $contactGroup; | |
737 | } | |
738 | } | |
739 | ||
4052239b | 740 | /** |
741 | * Get the datetime from which the cache should be considered invalid. | |
742 | * | |
743 | * Ie if the smartgroup cache timeout is 5 minutes ago then the cache is invalid if it was | |
744 | * refreshed 6 minutes ago, but not if it was refreshed 4 minutes ago. | |
745 | * | |
746 | * @return string | |
747 | */ | |
748 | public static function getCacheInvalidDateTime() { | |
8b6074a7 | 749 | return date('YmdHis', strtotime("-" . self::smartGroupCacheTimeout() . " Minutes")); |
4052239b | 750 | } |
751 | ||
a986056d | 752 | /** |
753 | * Get the date when the cache should be refreshed from. | |
754 | * | |
755 | * Ie. now + the offset & we will delete anything prior to then. | |
756 | * | |
757 | * @return string | |
758 | */ | |
4052239b | 759 | public static function getRefreshDateTime() { |
8b6074a7 | 760 | return date('YmdHis', strtotime("+ " . self::smartGroupCacheTimeout() . " Minutes")); |
a986056d | 761 | } |
762 | ||
dadeae7d SL |
763 | /** |
764 | * Invalidates the smart group cache for a particular group | |
765 | * @param int $groupID - Group to invalidate | |
766 | */ | |
767 | public static function invalidateGroupContactCache($groupID) { | |
768 | CRM_Core_DAO::executeQuery("UPDATE civicrm_group | |
769 | SET cache_date = NULL, refresh_date = NULL | |
770 | WHERE id = %1", [ | |
771 | 1 => [$groupID, 'Positive'], | |
772 | ]); | |
773 | } | |
774 | ||
6a488035 | 775 | } |