3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
33 class CRM_Contact_BAO_GroupContactCache
extends CRM_Contact_DAO_GroupContactCache
{
35 static $_alreadyLoaded = array();
38 * Get a list of caching modes.
42 public static function getModes() {
44 // Flush expired caches in response to user actions.
45 'opportunistic' => ts('Opportunistic Flush'),
47 // Flush expired caches via background cron jobs.
48 'deterministic' => ts('Cron Flush'),
53 * Check to see if we have cache entries for this group.
55 * If not, regenerate, else return.
57 * @param array $groupIDs
58 * Of group that we are checking against.
61 * TRUE if we did not regenerate, FALSE if we did
63 public static function check($groupIDs) {
64 if (empty($groupIDs)) {
68 return self
::loadAll($groupIDs);
72 * Formulate the query to see which groups needs to be refreshed.
74 * The calculation is based on their cache date and the smartGroupCacheTimeOut
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.
82 * the sql query which lists the groups that need to be refreshed
84 public static function groupRefreshedClause($groupIDClause = NULL, $includeHiddenGroups = FALSE) {
85 $smartGroupCacheTimeoutDateTime = self
::getCacheInvalidDateTime();
90 WHERE ( g.saved_search_id IS NOT NULL OR g.children IS NOT NULL )
94 OR cache_date <= $smartGroupCacheTimeoutDateTime
95 OR NOW() >= g.refresh_date
98 if (!$includeHiddenGroups) {
99 $query .= "AND (g.is_hidden = 0 OR g.is_hidden IS NULL)";
102 if (!empty($groupIDClause)) {
103 $query .= " AND ( $groupIDClause ) ";
110 * Check to see if a group has been refreshed recently.
112 * This is primarily used in a locking scenario when some other process might have refreshed things underneath
115 * @param int $groupID
117 * @param bool $includeHiddenGroups
118 * Hidden groups are excluded by default.
121 * the sql query which lists the groups that need to be refreshed
123 public static function shouldGroupBeRefreshed($groupID, $includeHiddenGroups = FALSE) {
124 $query = self
::groupRefreshedClause("g.id = %1", $includeHiddenGroups);
125 $params = array(1 => array($groupID, 'Integer'));
127 // if the query returns the group ID, it means the group is a valid candidate for refreshing
128 return CRM_Core_DAO
::singleValueQuery($query, $params);
132 * Check to see if we have cache entries for this group.
134 * if not, regenerate, else return
136 * @param int|array $groupIDs groupIDs of group that we are checking against
137 * if empty, all groups are checked
139 * Limits the number of groups we evaluate.
142 * TRUE if we did not regenerate, FALSE if we did
144 public static function loadAll($groupIDs = NULL, $limit = 0) {
145 // ensure that all the smart groups are loaded
146 // this function is expensive and should be sparingly used if groupIDs is empty
147 if (empty($groupIDs)) {
148 $groupIDClause = NULL;
152 if (!is_array($groupIDs)) {
153 $groupIDs = array($groupIDs);
156 // note escapeString is a must here and we can't send the imploded value as second argument 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.
159 $groupIDString = CRM_Core_DAO
::escapeString(implode(', ', $groupIDs));
161 $groupIDClause = "g.id IN ({$groupIDString})";
164 $query = self
::groupRefreshedClause($groupIDClause);
166 $limitClause = $orderClause = NULL;
168 $limitClause = " LIMIT 0, $limit";
169 $orderClause = " ORDER BY g.cache_date, g.refresh_date";
171 // We ignore hidden groups and disabled groups
177 $dao = CRM_Core_DAO
::executeQuery($query);
178 $processGroupIDs = array();
179 $refreshGroupIDs = $groupIDs;
180 while ($dao->fetch()) {
181 $processGroupIDs[] = $dao->id
;
183 // remove this id from refreshGroupIDs
184 foreach ($refreshGroupIDs as $idx => $gid) {
185 if ($gid == $dao->id
) {
186 unset($refreshGroupIDs[$idx]);
192 if (!empty($refreshGroupIDs)) {
193 $refreshGroupIDString = CRM_Core_DAO
::escapeString(implode(', ', $refreshGroupIDs));
194 $time = self
::getRefreshDateTime();
196 UPDATE civicrm_group g
197 SET g.refresh_date = $time
198 WHERE g.id IN ( {$refreshGroupIDString} )
199 AND g.refresh_date IS NULL
201 CRM_Core_DAO
::executeQuery($query);
204 if (empty($processGroupIDs)) {
208 self
::add($processGroupIDs);
214 * Build the smart group cache for given groups.
216 * @param array $groupIDs
218 public static function add($groupIDs) {
219 $groupIDs = (array) $groupIDs;
221 foreach ($groupIDs as $groupID) {
222 // first delete the current cache
223 self
::clearGroupContactCache($groupID);
224 $params = array(array('group', 'IN', array($groupID), 0, 0));
225 // the below call updates the cache table as a byproduct of the query
226 CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'), NULL, NULL, 0, 0, FALSE);
231 * Store values into the group contact cache.
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.
236 * @param array $groupID
237 * @param array $values
239 public static function store($groupID, &$values) {
242 // sort the values so we put group IDs in front and hence optimize
243 // mysql storage (or so we think) CRM-9493
246 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
247 while (!empty($values)) {
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;";
252 CRM_Core_DAO
::executeQuery($sql);
254 self
::updateCacheTime($groupID, $processed);
258 * Change the cache_date.
260 * @param array $groupID
261 * @param bool $processed
262 * Whether the cache data was recently modified.
264 public static function updateCacheTime($groupID, $processed) {
265 // only update cache entry if we had any values
267 // also update the group with cache date information
268 $now = date('YmdHis');
276 $groupIDs = implode(',', $groupID);
279 SET cache_date = $now, refresh_date = $refresh
280 WHERE id IN ( $groupIDs )
282 CRM_Core_DAO
::executeQuery($sql);
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.
290 * Remove this function altogether by mid 2018.
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.
296 public static function remove() {
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', array('civi.tag' => 'deprecated'));
299 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
303 * Function to clear group contact cache and reset the corresponding
304 * group's cache and refresh date
306 * @param int $groupID
309 public static function clearGroupContactCache($groupID) {
310 $transaction = new CRM_Core_Transaction();
313 FROM civicrm_group_contact_cache g
314 WHERE g.group_id = %1 ";
317 UPDATE civicrm_group g
318 SET cache_date = null, refresh_date = null
322 1 => array($groupID, 'Integer'),
325 CRM_Core_DAO
::executeQuery($query, $params);
326 // also update the cache_date for these groups
327 CRM_Core_DAO
::executeQuery($update, $params);
328 unset(self
::$_alreadyLoaded[$groupID]);
330 $transaction->commit();
334 * Refresh the smart group cache tables.
336 * This involves clearing out any aged entries (based on the site timeout setting) and resetting the time outs.
338 * This function should be called via the opportunistic or deterministic cache refresh function to make the intent
341 protected static function flushCaches() {
343 $lock = self
::getLockForRefresh();
345 catch (CRM_Core_Exception
$e) {
346 // Someone else is kindly doing the refresh for us right now.
349 $params = array(1 => array(self
::getCacheInvalidDateTime(), 'String'));
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.
359 CRM_Core_DAO
::executeQuery(
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
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'.
371 CRM_Core_DAO
::executeQuery(
373 UPDATE civicrm_group g
374 SET cache_date = NULL,
376 WHERE g.cache_date <= %1
384 * Check if the refresh is already initiated.
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+
390 * Where these 2 locks fail we get 2 processes running at the same time, but we have at least minimised that.
392 * @return \Civi\Core\Lock\LockInterface
393 * @throws \CRM_Core_Exception
395 protected static function getLockForRefresh() {
396 if (!isset(Civi
::$statics[__CLASS__
]['is_refresh_init'])) {
397 Civi
::$statics[__CLASS__
] = array('is_refresh_init' => FALSE);
400 if (Civi
::$statics[__CLASS__
]['is_refresh_init']) {
401 throw new CRM_Core_Exception('A refresh has already run in this process');
403 $lock = Civi
::lockManager()->acquire('data.core.group.refresh');
404 if ($lock->isAcquired()) {
405 Civi
::$statics[__CLASS__
]['is_refresh_init'] = TRUE;
408 throw new CRM_Core_Exception('Mysql lock unavailable');
412 * Do an opportunistic cache refresh if the site is configured for these.
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
418 public static function opportunisticCacheFlush() {
419 if (Civi
::settings()->get('smart_group_cache_refresh_mode') == 'opportunistic') {
425 * Do a forced cache refresh.
427 * This function is appropriate to be called by system jobs & non-user sessions.
429 public static function deterministicCacheFlush() {
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");
442 * Remove one or more contacts from the smart group cache.
444 * @param int|array $cid
445 * @param int $groupId
448 * TRUE if successful.
450 public static function removeContact($cid, $groupId = NULL) {
453 foreach ((array) $cid as $c) {
454 $cids[] = CRM_Utils_Type
::escape($c, 'Integer');
457 $condition = count($cids) == 1 ?
"= {$cids[0]}" : "IN (" . implode(',', $cids) . ")";
459 $condition .= " AND group_id = " . CRM_Utils_Type
::escape($groupId, 'Integer');
461 $sql = "DELETE FROM civicrm_group_contact_cache WHERE contact_id $condition";
462 CRM_Core_DAO
::executeQuery($sql);
469 * Load the smart group cache for a saved search.
471 * @param object $group
472 * The smart group that needs to be loaded.
474 * Should we force a search through.
476 public static function load(&$group, $force = FALSE) {
477 $groupID = $group->id
;
478 $savedSearchID = $group->saved_search_id
;
479 if (array_key_exists($groupID, self
::$_alreadyLoaded) && !$force) {
483 // grab a lock so other processes don't compete and do the same query
484 $lock = Civi
::lockManager()->acquire("data.core.group.{$groupID}");
485 if (!$lock->isAcquired()) {
486 // this can cause inconsistent results since we don't know if the other process
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"
493 self
::$_alreadyLoaded[$groupID] = 1;
495 // we now have the lock, but some other process could have actually done the work
496 // before we got here, so before we do any work, lets ensure that work needs to be
498 // we allow hidden groups here since we dont know if the caller wants to evaluate an
500 if (!$force && !self
::shouldGroupBeRefreshed($groupID, TRUE)) {
508 if ($savedSearchID) {
509 $ssParams = CRM_Contact_BAO_SavedSearch
::getSearchParams($savedSearchID);
511 // rectify params to what proximity search expects if there is a value for prox_distance
513 if (!empty($ssParams)) {
514 CRM_Contact_BAO_ProximityQuery
::fixInputParams($ssParams);
517 $returnProperties = array();
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);
523 if (isset($ssParams['customSearchID'])) {
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
529 $customClass = CRM_Contact_BAO_SearchCustom
::customClass($ssParams['customSearchID'], $savedSearchID);
530 $searchSQL = $customClass->contactIDs();
531 $searchSQL = str_replace('ORDER BY contact_a.id ASC', '', $searchSQL);
532 if (!strstr($searchSQL, 'WHERE')) {
533 $searchSQL .= " WHERE ( 1 ) ";
535 $idName = 'contact_id';
538 $formValues = CRM_Contact_BAO_SavedSearch
::getFormValues($savedSearchID);
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).
548 = new CRM_Contact_BAO_Query(
549 $ssParams, $returnProperties, NULL,
553 CRM_Utils_Array
::value('display_relationship_type', $formValues),
554 CRM_Utils_Array
::value('operator', $formValues, 'AND')
556 $query->_useDistinct
= FALSE;
557 $query->_useGroupBy
= FALSE;
559 = $query->searchQuery(
568 $groupID = CRM_Utils_Type
::escape($groupID, 'Integer');
569 $sql = $searchSQL . " AND contact_a.id NOT IN (
570 SELECT contact_id FROM civicrm_group_contact
571 WHERE civicrm_group_contact.status = 'Removed'
572 AND civicrm_group_contact.group_id = $groupID ) ";
576 $sql = preg_replace("/^\s*SELECT/", "SELECT $groupID as group_id, ", $sql);
579 // lets also store the records that are explicitly added to the group
580 // this allows us to skip the group contact LEFT JOIN
582 SELECT $groupID as group_id, contact_id as $idName
583 FROM civicrm_group_contact
584 WHERE civicrm_group_contact.status = 'Added'
585 AND civicrm_group_contact.group_id = $groupID ";
587 self
::clearGroupContactCache($groupID);
590 $tempTable = 'civicrm_temp_group_contact_cache' . rand(0, 2000);
591 foreach (array($sql, $sqlB) as $selectSql) {
595 $insertSql = "CREATE TEMPORARY TABLE $tempTable ($selectSql);";
597 CRM_Core_DAO
::executeQuery($insertSql);
598 CRM_Core_DAO
::executeQuery(
599 "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)
600 SELECT DISTINCT $idName, group_id FROM $tempTable
602 CRM_Core_DAO
::executeQuery(" DROP TEMPORARY TABLE $tempTable");
605 self
::updateCacheTime(array($groupID), $processed);
607 if ($group->children
) {
609 //Store a list of contacts who are removed from the parent group
612 FROM civicrm_group_contact
613 WHERE civicrm_group_contact.status = 'Removed'
614 AND civicrm_group_contact.group_id = $groupID ";
615 $dao = CRM_Core_DAO
::executeQuery($sql);
616 $removed_contacts = array();
617 while ($dao->fetch()) {
618 $removed_contacts[] = $dao->contact_id
;
621 $childrenIDs = explode(',', $group->children
);
622 foreach ($childrenIDs as $childID) {
623 $contactIDs = CRM_Contact_BAO_Group
::getMember($childID, FALSE);
624 //Unset each contact that is removed from the parent group
625 foreach ($removed_contacts as $removed_contact) {
626 unset($contactIDs[$removed_contact]);
629 foreach ($contactIDs as $contactID => $dontCare) {
630 $values[] = "({$groupID},{$contactID})";
633 self
::store(array($groupID), $values);
641 * Retrieve the smart group cache timeout in minutes.
643 * This checks if a timeout has been configured. If one has then smart groups should not
644 * be refreshed more frequently than the time out. If a group was recently refreshed it should not
645 * refresh again within that period.
649 public static function smartGroupCacheTimeout() {
650 $config = CRM_Core_Config
::singleton();
653 isset($config->smartGroupCacheTimeout
) &&
654 is_numeric($config->smartGroupCacheTimeout
)
656 return $config->smartGroupCacheTimeout
;
659 // Default to 5 minutes.
664 * Get all the smart groups that this contact belongs to.
666 * Note that this could potentially be a super slow function since
667 * it ensure that all contact groups are loaded in the cache
669 * @param int $contactID
670 * @param bool $showHidden
671 * Hidden groups are shown only if this flag is set.
674 * an array of groups that this contact belongs to
676 public static function contactGroup($contactID, $showHidden = FALSE) {
677 if (empty($contactID)) {
681 if (is_array($contactID)) {
682 $contactIDs = $contactID;
685 $contactIDs = array($contactID);
692 $hiddenClause = ' AND (g.is_hidden = 0 OR g.is_hidden IS NULL) ';
695 $contactIDString = CRM_Core_DAO
::escapeString(implode(', ', $contactIDs));
697 SELECT gc.group_id, gc.contact_id, g.title, g.children, g.description
698 FROM civicrm_group_contact_cache gc
699 INNER JOIN civicrm_group g ON g.id = gc.group_id
700 WHERE gc.contact_id IN ($contactIDString)
702 ORDER BY gc.contact_id, g.children
705 $dao = CRM_Core_DAO
::executeQuery($sql);
706 $contactGroup = array();
707 $prevContactID = NULL;
708 while ($dao->fetch()) {
711 $prevContactID != $dao->contact_id
713 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
715 $prevContactID = $dao->contact_id
;
716 if (!array_key_exists($dao->contact_id
, $contactGroup)) {
717 $contactGroup[$dao->contact_id
]
718 = array('group' => array(), 'groupTitle' => array());
721 $contactGroup[$dao->contact_id
]['group'][]
723 'id' => $dao->group_id
,
724 'title' => $dao->title
,
725 'description' => $dao->description
,
726 'children' => $dao->children
,
728 $contactGroup[$dao->contact_id
]['groupTitle'][] = $dao->title
;
731 if ($prevContactID) {
732 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
735 if ((!empty($contactGroup[$contactID]) && is_numeric($contactID))) {
736 return $contactGroup[$contactID];
739 return $contactGroup;
744 * Get the datetime from which the cache should be considered invalid.
746 * Ie if the smartgroup cache timeout is 5 minutes ago then the cache is invalid if it was
747 * refreshed 6 minutes ago, but not if it was refreshed 4 minutes ago.
751 public static function getCacheInvalidDateTime() {
752 return date('YmdHis', strtotime("-" . self
::smartGroupCacheTimeout() . " Minutes"));
756 * Get the date when the cache should be refreshed from.
758 * Ie. now + the offset & we will delete anything prior to then.
762 public static function getRefreshDateTime() {
763 return date('YmdHis', strtotime("+ " . self
::smartGroupCacheTimeout() . " Minutes"));