3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 class CRM_Contact_BAO_GroupContactCache
extends CRM_Contact_DAO_GroupContactCache
{
37 static $_alreadyLoaded = array();
40 * Check to see if we have cache entries for this group
41 * if not, regenerate, else return
43 * @param int $groupID groupID of group that we are checking against
45 * @return boolean true if we did not regenerate, false if we did
47 static function check($groupIDs) {
48 if (empty($groupIDs)) {
52 return self
::loadAll($groupIDs);
56 * Check to see if we have cache entries for this group
57 * if not, regenerate, else return
59 * @param int/array $groupID groupID of group that we are checking against
60 * if empty, all groups are checked
61 * @param int $limit limits the number of groups we evaluate
63 * @return boolean true if we did not regenerate, false if we did
65 static function loadAll($groupIDs = null, $limit = 0) {
66 // ensure that all the smart groups are loaded
67 // this function is expensive and should be sparingly used if groupIDs is empty
69 if (empty($groupIDs)) {
70 $groupIDClause = null;
74 if (!is_array($groupIDs)) {
75 $groupIDs = array($groupIDs);
78 // note escapeString is a must here and we can't send the imploded value as second arguement to
79 // the executeQuery(), since that would put single quote around the string and such a string
80 // of comma separated integers would not work.
81 $groupIDString = CRM_Core_DAO
::escapeString(implode(', ', $groupID));
83 $groupIDClause = "AND (g.id IN ( {$groupIDString} ))";
86 $smartGroupCacheTimeout = self
::smartGroupCacheTimeout();
88 //make sure to give original timezone settings again.
89 $now = CRM_Utils_Date
::getUTCTime();
91 $limitClause = $orderClause = NULL;
93 $limitClause = " LIMIT 0, $limit";
94 $orderClause = " ORDER BY g.cache_date, g.refresh_date";
99 WHERE ( g.saved_search_id IS NOT NULL OR
100 g.children IS NOT NULL )
101 AND ( g.cache_date IS NULL OR
102 ( TIMESTAMPDIFF(MINUTE, g.cache_date, $now) >= $smartGroupCacheTimeout ) OR
103 ( $now >= g.refresh_date )
110 $dao = CRM_Core_DAO
::executeQuery($query);
111 $processGroupIDs = array();
112 $refreshGroupIDs = $groupIDs;
113 while ($dao->fetch()) {
114 $processGroupIDs[] = $dao->id
;
116 // remove this id from refreshGroupIDs
117 foreach ($refreshGroupIDs as $idx => $gid) {
118 if ($gid == $dao->id
) {
119 unset($refreshGroupIDs[$idx]);
125 if (!empty($refreshGroupIDs)) {
126 $refreshGroupIDString = CRM_Core_DAO
::escapeString(implode(', ', $refreshGroupIDString));
127 $time = CRM_Utils_Date
::getUTCTime('YmdHis', $smartGroupCacheTimeout * 60);
129 UPDATE civicrm_group g
130 SET g.refresh_date = $time
131 WHERE g.id IN ( {$refreshGroupIDString} )
132 AND g.refresh_date IS NULL
136 if (empty($processGroupIDs)) {
140 self
::add($processGroupIDs);
145 static function add($groupID) {
146 // first delete the current cache
147 self
::remove($groupID);
148 if (!is_array($groupID)) {
149 $groupID = array($groupID);
152 $returnProperties = array('contact_id');
153 foreach ($groupID as $gid) {
154 $params = array(array('group', 'IN', array($gid => 1), 0, 0));
155 // the below call update the cache table as a byproduct of the query
156 CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, FALSE);
160 static function store(&$groupID, &$values) {
163 // sort the values so we put group IDs in front and hence optimize
164 // mysql storage (or so we think) CRM-9493
167 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
168 while (!empty($values)) {
170 $input = array_splice($values, 0, CRM_Core_DAO
::BULK_INSERT_COUNT
);
171 $str = implode(',', $input);
172 $sql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) VALUES $str;";
173 CRM_Core_DAO
::executeQuery($sql);
175 self
::updateCacheTime($groupID, $processed);
179 * Change the cache_date
181 * @param $groupID array(int)
182 * @param $processed bool, whether the cache data was recently modified
184 static function updateCacheTime($groupID, $processed) {
185 // only update cache entry if we had any values
187 // also update the group with cache date information
188 //make sure to give original timezone settings again.
189 $now = CRM_Utils_Date
::getUTCTime();
197 $groupIDs = implode(',', $groupID);
200 SET cache_date = $now, refresh_date = $refresh
201 WHERE id IN ( $groupIDs )
203 CRM_Core_DAO
::executeQuery($sql);
206 static function remove($groupID = NULL, $onceOnly = TRUE) {
207 static $invoked = FALSE;
209 // typically this needs to happy only once per instance
210 // this is especially true in import, where we dont need
211 // to do this all the time
212 // this optimization is done only when no groupID is passed
213 // i.e. cache is reset for all groups
221 if ($groupID == NULL) {
223 } else if (is_array($groupID)) {
224 foreach ($groupID as $gid)
225 unset(self
::$_alreadyLoaded[$gid]);
226 } else if ($groupID && array_key_exists($groupID, self
::$_alreadyLoaded)) {
227 unset(self
::$_alreadyLoaded[$groupID]);
232 $smartGroupCacheTimeout = self
::smartGroupCacheTimeout();
234 $now = CRM_Utils_Date
::getUTCTime();
235 $refreshTime = CRM_Utils_Date
::getUTCTime('YmdHis', $smartGroupCacheTimeout * 60);
237 if (!isset($groupID)) {
238 if ($smartGroupCacheTimeout == 0) {
240 TRUNCATE civicrm_group_contact_cache
243 UPDATE civicrm_group g
244 SET cache_date = null,
251 FROM civicrm_group_contact_cache gc
252 INNER JOIN civicrm_group g ON g.id = gc.group_id
253 WHERE TIMESTAMPDIFF(MINUTE, g.cache_date, $now) >= $smartGroupCacheTimeout
256 UPDATE civicrm_group g
257 SET cache_date = null,
259 WHERE TIMESTAMPDIFF(MINUTE, cache_date, $now) >= $smartGroupCacheTimeout
262 UPDATE civicrm_group g
263 SET refresh_date = $refreshTime
264 WHERE TIMESTAMPDIFF(MINUTE, cache_date, $now) < $smartGroupCacheTimeout
265 AND refresh_date IS NULL
269 elseif (is_array($groupID)) {
270 $groupIDs = implode(', ', $groupID);
273 FROM civicrm_group_contact_cache g
274 WHERE g.group_id IN ( $groupIDs )
277 UPDATE civicrm_group g
278 SET cache_date = null,
280 WHERE id IN ( $groupIDs )
286 FROM civicrm_group_contact_cache g
287 WHERE g.group_id = %1
290 UPDATE civicrm_group g
291 SET cache_date = null,
295 $params = array(1 => array($groupID, 'Integer'));
298 CRM_Core_DAO
::executeQuery($query, $params);
301 CRM_Core_DAO
::executeQuery($refresh, $params);
304 // also update the cache_date for these groups
305 CRM_Core_DAO
::executeQuery($update, $params);
309 * load the smart group cache for a saved search
311 static function load(&$group, $fresh = FALSE) {
312 $groupID = $group->id
;
313 $savedSearchID = $group->saved_search_id
;
314 if (array_key_exists($groupID, self
::$_alreadyLoaded) && !$fresh) {
317 self
::$_alreadyLoaded[$groupID] = 1;
321 if ($savedSearchID) {
322 $ssParams = CRM_Contact_BAO_SavedSearch
::getSearchParams($savedSearchID);
324 // rectify params to what proximity search expects if there is a value for prox_distance
326 if (!empty($ssParams)) {
327 CRM_Contact_BAO_ProximityQuery
::fixInputParams($ssParams);
331 $returnProperties = array();
332 if (CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) {
333 $fv = CRM_Contact_BAO_SavedSearch
::getFormValues($savedSearchID);
334 $returnProperties = CRM_Core_BAO_Mapping
::returnProperties($fv);
337 if (isset($ssParams['customSearchID'])) {
340 // we split it up and store custom class
341 // so temp tables are not destroyed if they are used
342 // hence customClass is defined above at top of function
344 CRM_Contact_BAO_SearchCustom
::customClass($ssParams['customSearchID'], $savedSearchID);
345 $searchSQL = $customClass->contactIDs();
346 $idName = 'contact_id';
349 $formValues = CRM_Contact_BAO_SavedSearch
::getFormValues($savedSearchID);
352 new CRM_Contact_BAO_Query(
353 $ssParams, $returnProperties, NULL,
357 CRM_Utils_Array
::value('display_relationship_type', $formValues),
358 CRM_Utils_Array
::value('operator', $formValues, 'AND')
360 $query->_useDistinct
= FALSE;
361 $query->_useGroupBy
= FALSE;
372 $groupID = CRM_Utils_Type
::escape($groupID, 'Integer');
373 $sql = $searchSQL . " AND contact_a.id NOT IN (
374 SELECT contact_id FROM civicrm_group_contact
375 WHERE civicrm_group_contact.status = 'Removed'
376 AND civicrm_group_contact.group_id = $groupID ) ";
380 $sql = preg_replace("/^\s*SELECT/", "SELECT $groupID as group_id, ", $sql);
383 // lets also store the records that are explicitly added to the group
384 // this allows us to skip the group contact LEFT JOIN
386 SELECT $groupID as group_id, contact_id as $idName
387 FROM civicrm_group_contact
388 WHERE civicrm_group_contact.status = 'Added'
389 AND civicrm_group_contact.group_id = $groupID ";
391 $groupIDs = array($groupID);
392 self
::remove($groupIDs);
394 foreach (array($sql, $sqlB) as $selectSql) {
398 $insertSql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) ($selectSql);";
399 $processed = TRUE; // FIXME
400 $result = CRM_Core_DAO
::executeQuery($insertSql);
402 self
::updateCacheTime($groupIDs, $processed);
404 if ($group->children
) {
406 //Store a list of contacts who are removed from the parent group
409 FROM civicrm_group_contact
410 WHERE civicrm_group_contact.status = 'Removed'
411 AND civicrm_group_contact.group_id = $groupID ";
412 $dao = CRM_Core_DAO
::executeQuery($sql);
413 $removed_contacts = array();
414 while ($dao->fetch()) {
415 $removed_contacts[] = $dao->contact_id
;
418 $childrenIDs = explode(',', $group->children
);
419 foreach ($childrenIDs as $childID) {
420 $contactIDs = CRM_Contact_BAO_Group
::getMember($childID, FALSE);
421 //Unset each contact that is removed from the parent group
422 foreach ($removed_contacts as $removed_contact) {
423 unset($contactIDs[$removed_contact]);
426 foreach ($contactIDs as $contactID => $dontCare) {
427 $values[] = "({$groupID},{$contactID})";
430 self
::store($groupIDs, $values);
435 static function smartGroupCacheTimeout() {
436 $config = CRM_Core_Config
::singleton();
439 isset($config->smartGroupCacheTimeout
) &&
440 is_numeric($config->smartGroupCacheTimeout
) &&
441 $config->smartGroupCacheTimeout
> 0) {
442 return $config->smartGroupCacheTimeout
;
445 // lets have a min cache time of 5 mins if not set
449 static function contactGroup($contactID) {
450 if (empty($contactID)) {
454 if (is_array($contactID)) {
455 $contactIDs = $contactID;
458 $contactIDs = array($contactID);
463 $contactIDString = CRM_Core_DAO
::escapeString(implode(', ', $contactIDs));
465 SELECT gc.group_id, gc.contact_id, g.title, g.children, g.description
466 FROM civicrm_group_contact_cache gc
467 INNER JOIN civicrm_group g ON g.id = gc.group_id
468 WHERE gc.contact_id IN ($contactIDString)
469 ORDER BY gc.contact_id, g.children
472 $dao = CRM_Core_DAO
::executeQuery($sql);
473 $contactGroup = array();
474 $prevContactID = null;
475 while ($dao->fetch()) {
478 $prevContactID != $dao->contact_id
480 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
482 $prevContactID = $dao->contact_id
;
483 if (!array_key_exists($dao->contact_id
, $contactGroup)) {
484 $contactGroup[$dao->contact_id
] =
485 array( 'group' => array(), 'groupTitle' => array());
488 $contactGroup[$dao->contact_id
]['group'][] =
490 'id' => $dao->group_id
,
491 'title' => $dao->title
,
492 'description' => $dao->description
,
493 'children' => $dao->children
495 $contactGroup[$dao->contact_id
]['groupTitle'][] = $dao->title
;
498 if ($prevContactID) {
499 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
502 if (is_numeric($contactID)) {
503 return $contactGroup[$contactID];
506 return $contactGroup;