Merge pull request #5903 from scardinius/master
[civicrm-core.git] / CRM / Contact / BAO / GroupContactCache.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 */
33class CRM_Contact_BAO_GroupContactCache extends CRM_Contact_DAO_GroupContactCache {
34
35 static $_alreadyLoaded = array();
36
37 /**
67d19299 38 * Check to see if we have cache entries for this group.
39 *
40 * If not, regenerate, else return.
6a488035 41 *
77c5b619
TO
42 * @param $groupIDs
43 * Of group that we are checking against.
6a488035 44 *
5396af74 45 * @return bool
a6c01b45 46 * TRUE if we did not regenerate, FALSE if we did
6a488035 47 */
00be9182 48 public static function check($groupIDs) {
6a488035
TO
49 if (empty($groupIDs)) {
50 return TRUE;
51 }
52
53 return self::loadAll($groupIDs);
54 }
55
abdb2607
DL
56 /**
57 * Common function that formulates the query to see which groups needs to be refreshed
58 * based on their cache date and the smartGroupCacheTimeOut
59 *
77c5b619
TO
60 * @param string $groupIDClause
61 * The clause which limits which groups we need to evaluate.
62 * @param bool $includeHiddenGroups
63 * Hidden groups are excluded by default.
abdb2607 64 *
a6c01b45
CW
65 * @return string
66 * the sql query which lists the groups that need to be refreshed
abdb2607 67 */
e60f24eb 68 public static function groupRefreshedClause($groupIDClause = NULL, $includeHiddenGroups = FALSE) {
abdb2607
DL
69 $smartGroupCacheTimeout = self::smartGroupCacheTimeout();
70 $now = CRM_Utils_Date::getUTCTime();
71
72 $query = "
73SELECT g.id
74FROM civicrm_group g
75WHERE ( g.saved_search_id IS NOT NULL OR g.children IS NOT NULL )
76AND g.is_active = 1
77AND ( g.cache_date IS NULL OR
78 ( TIMESTAMPDIFF(MINUTE, g.cache_date, $now) >= $smartGroupCacheTimeout ) OR
79 ( $now >= g.refresh_date )
80 )
81";
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 /**
95 * Checks to see if a group has been refreshed recently. This is primarily used
96 * in a locking scenario when some other process might have refreshed things underneath
97 * this process
98 *
77c5b619
TO
99 * @param int $groupID
100 * The group ID.
101 * @param bool $includeHiddenGroups
102 * Hidden groups are excluded by default.
abdb2607 103 *
a6c01b45
CW
104 * @return string
105 * the sql query which lists the groups that need to be refreshed
abdb2607 106 */
00be9182 107 public static function shouldGroupBeRefreshed($groupID, $includeHiddenGroups = FALSE) {
abdb2607
DL
108 $query = self::groupRefreshedClause("g.id = %1", $includeHiddenGroups);
109 $params = array(1 => array($groupID, 'Integer'));
110
4f53db5a 111 // if the query returns the group ID, it means the group is a valid candidate for refreshing
abdb2607
DL
112 return CRM_Core_DAO::singleValueQuery($query, $params);
113 }
114
6a488035
TO
115 /**
116 * Check to see if we have cache entries for this group
117 * if not, regenerate, else return
118 *
5396af74 119 * @param int /array $groupIDs groupIDs of group that we are checking against
6a488035 120 * if empty, all groups are checked
77c5b619
TO
121 * @param int $limit
122 * Limits the number of groups we evaluate.
6a488035 123 *
5396af74 124 * @return bool
a6c01b45 125 * TRUE if we did not regenerate, FALSE if we did
6a488035 126 */
e60f24eb 127 public static function loadAll($groupIDs = NULL, $limit = 0) {
6a488035
TO
128 // ensure that all the smart groups are loaded
129 // this function is expensive and should be sparingly used if groupIDs is empty
6a488035 130 if (empty($groupIDs)) {
e60f24eb 131 $groupIDClause = NULL;
481a74f4 132 $groupIDs = array();
6a488035
TO
133 }
134 else {
135 if (!is_array($groupIDs)) {
136 $groupIDs = array($groupIDs);
137 }
138
b44e3f84 139 // note escapeString is a must here and we can't send the imploded value as second argument to
6a488035
TO
140 // the executeQuery(), since that would put single quote around the string and such a string
141 // of comma separated integers would not work.
0e4e5a49 142 $groupIDString = CRM_Core_DAO::escapeString(implode(', ', $groupIDs));
6a488035 143
abdb2607 144 $groupIDClause = "g.id IN ({$groupIDString})";
6a488035
TO
145 }
146
abdb2607 147 $query = self::groupRefreshedClause($groupIDClause);
6a488035
TO
148
149 $limitClause = $orderClause = NULL;
150 if ($limit > 0) {
151 $limitClause = " LIMIT 0, $limit";
152 $orderClause = " ORDER BY g.cache_date, g.refresh_date";
153 }
e2422b8f 154 // We ignore hidden groups and disabled groups
abdb2607 155 $query .= "
6a488035 156 $orderClause
f9e16e9a 157 $limitClause
6a488035
TO
158";
159
160 $dao = CRM_Core_DAO::executeQuery($query);
161 $processGroupIDs = array();
162 $refreshGroupIDs = $groupIDs;
163 while ($dao->fetch()) {
164 $processGroupIDs[] = $dao->id;
165
166 // remove this id from refreshGroupIDs
167 foreach ($refreshGroupIDs as $idx => $gid) {
168 if ($gid == $dao->id) {
169 unset($refreshGroupIDs[$idx]);
170 break;
171 }
172 }
173 }
174
175 if (!empty($refreshGroupIDs)) {
82a837e9 176 $refreshGroupIDString = CRM_Core_DAO::escapeString(implode(', ', $refreshGroupIDs));
353ffa53 177 $time = CRM_Utils_Date::getUTCTime(self::smartGroupCacheTimeout() * 60);
6a488035
TO
178 $query = "
179UPDATE civicrm_group g
180SET g.refresh_date = $time
181WHERE g.id IN ( {$refreshGroupIDString} )
182AND g.refresh_date IS NULL
183";
82a837e9 184 CRM_Core_DAO::executeQuery($query);
6a488035
TO
185 }
186
187 if (empty($processGroupIDs)) {
188 return TRUE;
189 }
190 else {
191 self::add($processGroupIDs);
192 return FALSE;
193 }
194 }
195
520bca8e
CW
196 /**
197 * FIXME: This function should not be needed, because the cache table should not be getting truncated
198 */
00be9182 199 public static function fillIfEmpty() {
520bca8e
CW
200 if (!CRM_Core_DAO::singleValueQuery("SELECT COUNT(id) FROM civicrm_group_contact_cache")) {
201 self::loadAll();
202 }
203 }
204
86538308 205 /**
100fef9d 206 * @param int $groupID
86538308 207 */
00be9182 208 public static function add($groupID) {
6a488035
TO
209 // first delete the current cache
210 self::remove($groupID);
211 if (!is_array($groupID)) {
212 $groupID = array($groupID);
213 }
214
215 $returnProperties = array('contact_id');
216 foreach ($groupID as $gid) {
1dbdc161 217 $params = array(array('group', 'IN', array($gid), 0, 0));
abdb2607 218 // the below call updates the cache table as a byproduct of the query
6a488035
TO
219 CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, FALSE);
220 }
221 }
222
86538308 223 /**
100fef9d 224 * @param int $groupID
86538308
EM
225 * @param $values
226 */
00be9182 227 public static function store(&$groupID, &$values) {
6a488035
TO
228 $processed = FALSE;
229
230 // sort the values so we put group IDs in front and hence optimize
231 // mysql storage (or so we think) CRM-9493
232 sort($values);
eb917190 233
6a488035
TO
234 // to avoid long strings, lets do BULK_INSERT_COUNT values at a time
235 while (!empty($values)) {
236 $processed = TRUE;
353ffa53
TO
237 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
238 $str = implode(',', $input);
239 $sql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) VALUES $str;";
6a488035
TO
240 CRM_Core_DAO::executeQuery($sql);
241 }
242 self::updateCacheTime($groupID, $processed);
243 }
244
245 /**
fe482240 246 * Change the cache_date.
6a488035 247 *
5a4f6742
CW
248 * @param array $groupID
249 * @param bool $processed
250 * Whether the cache data was recently modified.
6a488035 251 */
00be9182 252 public static function updateCacheTime($groupID, $processed) {
6a488035
TO
253 // only update cache entry if we had any values
254 if ($processed) {
255 // also update the group with cache date information
256 //make sure to give original timezone settings again.
353ffa53 257 $now = CRM_Utils_Date::getUTCTime();
6a488035
TO
258 $refresh = 'null';
259 }
260 else {
353ffa53 261 $now = 'null';
6a488035
TO
262 $refresh = 'null';
263 }
264
265 $groupIDs = implode(',', $groupID);
266 $sql = "
267UPDATE civicrm_group
268SET cache_date = $now, refresh_date = $refresh
269WHERE id IN ( $groupIDs )
270";
271 CRM_Core_DAO::executeQuery($sql);
272 }
273
cee4f6a1 274 /**
fe482240 275 * Removes all the cache entries pertaining to a specific group.
cee4f6a1
DL
276 * If no groupID is passed in, removes cache entries for all groups
277 * Has an optimization to bypass repeated invocations of this function.
278 * Note that this function is an advisory, i.e. the removal respects the
279 * cache date, i.e. the removal is not done if the group was recently
280 * loaded into the cache.
281 *
5a4f6742
CW
282 * @param int $groupID
283 * the groupID to delete cache entries, NULL for all groups.
284 * @param bool $onceOnly
285 * run the function exactly once for all groups.
cee4f6a1 286 */
00be9182 287 public static function remove($groupID = NULL, $onceOnly = TRUE) {
6a488035
TO
288 static $invoked = FALSE;
289
290 // typically this needs to happy only once per instance
4eeb9a5b 291 // this is especially TRUE in import, where we dont need
6a488035
TO
292 // to do this all the time
293 // this optimization is done only when no groupID is passed
294 // i.e. cache is reset for all groups
abdb2607
DL
295 if (
296 $onceOnly &&
6a488035
TO
297 $invoked &&
298 $groupID == NULL
299 ) {
300 return;
301 }
302
303 if ($groupID == NULL) {
304 $invoked = TRUE;
0db6c3e1 305 }
4c9b6178 306 elseif (is_array($groupID)) {
abdb2607 307 foreach ($groupID as $gid) {
6a488035 308 unset(self::$_alreadyLoaded[$gid]);
abdb2607 309 }
0db6c3e1 310 }
4c9b6178 311 elseif ($groupID && array_key_exists($groupID, self::$_alreadyLoaded)) {
6a488035
TO
312 unset(self::$_alreadyLoaded[$groupID]);
313 }
314
e60f24eb 315 $refresh = NULL;
353ffa53 316 $params = array();
6a488035
TO
317 $smartGroupCacheTimeout = self::smartGroupCacheTimeout();
318
353ffa53 319 $now = CRM_Utils_Date::getUTCTime();
cf142e47 320 $refreshTime = CRM_Utils_Date::getUTCTime($smartGroupCacheTimeout * 60);
6a488035
TO
321
322 if (!isset($groupID)) {
323 if ($smartGroupCacheTimeout == 0) {
324 $query = "
325TRUNCATE civicrm_group_contact_cache
326";
327 $update = "
328UPDATE civicrm_group g
329SET cache_date = null,
330 refresh_date = null
331";
332 }
333 else {
a4f518e9 334
6a488035
TO
335 $query = "
336DELETE gc
337FROM civicrm_group_contact_cache gc
338INNER JOIN civicrm_group g ON g.id = gc.group_id
9fd7ef4f 339WHERE g.cache_date <= %1
6a488035
TO
340";
341 $update = "
342UPDATE civicrm_group g
343SET cache_date = null,
344 refresh_date = null
9fd7ef4f 345WHERE g.cache_date <= %1
6a488035
TO
346";
347 $refresh = "
348UPDATE civicrm_group g
349SET refresh_date = $refreshTime
9fd7ef4f 350WHERE g.cache_date > %1
6a488035
TO
351AND refresh_date IS NULL
352";
a4f518e9 353 $cacheTime = date('Y-m-d H-i-s', strtotime("- $smartGroupCacheTimeout minutes"));
354 $params = array(1 => array($cacheTime, 'String'));
6a488035
TO
355 }
356 }
357 elseif (is_array($groupID)) {
358 $groupIDs = implode(', ', $groupID);
359 $query = "
360DELETE g
361FROM civicrm_group_contact_cache g
362WHERE g.group_id IN ( $groupIDs )
363";
364 $update = "
365UPDATE civicrm_group g
366SET cache_date = null,
367 refresh_date = null
368WHERE id IN ( $groupIDs )
369";
370 }
371 else {
372 $query = "
373DELETE g
374FROM civicrm_group_contact_cache g
375WHERE g.group_id = %1
376";
377 $update = "
378UPDATE civicrm_group g
379SET cache_date = null,
380 refresh_date = null
381WHERE id = %1
382";
383 $params = array(1 => array($groupID, 'Integer'));
384 }
385
386 CRM_Core_DAO::executeQuery($query, $params);
387
388 if ($refresh) {
389 CRM_Core_DAO::executeQuery($refresh, $params);
390 }
391
392 // also update the cache_date for these groups
393 CRM_Core_DAO::executeQuery($update, $params);
394 }
395
2c6bbd06 396 /**
fe482240 397 * Removes one or more contacts from the smart group cache.
2c6bbd06
CW
398 * @param int|array $cid
399 * @param int $groupId
4eeb9a5b
TO
400 * @return bool
401 * TRUE if successful.
2c6bbd06 402 */
00be9182 403 public static function removeContact($cid, $groupId = NULL) {
2c6bbd06
CW
404 $cids = array();
405 // sanitize input
406 foreach ((array) $cid as $c) {
407 $cids[] = CRM_Utils_Type::escape($c, 'Integer');
408 }
409 if ($cids) {
410 $condition = count($cids) == 1 ? "= {$cids[0]}" : "IN (" . implode(',', $cids) . ")";
411 if ($groupId) {
412 $condition .= " AND group_id = " . CRM_Utils_Type::escape($groupId, 'Integer');
413 }
414 $sql = "DELETE FROM civicrm_group_contact_cache WHERE contact_id $condition";
415 CRM_Core_DAO::executeQuery($sql);
416 return TRUE;
417 }
418 return FALSE;
419 }
420
6a488035 421 /**
fe482240 422 * Load the smart group cache for a saved search.
abdb2607 423 *
77c5b619
TO
424 * @param object $group
425 * The smart group that needs to be loaded.
426 * @param bool $force
427 * Should we force a search through.
6a488035 428 */
00be9182 429 public static function load(&$group, $force = FALSE) {
6a488035
TO
430 $groupID = $group->id;
431 $savedSearchID = $group->saved_search_id;
abdb2607 432 if (array_key_exists($groupID, self::$_alreadyLoaded) && !$force) {
6a488035
TO
433 return;
434 }
cc13551d
DL
435
436 // grab a lock so other processes dont compete and do the same query
83617886 437 $lock = Civi::lockManager()->acquire("data.core.group.{$groupID}");
cc13551d
DL
438 if (!$lock->isAcquired()) {
439 // this can cause inconsistent results since we dont know if the other process
440 // will fill up the cache before our calling routine needs it.
441 // however this routine does not return the status either, so basically
442 // its a "lets return and hope for the best"
443 return;
444 }
445
6a488035 446 self::$_alreadyLoaded[$groupID] = 1;
abdb2607 447
b44e3f84 448 // we now have the lock, but some other process could have actually done the work
abdb2607
DL
449 // before we got here, so before we do any work, lets ensure that work needs to be
450 // done
451 // we allow hidden groups here since we dont know if the caller wants to evaluate an
452 // hidden group
3cd86345 453 if (!$force && !self::shouldGroupBeRefreshed($groupID, TRUE)) {
abdb2607
DL
454 $lock->release();
455 return;
456 }
457
353ffa53
TO
458 $sql = NULL;
459 $idName = 'id';
6a488035
TO
460 $customClass = NULL;
461 if ($savedSearchID) {
462 $ssParams = CRM_Contact_BAO_SavedSearch::getSearchParams($savedSearchID);
463
464 // rectify params to what proximity search expects if there is a value for prox_distance
465 // CRM-7021
466 if (!empty($ssParams)) {
467 CRM_Contact_BAO_ProximityQuery::fixInputParams($ssParams);
468 }
469
6a488035
TO
470 $returnProperties = array();
471 if (CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch', $savedSearchID, 'mapping_id')) {
472 $fv = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
473 $returnProperties = CRM_Core_BAO_Mapping::returnProperties($fv);
474 }
475
476 if (isset($ssParams['customSearchID'])) {
477 // if custom search
478
479 // we split it up and store custom class
480 // so temp tables are not destroyed if they are used
481 // hence customClass is defined above at top of function
5396af74 482 $customClass = CRM_Contact_BAO_SearchCustom::customClass($ssParams['customSearchID'], $savedSearchID);
6a488035 483 $searchSQL = $customClass->contactIDs();
26a9b6ab 484 $searchSQL = str_replace('ORDER BY contact_a.id ASC', '', $searchSQL);
d02c030f 485 if (!strstr($searchSQL, 'WHERE')) {
486 $searchSQL .= " WHERE ( 1 ) ";
487 }
6a488035
TO
488 $idName = 'contact_id';
489 }
490 else {
491 $formValues = CRM_Contact_BAO_SavedSearch::getFormValues($savedSearchID);
beccb90f 492 // CRM-17075 using the formValues in this way imposes extra logic and complexity.
493 // we have the where_clause and where tables stored in the saved_search table
494 // and should use these rather than re-processing the form criteria (which over-works
495 // the link between the form layer & the query layer too).
496 // It's hard to think of when you would want to use anything other than return
497 // properties = array('contact_id' => 1) here as the point would appear to be to
498 // generate the list of contact ids in the group.
499 // @todo review this to use values in saved_search table (preferably for 4.8).
5396af74 500 $query
501 = new CRM_Contact_BAO_Query(
6a488035 502 $ssParams, $returnProperties, NULL,
cc13551d
DL
503 FALSE, FALSE, 1,
504 TRUE, TRUE,
505 FALSE,
6a488035
TO
506 CRM_Utils_Array::value('display_relationship_type', $formValues),
507 CRM_Utils_Array::value('operator', $formValues, 'AND')
353ffa53 508 );
6a488035 509 $query->_useDistinct = FALSE;
353ffa53 510 $query->_useGroupBy = FALSE;
5396af74 511 $searchSQL
512 = $query->searchQuery(
6a488035 513 0, 0, NULL,
353ffa53
TO
514 FALSE, FALSE,
515 FALSE, TRUE,
516 TRUE,
517 NULL, NULL, NULL,
518 TRUE
519 );
6a488035
TO
520 }
521 $groupID = CRM_Utils_Type::escape($groupID, 'Integer');
522 $sql = $searchSQL . " AND contact_a.id NOT IN (
523 SELECT contact_id FROM civicrm_group_contact
524 WHERE civicrm_group_contact.status = 'Removed'
525 AND civicrm_group_contact.group_id = $groupID ) ";
526 }
527
528 if ($sql) {
529 $sql = preg_replace("/^\s*SELECT/", "SELECT $groupID as group_id, ", $sql);
530 }
531
532 // lets also store the records that are explicitly added to the group
533 // this allows us to skip the group contact LEFT JOIN
534 $sqlB = "
535SELECT $groupID as group_id, contact_id as $idName
536FROM civicrm_group_contact
537WHERE civicrm_group_contact.status = 'Added'
538 AND civicrm_group_contact.group_id = $groupID ";
539
540 $groupIDs = array($groupID);
541 self::remove($groupIDs);
abdb2607 542 $processed = FALSE;
353ffa53 543 $tempTable = 'civicrm_temp_group_contact_cache' . rand(0, 2000);
6a488035
TO
544 foreach (array($sql, $sqlB) as $selectSql) {
545 if (!$selectSql) {
546 continue;
547 }
b8eae4bd 548 $insertSql = "CREATE TEMPORARY TABLE $tempTable ($selectSql);";
eb917190 549 $processed = TRUE;
6a488035 550 $result = CRM_Core_DAO::executeQuery($insertSql);
b8eae4bd 551 CRM_Core_DAO::executeQuery(
552 "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)
eab13399 553 SELECT DISTINCT $idName, group_id FROM $tempTable
b8eae4bd 554 ");
5467c9fb 555 CRM_Core_DAO::executeQuery(" DROP TEMPORARY TABLE $tempTable");
6a488035 556 }
b8eae4bd 557
6a488035
TO
558 self::updateCacheTime($groupIDs, $processed);
559
560 if ($group->children) {
561
562 //Store a list of contacts who are removed from the parent group
563 $sql = "
564SELECT contact_id
565FROM civicrm_group_contact
566WHERE civicrm_group_contact.status = 'Removed'
567AND civicrm_group_contact.group_id = $groupID ";
568 $dao = CRM_Core_DAO::executeQuery($sql);
569 $removed_contacts = array();
570 while ($dao->fetch()) {
571 $removed_contacts[] = $dao->contact_id;
572 }
573
574 $childrenIDs = explode(',', $group->children);
575 foreach ($childrenIDs as $childID) {
576 $contactIDs = CRM_Contact_BAO_Group::getMember($childID, FALSE);
577 //Unset each contact that is removed from the parent group
578 foreach ($removed_contacts as $removed_contact) {
579 unset($contactIDs[$removed_contact]);
580 }
581 $values = array();
582 foreach ($contactIDs as $contactID => $dontCare) {
583 $values[] = "({$groupID},{$contactID})";
584 }
585
586 self::store($groupIDs, $values);
587 }
588 }
cc13551d
DL
589
590 $lock->release();
6a488035
TO
591 }
592
86538308
EM
593 /**
594 * @return int
595 */
00be9182 596 public static function smartGroupCacheTimeout() {
6a488035
TO
597 $config = CRM_Core_Config::singleton();
598
599 if (
600 isset($config->smartGroupCacheTimeout) &&
9bdcddd7 601 is_numeric($config->smartGroupCacheTimeout)
353ffa53 602 ) {
6a488035
TO
603 return $config->smartGroupCacheTimeout;
604 }
605
606 // lets have a min cache time of 5 mins if not set
607 return 5;
608 }
609
9be31c7a 610 /**
fe482240 611 * Get all the smart groups that this contact belongs to.
9be31c7a
DL
612 * Note that this could potentially be a super slow function since
613 * it ensure that all contact groups are loaded in the cache
614 *
77c5b619
TO
615 * @param int $contactID
616 * @param bool $showHidden
617 * Hidden groups are shown only if this flag is set.
9be31c7a 618 *
a6c01b45
CW
619 * @return array
620 * an array of groups that this contact belongs to
9be31c7a 621 */
00be9182 622 public static function contactGroup($contactID, $showHidden = FALSE) {
6a488035 623 if (empty($contactID)) {
5396af74 624 return NULL;
6a488035
TO
625 }
626
627 if (is_array($contactID)) {
628 $contactIDs = $contactID;
629 }
630 else {
631 $contactIDs = array($contactID);
632 }
633
634 self::loadAll();
635
9be31c7a
DL
636 $hiddenClause = '';
637 if (!$showHidden) {
638 $hiddenClause = ' AND (g.is_hidden = 0 OR g.is_hidden IS NULL) ';
639 }
640
6a488035
TO
641 $contactIDString = CRM_Core_DAO::escapeString(implode(', ', $contactIDs));
642 $sql = "
643SELECT gc.group_id, gc.contact_id, g.title, g.children, g.description
644FROM civicrm_group_contact_cache gc
645INNER JOIN civicrm_group g ON g.id = gc.group_id
646WHERE gc.contact_id IN ($contactIDString)
9be31c7a 647 $hiddenClause
6a488035
TO
648ORDER BY gc.contact_id, g.children
649";
650
651 $dao = CRM_Core_DAO::executeQuery($sql);
652 $contactGroup = array();
e60f24eb 653 $prevContactID = NULL;
6a488035
TO
654 while ($dao->fetch()) {
655 if (
656 $prevContactID &&
657 $prevContactID != $dao->contact_id
658 ) {
659 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
660 }
661 $prevContactID = $dao->contact_id;
662 if (!array_key_exists($dao->contact_id, $contactGroup)) {
5396af74 663 $contactGroup[$dao->contact_id]
664 = array('group' => array(), 'groupTitle' => array());
6a488035
TO
665 }
666
5396af74 667 $contactGroup[$dao->contact_id]['group'][]
668 = array(
6a488035
TO
669 'id' => $dao->group_id,
670 'title' => $dao->title,
671 'description' => $dao->description,
21dfd5f5 672 'children' => $dao->children,
6a488035
TO
673 );
674 $contactGroup[$dao->contact_id]['groupTitle'][] = $dao->title;
675 }
676
677 if ($prevContactID) {
678 $contactGroup[$prevContactID]['groupTitle'] = implode(', ', $contactGroup[$prevContactID]['groupTitle']);
679 }
680
13982f7b 681 if ((!empty($contactGroup[$contactID]) && is_numeric($contactID))) {
6a488035
TO
682 return $contactGroup[$contactID];
683 }
684 else {
685 return $contactGroup;
686 }
687 }
688
689}