CRM-12347
[civicrm-core.git] / CRM / Contact / BAO / GroupContactCache.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35 class CRM_Contact_BAO_GroupContactCache extends CRM_Contact_DAO_GroupContactCache {
36
37 static $_alreadyLoaded = array();
38
39 /**
40 * Check to see if we have cache entries for this group
41 * if not, regenerate, else return
42 *
43 * @param int $groupID groupID of group that we are checking against
44 *
45 * @return boolean true if we did not regenerate, false if we did
46 */
47 static function check($groupIDs) {
48 if (empty($groupIDs)) {
49 return TRUE;
50 }
51
52 return self::loadAll($groupIDs);
53 }
54
55 /**
56 * Check to see if we have cache entries for this group
57 * if not, regenerate, else return
58 *
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
62 *
63 * @return boolean true if we did not regenerate, false if we did
64 */
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
68
69 if (empty($groupIDs)) {
70 $groupIDClause = null;
71 $groupIDs = array( );
72 }
73 else {
74 if (!is_array($groupIDs)) {
75 $groupIDs = array($groupIDs);
76 }
77
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));
82
83 $groupIDClause = "AND (g.id IN ( {$groupIDString} ))";
84 }
85
86 $smartGroupCacheTimeout = self::smartGroupCacheTimeout();
87
88 //make sure to give original timezone settings again.
89 $now = CRM_Utils_Date::getUTCTime();
90
91 $limitClause = $orderClause = NULL;
92 if ($limit > 0) {
93 $limitClause = " LIMIT 0, $limit";
94 $orderClause = " ORDER BY g.cache_date, g.refresh_date";
95 }
96 $query = "
97 SELECT g.id
98 FROM civicrm_group g
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 )
104 )
105 $groupIDClause
106 $orderClause
107 $limitClause
108 ";
109
110 $dao = CRM_Core_DAO::executeQuery($query);
111 $processGroupIDs = array();
112 $refreshGroupIDs = $groupIDs;
113 while ($dao->fetch()) {
114 $processGroupIDs[] = $dao->id;
115
116 // remove this id from refreshGroupIDs
117 foreach ($refreshGroupIDs as $idx => $gid) {
118 if ($gid == $dao->id) {
119 unset($refreshGroupIDs[$idx]);
120 break;
121 }
122 }
123 }
124
125 if (!empty($refreshGroupIDs)) {
126 $refreshGroupIDString = CRM_Core_DAO::escapeString(implode(', ', $refreshGroupIDString));
127 $time = CRM_Utils_Date::getUTCTime('YmdHis', $smartGroupCacheTimeout * 60);
128 $query = "
129 UPDATE civicrm_group g
130 SET g.refresh_date = $time
131 WHERE g.id IN ( {$refreshGroupIDString} )
132 AND g.refresh_date IS NULL
133 ";
134 }
135
136 if (empty($processGroupIDs)) {
137 return TRUE;
138 }
139 else {
140 self::add($processGroupIDs);
141 return FALSE;
142 }
143 }
144
145 static function add($groupID) {
146 // first delete the current cache
147 self::remove($groupID);
148 if (!is_array($groupID)) {
149 $groupID = array($groupID);
150 }
151
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);
157 }
158 }
159
160 static function store(&$groupID, &$values) {
161 $processed = FALSE;
162
163 // sort the values so we put group IDs in front and hence optimize
164 // mysql storage (or so we think) CRM-9493
165 sort($values);
166
167 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
168 while (!empty($values)) {
169 $processed = TRUE;
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);
174 }
175 self::updateCacheTime($groupID, $processed);
176 }
177
178 /**
179 * Change the cache_date
180 *
181 * @param $groupID array(int)
182 * @param $processed bool, whether the cache data was recently modified
183 */
184 static function updateCacheTime($groupID, $processed) {
185 // only update cache entry if we had any values
186 if ($processed) {
187 // also update the group with cache date information
188 //make sure to give original timezone settings again.
189 $now = CRM_Utils_Date::getUTCTime();
190 $refresh = 'null';
191 }
192 else {
193 $now = 'null';
194 $refresh = 'null';
195 }
196
197 $groupIDs = implode(',', $groupID);
198 $sql = "
199 UPDATE civicrm_group
200 SET cache_date = $now, refresh_date = $refresh
201 WHERE id IN ( $groupIDs )
202 ";
203 CRM_Core_DAO::executeQuery($sql);
204 }
205
206 static function remove($groupID = NULL, $onceOnly = TRUE) {
207 static $invoked = FALSE;
208
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
214 if ($onceOnly &&
215 $invoked &&
216 $groupID == NULL
217 ) {
218 return;
219 }
220
221 if ($groupID == NULL) {
222 $invoked = TRUE;
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]);
228 }
229
230 $refresh = null;
231 $params = array();
232 $smartGroupCacheTimeout = self::smartGroupCacheTimeout();
233
234 $now = CRM_Utils_Date::getUTCTime();
235 $refreshTime = CRM_Utils_Date::getUTCTime('YmdHis', $smartGroupCacheTimeout * 60);
236
237 if (!isset($groupID)) {
238 if ($smartGroupCacheTimeout == 0) {
239 $query = "
240 TRUNCATE civicrm_group_contact_cache
241 ";
242 $update = "
243 UPDATE civicrm_group g
244 SET cache_date = null,
245 refresh_date = null
246 ";
247 }
248 else {
249 $query = "
250 DELETE gc
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
254 ";
255 $update = "
256 UPDATE civicrm_group g
257 SET cache_date = null,
258 refresh_date = null
259 WHERE TIMESTAMPDIFF(MINUTE, cache_date, $now) >= $smartGroupCacheTimeout
260 ";
261 $refresh = "
262 UPDATE civicrm_group g
263 SET refresh_date = $refreshTime
264 WHERE TIMESTAMPDIFF(MINUTE, cache_date, $now) < $smartGroupCacheTimeout
265 AND refresh_date IS NULL
266 ";
267 }
268 }
269 elseif (is_array($groupID)) {
270 $groupIDs = implode(', ', $groupID);
271 $query = "
272 DELETE g
273 FROM civicrm_group_contact_cache g
274 WHERE g.group_id IN ( $groupIDs )
275 ";
276 $update = "
277 UPDATE civicrm_group g
278 SET cache_date = null,
279 refresh_date = null
280 WHERE id IN ( $groupIDs )
281 ";
282 }
283 else {
284 $query = "
285 DELETE g
286 FROM civicrm_group_contact_cache g
287 WHERE g.group_id = %1
288 ";
289 $update = "
290 UPDATE civicrm_group g
291 SET cache_date = null,
292 refresh_date = null
293 WHERE id = %1
294 ";
295 $params = array(1 => array($groupID, 'Integer'));
296 }
297
298 CRM_Core_DAO::executeQuery($query, $params);
299
300 if ($refresh) {
301 CRM_Core_DAO::executeQuery($refresh, $params);
302 }
303
304 // also update the cache_date for these groups
305 CRM_Core_DAO::executeQuery($update, $params);
306 }
307
308 /**
309 * load the smart group cache for a saved search
310 */
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) {
315 return;
316 }
317 self::$_alreadyLoaded[$groupID] = 1;
318 $sql = NULL;
319 $idName = 'id';
320 $customClass = NULL;
321 if ($savedSearchID) {
322 $ssParams = CRM_Contact_BAO_SavedSearch::getSearchParams($savedSearchID);
323
324 // rectify params to what proximity search expects if there is a value for prox_distance
325 // CRM-7021
326 if (!empty($ssParams)) {
327 CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams);
328 }
329
330
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);
335 }
336
337 if (isset($ssParams['customSearchID'])) {
338 // if custom search
339
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
343 $customClass =
344 CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID);
345 $searchSQL = $customClass->contactIDs();
346 $idName = 'contact_id';
347 }
348 else {
349 $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
350
351 $query =
352 new CRM_Contact_BAO_Query(
353 $ssParams, $returnProperties, NULL,
354 FALSE, FALSE, 1,
355 TRUE, TRUE,
356 FALSE,
357 CRM_Utils_Array::value('display_relationship_type', $formValues),
358 CRM_Utils_Array::value('operator', $formValues, 'AND')
359 );
360 $query->_useDistinct = FALSE;
361 $query->_useGroupBy = FALSE;
362 $searchSQL =
363 $query->searchQuery(
364 0, 0, NULL,
365 FALSE, FALSE,
366 FALSE, TRUE,
367 TRUE,
368 NULL, NULL, NULL,
369 TRUE
370 );
371 }
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 ) ";
377 }
378
379 if ($sql) {
380 $sql = preg_replace("/^\s*SELECT/", "SELECT $groupID as group_id, ", $sql);
381 }
382
383 // lets also store the records that are explicitly added to the group
384 // this allows us to skip the group contact LEFT JOIN
385 $sqlB = "
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 ";
390
391 $groupIDs = array($groupID);
392 self::remove($groupIDs);
393
394 foreach (array($sql, $sqlB) as $selectSql) {
395 if (!$selectSql) {
396 continue;
397 }
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);
401 }
402 self::updateCacheTime($groupIDs, $processed);
403
404 if ($group->children) {
405
406 //Store a list of contacts who are removed from the parent group
407 $sql = "
408 SELECT contact_id
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;
416 }
417
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]);
424 }
425 $values = array();
426 foreach ($contactIDs as $contactID => $dontCare) {
427 $values[] = "({$groupID},{$contactID})";
428 }
429
430 self::store($groupIDs, $values);
431 }
432 }
433 }
434
435 static function smartGroupCacheTimeout() {
436 $config = CRM_Core_Config::singleton();
437
438 if (
439 isset($config->smartGroupCacheTimeout) &&
440 is_numeric($config->smartGroupCacheTimeout) &&
441 $config->smartGroupCacheTimeout > 0) {
442 return $config->smartGroupCacheTimeout;
443 }
444
445 // lets have a min cache time of 5 mins if not set
446 return 5;
447 }
448
449 static function contactGroup($contactID) {
450 if (empty($contactID)) {
451 return;
452 }
453
454 if (is_array($contactID)) {
455 $contactIDs = $contactID;
456 }
457 else {
458 $contactIDs = array($contactID);
459 }
460
461 self::loadAll();
462
463 $contactIDString = CRM_Core_DAO::escapeString(implode(', ', $contactIDs));
464 $sql = "
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
470 ";
471
472 $dao = CRM_Core_DAO::executeQuery($sql);
473 $contactGroup = array();
474 $prevContactID = null;
475 while ($dao->fetch()) {
476 if (
477 $prevContactID &&
478 $prevContactID != $dao->contact_id
479 ) {
480 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
481 }
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());
486 }
487
488 $contactGroup[$dao->contact_id]['group'][] =
489 array(
490 'id' => $dao->group_id,
491 'title' => $dao->title,
492 'description' => $dao->description,
493 'children' => $dao->children
494 );
495 $contactGroup[$dao->contact_id]['groupTitle'][] = $dao->title;
496 }
497
498 if ($prevContactID) {
499 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
500 }
501
502 if (is_numeric($contactID)) {
503 return $contactGroup[$contactID];
504 }
505 else {
506 return $contactGroup;
507 }
508 }
509
510 }
511