Merge pull request #12992 from mattwire/datepicker_eventfees
[civicrm-core.git] / CRM / Contact / BAO / Group.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
32 */
33 class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group {
34
35 /**
36 * Class constructor.
37 */
38 public function __construct() {
39 parent::__construct();
40 }
41
42 /**
43 * Retrieve DB object based on input parameters.
44 *
45 * It also stores all the retrieved values in the default array.
46 *
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 * @param array $defaults
50 * (reference ) an assoc array to hold the flattened values.
51 *
52 * @return CRM_Contact_BAO_Group
53 */
54 public static function retrieve(&$params, &$defaults) {
55 $group = new CRM_Contact_DAO_Group();
56 $group->copyValues($params);
57 if ($group->find(TRUE)) {
58 CRM_Core_DAO::storeValues($group, $defaults);
59 return $group;
60 }
61 }
62
63 /**
64 * Delete the group and all the object that connect to this group.
65 *
66 * Incredibly destructive.
67 *
68 * @param int $id Group id.
69 */
70 public static function discard($id) {
71 CRM_Utils_Hook::pre('delete', 'Group', $id, CRM_Core_DAO::$_nullArray);
72
73 $transaction = new CRM_Core_Transaction();
74
75 // added for CRM-1631 and CRM-1794
76 // delete all subscribed mails with the selected group id
77 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
78 $subscribe->group_id = $id;
79 $subscribe->delete();
80
81 // delete all Subscription records with the selected group id
82 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
83 $subHistory->group_id = $id;
84 $subHistory->delete();
85
86 // delete all crm_group_contact records with the selected group id
87 $groupContact = new CRM_Contact_DAO_GroupContact();
88 $groupContact->group_id = $id;
89 $groupContact->delete();
90
91 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
92 $params = array(1 => array($id, 'Integer'));
93 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
94 CRM_Core_DAO::executeQuery($query, $params);
95
96 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
97 CRM_Core_DAO::executeQuery($query, $params);
98
99 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
100 // CRM-6186
101 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
102 CRM_Core_DAO::executeQuery($query, $params);
103
104 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
105 CRM_Core_DAO::executeQuery($query, $params);
106
107 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
108 CRM_Core_DAO::executeQuery($query, $params);
109
110 // delete from group table
111 $group = new CRM_Contact_DAO_Group();
112 $group->id = $id;
113 $group->delete();
114
115 $transaction->commit();
116
117 CRM_Utils_Hook::post('delete', 'Group', $id, $group);
118
119 // delete the recently created Group
120 $groupRecent = array(
121 'id' => $id,
122 'type' => 'Group',
123 );
124 CRM_Utils_Recent::del($groupRecent);
125 }
126
127 /**
128 * Returns an array of the contacts in the given group.
129 *
130 * @param int $id
131 */
132 public static function getGroupContacts($id) {
133 $params = array(array('group', 'IN', array(1 => $id), 0, 0));
134 list($contacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, array('contact_id'));
135 return $contacts;
136 }
137
138 /**
139 * Get the count of a members in a group with the specific status.
140 *
141 * @param int $id
142 * Group id.
143 * @param string $status
144 * status of members in group
145 * @param bool $countChildGroups
146 *
147 * @return int
148 * count of members in the group with above status
149 */
150 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
151 $groupContact = new CRM_Contact_DAO_GroupContact();
152 $groupIds = array($id);
153 if ($countChildGroups) {
154 $groupIds = CRM_Contact_BAO_GroupNesting::getDescendentGroupIds($groupIds);
155 }
156 $count = 0;
157
158 $contacts = self::getGroupContacts($id);
159
160 foreach ($groupIds as $groupId) {
161
162 $groupContacts = self::getGroupContacts($groupId);
163 foreach ($groupContacts as $gcontact) {
164 if ($groupId != $id) {
165 // Loop through main group's contacts
166 // and subtract from the count for each contact which
167 // matches one in the present group, if it is not the
168 // main group
169 foreach ($contacts as $contact) {
170 if ($contact['contact_id'] == $gcontact['contact_id']) {
171 $count--;
172 }
173 }
174 }
175 }
176 $groupContact->group_id = $groupId;
177 if (isset($status)) {
178 $groupContact->status = $status;
179 }
180 $groupContact->_query['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
181 $count += $groupContact->count();
182 }
183 return $count;
184 }
185
186 /**
187 * Get the list of member for a group id.
188 *
189 * @param int $groupID
190 * @param bool $useCache
191 * @param int $limit
192 * Number to limit to (or 0 for unlimited).
193 *
194 * @return array
195 * this array contains the list of members for this group id
196 */
197 public static function getMember($groupID, $useCache = TRUE, $limit = 0) {
198 $params = array(array('group', '=', $groupID, 0, 0));
199 $returnProperties = array('contact_id');
200 list($contacts) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache);
201
202 $aMembers = array();
203 foreach ($contacts as $contact) {
204 $aMembers[$contact['contact_id']] = 1;
205 }
206
207 return $aMembers;
208 }
209
210 /**
211 * Returns array of group object(s) matching a set of one or Group properties.
212 *
213 * @param array $params
214 * Limits the set of groups returned.
215 * @param array $returnProperties
216 * Which properties should be included in the returned group objects.
217 * (member_count should be last element.)
218 * @param string $sort
219 * @param int $offset
220 * @param int $rowCount
221 *
222 * @return array
223 * Array of group objects.
224 *
225 *
226 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
227 * add in essential fields (e.g. id). This should follow a regular pattern like the others
228 */
229 public static function getGroups(
230 $params = NULL,
231 $returnProperties = NULL,
232 $sort = NULL,
233 $offset = NULL,
234 $rowCount = NULL
235 ) {
236 $dao = new CRM_Contact_DAO_Group();
237 if (!isset($params['is_active'])) {
238 $dao->is_active = 1;
239 }
240 if ($params) {
241 foreach ($params as $k => $v) {
242 if ($k == 'name' || $k == 'title') {
243 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO::escapeString($v) . '"');
244 }
245 elseif ($k == 'group_type') {
246 foreach ((array) $v as $type) {
247 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO::VALUE_SEPARATOR . (int) $type . CRM_Core_DAO::VALUE_SEPARATOR . "%'");
248 }
249 }
250 elseif (is_array($v)) {
251 foreach ($v as &$num) {
252 $num = (int) $num;
253 }
254 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
255 }
256 else {
257 $dao->$k = $v;
258 }
259 }
260 }
261
262 if ($offset || $rowCount) {
263 $offset = ($offset > 0) ? $offset : 0;
264 $rowCount = ($rowCount > 0) ? $rowCount : 25;
265 $dao->limit($offset, $rowCount);
266 }
267
268 if ($sort) {
269 $dao->orderBy($sort);
270 }
271
272 // return only specific fields if returnproperties are sent
273 if (!empty($returnProperties)) {
274 $dao->selectAdd();
275 $dao->selectAdd(implode(',', $returnProperties));
276 }
277 $dao->find();
278
279 $flag = $returnProperties && in_array('member_count', $returnProperties) ? 1 : 0;
280
281 $groups = array();
282 while ($dao->fetch()) {
283 $group = new CRM_Contact_DAO_Group();
284 if ($flag) {
285 $dao->member_count = CRM_Contact_BAO_Group::memberCount($dao->id);
286 }
287 $groups[] = clone($dao);
288 }
289 return $groups;
290 }
291
292 /**
293 * Make sure that the user has permission to access this group.
294 *
295 * @param int $id
296 * The id of the object.
297 * @param bool $excludeHidden
298 * Should hidden groups be excluded.
299 * Logically this is the wrong place to filter hidden groups out as that is
300 * not a permission issue. However, as other functions may rely on that defaulting to
301 * FALSE for now & only the api call is calling with true.
302 *
303 * @return array
304 * The permission that the user has (or NULL)
305 */
306 public static function checkPermission($id, $excludeHidden = FALSE) {
307 $allGroups = CRM_Core_PseudoConstant::allGroup(NULL, $excludeHidden);
308
309 $permissions = NULL;
310 if (CRM_Core_Permission::check('edit all contacts') ||
311 CRM_ACL_API::groupPermission(CRM_ACL_API::EDIT, $id, NULL,
312 'civicrm_saved_search', $allGroups
313 )
314 ) {
315 $permissions[] = CRM_Core_Permission::EDIT;
316 }
317
318 if (CRM_Core_Permission::check('view all contacts') ||
319 CRM_ACL_API::groupPermission(CRM_ACL_API::VIEW, $id, NULL,
320 'civicrm_saved_search', $allGroups
321 )
322 ) {
323 $permissions[] = CRM_Core_Permission::VIEW;
324 }
325
326 if (!empty($permissions) && CRM_Core_Permission::check('delete contacts')) {
327 // Note: using !empty() in if condition, restricts the scope of delete
328 // permission to groups/contacts that are editable/viewable.
329 // We can remove this !empty condition once we have ACL support for delete functionality.
330 $permissions[] = CRM_Core_Permission::DELETE;
331 }
332
333 return $permissions;
334 }
335
336 /**
337 * Create a new group.
338 *
339 * @param array $params
340 *
341 * @return CRM_Contact_BAO_Group|NULL
342 * The new group BAO (if created)
343 */
344 public static function create(&$params) {
345
346 if (!empty($params['id'])) {
347 CRM_Utils_Hook::pre('edit', 'Group', $params['id'], $params);
348 }
349 else {
350 CRM_Utils_Hook::pre('create', 'Group', NULL, $params);
351 }
352
353 // form the name only if missing: CRM-627
354 $nameParam = CRM_Utils_Array::value('name', $params, NULL);
355 if (!$nameParam && empty($params['id'])) {
356 $params['name'] = CRM_Utils_String::titleToVar($params['title']);
357 }
358
359 if (!empty($params['parents'])) {
360 $params['parents'] = CRM_Utils_Array::convertCheckboxFormatToArray((array) $params['parents']);
361 }
362
363 // convert params if array type
364 if (isset($params['group_type'])) {
365 $params['group_type'] = CRM_Utils_Array::convertCheckboxFormatToArray((array) $params['group_type']);
366 }
367 else {
368 $params['group_type'] = NULL;
369 }
370
371 $session = CRM_Core_Session::singleton();
372 $cid = $session->get('userID');
373 // this action is add
374 if ($cid && empty($params['id'])) {
375 $params['created_id'] = $cid;
376 }
377 // this action is update
378 if ($cid && !empty($params['id'])) {
379 $params['modified_id'] = $cid;
380 }
381
382 // CRM-19068.
383 // Validate parents parameter when creating group.
384 if (!empty($params['parents'])) {
385 $parents = is_array($params['parents']) ? array_keys($params['parents']) : (array) $params['parents'];
386 foreach ($parents as $parent) {
387 CRM_Utils_Type::validate($parent, 'Integer');
388 }
389 }
390 $group = new CRM_Contact_BAO_Group();
391 $group->copyValues($params, TRUE);
392
393 if (empty($params['id']) &&
394 !$nameParam
395 ) {
396 $group->name .= "_tmp";
397 }
398 $group->save();
399
400 if (!$group->id) {
401 return NULL;
402 }
403
404 if (empty($params['id']) &&
405 !$nameParam
406 ) {
407 $group->name = substr($group->name, 0, -4) . "_{$group->id}";
408 }
409
410 $group->buildClause();
411 $group->save();
412
413 // add custom field values
414 if (!empty($params['custom'])) {
415 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_group', $group->id);
416 }
417
418 // make the group, child of domain/site group by default.
419 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
420 if (CRM_Utils_Array::value('no_parent', $params) !== 1) {
421 if (empty($params['parents']) &&
422 $domainGroupID != $group->id &&
423 Civi::settings()->get('is_enabled') &&
424 !CRM_Contact_BAO_GroupNesting::hasParentGroups($group->id)
425 ) {
426 // if no parent present and the group doesn't already have any parents,
427 // make sure site group goes as parent
428 $params['parents'] = array($domainGroupID);
429 }
430
431 if (!empty($params['parents'])) {
432 foreach ($params['parents'] as $parentId) {
433 if ($parentId && !CRM_Contact_BAO_GroupNesting::isParentChild($parentId, $group->id)) {
434 CRM_Contact_BAO_GroupNesting::add($parentId, $group->id);
435 }
436 }
437 }
438
439 // this is always required, since we don't know when a
440 // parent group is removed
441 CRM_Contact_BAO_GroupNestingCache::update();
442
443 // update group contact cache for all parent groups
444 $parentIds = CRM_Contact_BAO_GroupNesting::getParentGroupIds($group->id);
445 foreach ($parentIds as $parentId) {
446 CRM_Contact_BAO_GroupContactCache::add($parentId);
447 }
448 }
449
450 if (!empty($params['organization_id'])) {
451 // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table
452 $groupOrg = [
453 'group_id' => $group->id,
454 'organization_id' => $params['organization_id'],
455 ];
456 CRM_Contact_BAO_GroupOrganization::add($groupOrg);
457 }
458
459 self::flushCaches();
460 CRM_Contact_BAO_GroupContactCache::add($group->id);
461
462 if (!empty($params['id'])) {
463 CRM_Utils_Hook::post('edit', 'Group', $group->id, $group);
464 }
465 else {
466 CRM_Utils_Hook::post('create', 'Group', $group->id, $group);
467 }
468
469 $recentOther = array();
470 if (CRM_Core_Permission::check('edit groups')) {
471 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=update&id=' . $group->id);
472 // currently same permission we are using for delete a group
473 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id);
474 }
475
476 // add the recently added group (unless hidden: CRM-6432)
477 if (!$group->is_hidden) {
478 CRM_Utils_Recent::add($group->title,
479 CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id),
480 $group->id,
481 'Group',
482 NULL,
483 NULL,
484 $recentOther
485 );
486 }
487 return $group;
488 }
489
490 /**
491 * Given a saved search compute the clause and the tables
492 * and store it for future use
493 */
494 public function buildClause() {
495 $params = array(array('group', 'IN', array($this->id), 0, 0));
496
497 if (!empty($params)) {
498 $tables = $whereTables = array();
499 $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
500 if (!empty($tables)) {
501 $this->select_tables = serialize($tables);
502 }
503 if (!empty($whereTables)) {
504 $this->where_tables = serialize($whereTables);
505 }
506 }
507 }
508
509 /**
510 * Defines a new smart group.
511 *
512 * @param array $params
513 * Associative array of parameters.
514 *
515 * @return CRM_Contact_BAO_Group|NULL
516 * The new group BAO (if created)
517 */
518 public static function createSmartGroup(&$params) {
519 if (!empty($params['formValues'])) {
520 $ssParams = $params;
521 unset($ssParams['id']);
522 if (isset($ssParams['saved_search_id'])) {
523 $ssParams['id'] = $ssParams['saved_search_id'];
524 }
525
526 $savedSearch = CRM_Contact_BAO_SavedSearch::create($params);
527
528 $params['saved_search_id'] = $savedSearch->id;
529 }
530 else {
531 return NULL;
532 }
533
534 return self::create($params);
535 }
536
537 /**
538 * Update the is_active flag in the db.
539 *
540 * @param int $id
541 * Id of the database record.
542 * @param bool $isActive
543 * Value we want to set the is_active field.
544 *
545 * @return bool
546 * true if we found and updated the object, else false
547 */
548 public static function setIsActive($id, $isActive) {
549 return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
550 }
551
552 /**
553 * Build the condition to retrieve groups.
554 *
555 * @param string $groupType
556 * Type of group(Access/Mailing) OR the key of the group.
557 * @param bool $excludeHidden exclude hidden groups.
558 *
559 * @return string
560 */
561 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
562 $value = NULL;
563 if ($groupType == 'Mailing') {
564 $value = CRM_Core_DAO::VALUE_SEPARATOR . '2' . CRM_Core_DAO::VALUE_SEPARATOR;
565 }
566 elseif ($groupType == 'Access') {
567 $value = CRM_Core_DAO::VALUE_SEPARATOR . '1' . CRM_Core_DAO::VALUE_SEPARATOR;
568 }
569 elseif (!empty($groupType)) {
570 // ie we have been given the group key
571 $value = CRM_Core_DAO::VALUE_SEPARATOR . $groupType . CRM_Core_DAO::VALUE_SEPARATOR;
572 }
573
574 $condition = NULL;
575 if ($excludeHidden) {
576 $condition = "is_hidden = 0";
577 }
578
579 if ($value) {
580 if ($condition) {
581 $condition .= " AND group_type LIKE '%$value%'";
582 }
583 else {
584 $condition = "group_type LIKE '%$value%'";
585 }
586 }
587
588 return $condition;
589 }
590
591 /**
592 * Get permission relevant clauses.
593 *
594 * @return array
595 */
596 public static function getPermissionClause() {
597 if (!isset(Civi::$statics[__CLASS__]['permission_clause'])) {
598 if (CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts')) {
599 $clause = 1;
600 }
601 else {
602 //get the allowed groups for the current user
603 $groups = CRM_ACL_API::group(CRM_ACL_API::VIEW);
604 if (!empty($groups)) {
605 $groupList = implode(', ', array_values($groups));
606 $clause = "groups.id IN ( $groupList ) ";
607 }
608 else {
609 $clause = '1 = 0';
610 }
611 }
612 Civi::$statics[__CLASS__]['permission_clause'] = $clause;
613 }
614 return Civi::$statics[__CLASS__]['permission_clause'];
615 }
616
617 /**
618 * Flush caches that hold group data.
619 *
620 * (Actually probably some overkill at the moment.)
621 */
622 protected static function flushCaches() {
623 CRM_Utils_System::flushCache();
624 $staticCaches = array(
625 'CRM_Core_PseudoConstant' => 'groups',
626 'CRM_ACL_API' => 'group_permission',
627 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
628 'CRM_Contact_BAO_Group' => 'permission_clause',
629 );
630 foreach ($staticCaches as $class => $key) {
631 if (isset(Civi::$statics[$class][$key])) {
632 unset(Civi::$statics[$class][$key]);
633 }
634 }
635 }
636
637 /**
638 * @return string
639 */
640 public function __toString() {
641 return $this->title;
642 }
643
644 /**
645 * This function create the hidden smart group when user perform
646 * contact search and want to send mailing to search contacts.
647 *
648 * @param array $params
649 * ( reference ) an assoc array of name/value pairs.
650 *
651 * @return array
652 * ( smartGroupId, ssId ) smart group id and saved search id
653 */
654 public static function createHiddenSmartGroup($params) {
655 $ssId = CRM_Utils_Array::value('saved_search_id', $params);
656
657 //add mapping record only for search builder saved search
658 $mappingId = NULL;
659 if ($params['search_context'] == 'builder') {
660 //save the mapping for search builder
661 if (!$ssId) {
662 //save record in mapping table
663 $mappingParams = array(
664 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
665 );
666 $mapping = CRM_Core_BAO_Mapping::add($mappingParams);
667 $mappingId = $mapping->id;
668 }
669 else {
670 //get the mapping id from saved search
671 $savedSearch = new CRM_Contact_BAO_SavedSearch();
672 $savedSearch->id = $ssId;
673 $savedSearch->find(TRUE);
674 $mappingId = $savedSearch->mapping_id;
675 }
676
677 //save mapping fields
678 CRM_Core_BAO_Mapping::saveMappingFields($params['form_values'], $mappingId);
679 }
680
681 //create/update saved search record.
682 $savedSearch = new CRM_Contact_BAO_SavedSearch();
683 $savedSearch->id = $ssId;
684 $savedSearch->form_values = serialize(CRM_Contact_BAO_Query::convertFormValues($params['form_values']));
685 $savedSearch->mapping_id = $mappingId;
686 $savedSearch->search_custom_id = CRM_Utils_Array::value('search_custom_id', $params);
687 $savedSearch->save();
688
689 $ssId = $savedSearch->id;
690 if (!$ssId) {
691 return NULL;
692 }
693
694 $smartGroupId = NULL;
695 if (!empty($params['saved_search_id'])) {
696 $smartGroupId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
697 }
698 else {
699 //create group only when new saved search.
700 $groupParams = array(
701 'title' => "Hidden Smart Group {$ssId}",
702 'is_active' => CRM_Utils_Array::value('is_active', $params, 1),
703 'is_hidden' => CRM_Utils_Array::value('is_hidden', $params, 1),
704 'group_type' => CRM_Utils_Array::value('group_type', $params),
705 'visibility' => CRM_Utils_Array::value('visibility', $params),
706 'saved_search_id' => $ssId,
707 );
708
709 $smartGroup = self::create($groupParams);
710 $smartGroupId = $smartGroup->id;
711 }
712
713 // Update mapping with the name and description of the hidden smart group.
714 if ($mappingId) {
715 $mappingParams = array(
716 'id' => $mappingId,
717 'name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
718 'description' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
719 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
720 );
721 CRM_Core_BAO_Mapping::add($mappingParams);
722 }
723
724 return array($smartGroupId, $ssId);
725 }
726
727 /**
728 * wrapper for ajax group selector.
729 *
730 * @param array $params
731 * Associated array for params record id.
732 *
733 * @return array
734 * associated array of group list
735 * -rp = rowcount
736 * -page= offset
737 * @todo there seems little reason for the small number of functions that call this to pass in
738 * params that then need to be translated in this function since they are coding them when calling
739 */
740 static public function getGroupListSelector(&$params) {
741 // format the params
742 $params['offset'] = ($params['page'] - 1) * $params['rp'];
743 $params['rowCount'] = $params['rp'];
744 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
745
746 // get groups
747 $groups = CRM_Contact_BAO_Group::getGroupList($params);
748
749 //skip total if we are making call to show only children
750 if (empty($params['parent_id'])) {
751 // add total
752 $params['total'] = CRM_Contact_BAO_Group::getGroupCount($params);
753
754 // get all the groups
755 $allGroups = CRM_Core_PseudoConstant::allGroup();
756 }
757
758 // format params and add links
759 $groupList = array();
760 foreach ($groups as $id => $value) {
761 $group = array();
762 $group['group_id'] = $value['id'];
763 $group['count'] = $value['count'];
764 $group['title'] = $value['title'];
765
766 // append parent names if in search mode
767 if (empty($params['parent_id']) && !empty($value['parents'])) {
768 $group['parent_id'] = $value['parents'];
769 $groupIds = explode(',', $value['parents']);
770 $title = array();
771 foreach ($groupIds as $gId) {
772 $title[] = $allGroups[$gId];
773 }
774 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
775 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
776 }
777 $group['DT_RowId'] = 'row_' . $value['id'];
778 if (empty($params['parentsOnly'])) {
779 foreach ($value['class'] as $id => $class) {
780 if ($class == 'crm-group-parent') {
781 unset($value['class'][$id]);
782 }
783 }
784 }
785 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
786 $group['DT_RowAttr'] = array();
787 $group['DT_RowAttr']['data-id'] = $value['id'];
788 $group['DT_RowAttr']['data-entity'] = 'group';
789
790 $group['description'] = CRM_Utils_Array::value('description', $value);
791
792 if (!empty($value['group_type'])) {
793 $group['group_type'] = $value['group_type'];
794 }
795 else {
796 $group['group_type'] = '';
797 }
798
799 $group['visibility'] = $value['visibility'];
800 $group['links'] = $value['action'];
801 $group['org_info'] = CRM_Utils_Array::value('org_info', $value);
802 $group['created_by'] = CRM_Utils_Array::value('created_by', $value);
803
804 $group['is_parent'] = $value['is_parent'];
805
806 array_push($groupList, $group);
807 }
808
809 $groupsDT = array();
810 $groupsDT['data'] = $groupList;
811 $groupsDT['recordsTotal'] = !empty($params['total']) ? $params['total'] : NULL;
812 $groupsDT['recordsFiltered'] = !empty($params['total']) ? $params['total'] : NULL;
813
814 return $groupsDT;
815 }
816
817 /**
818 * This function to get list of groups.
819 *
820 * @param array $params
821 * Associated array for params.
822 *
823 * @return array
824 */
825 public static function getGroupList(&$params) {
826 $whereClause = self::whereClause($params, FALSE);
827
828 $limit = "";
829 if (!empty($params['rowCount']) &&
830 $params['rowCount'] > 0
831 ) {
832 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
833 }
834
835 $orderBy = ' ORDER BY groups.title asc';
836 if (!empty($params['sort'])) {
837 $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
838
839 // CRM-16905 - Sort by count cannot be done with sql
840 if (strpos($params['sort'], 'count') === 0) {
841 $orderBy = $limit = '';
842 }
843 }
844
845 $select = $from = $where = "";
846 $groupOrg = FALSE;
847 if (CRM_Core_Permission::check('administer Multiple Organizations') &&
848 CRM_Core_Permission::isMultisiteEnabled()
849 ) {
850 $select = ", contact.display_name as org_name, contact.id as org_id";
851 $from = " LEFT JOIN civicrm_group_organization gOrg
852 ON gOrg.group_id = groups.id
853 LEFT JOIN civicrm_contact contact
854 ON contact.id = gOrg.organization_id ";
855
856 //get the Organization ID
857 $orgID = CRM_Utils_Request::retrieve('oid', 'Positive');
858 if ($orgID) {
859 $where = " AND gOrg.organization_id = {$orgID}";
860 }
861
862 $groupOrg = TRUE;
863 }
864
865 $query = "
866 SELECT groups.*, createdBy.sort_name as created_by {$select}
867 FROM civicrm_group groups
868 LEFT JOIN civicrm_contact createdBy
869 ON createdBy.id = groups.created_id
870 {$from}
871 WHERE $whereClause {$where}
872 {$orderBy}
873 {$limit}";
874
875 $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
876
877 //FIXME CRM-4418, now we are handling delete separately
878 //if we introduce 'delete for group' make sure to handle here.
879 $groupPermissions = array(CRM_Core_Permission::VIEW);
880 if (CRM_Core_Permission::check('edit groups')) {
881 $groupPermissions[] = CRM_Core_Permission::EDIT;
882 $groupPermissions[] = CRM_Core_Permission::DELETE;
883 }
884
885 // CRM-9936
886 $reservedPermission = CRM_Core_Permission::check('administer reserved groups');
887
888 $links = self::actionLinks($params);
889
890 $allTypes = CRM_Core_OptionGroup::values('group_type');
891 $values = array();
892
893 $visibility = CRM_Core_SelectValues::ufVisibility();
894
895 while ($object->fetch()) {
896 $newLinks = $links;
897 $values[$object->id] = array(
898 'class' => array(),
899 'count' => '0',
900 );
901 CRM_Core_DAO::storeValues($object, $values[$object->id]);
902
903 if ($object->saved_search_id) {
904 $values[$object->id]['title'] .= ' (' . ts('Smart Group') . ')';
905 // check if custom search, if so fix view link
906 $customSearchID = CRM_Core_DAO::getFieldValue(
907 'CRM_Contact_DAO_SavedSearch',
908 $object->saved_search_id,
909 'search_custom_id'
910 );
911
912 if ($customSearchID) {
913 $newLinks[CRM_Core_Action::VIEW]['url'] = 'civicrm/contact/search/custom';
914 $newLinks[CRM_Core_Action::VIEW]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
915 }
916 }
917
918 $action = array_sum(array_keys($newLinks));
919
920 // CRM-9936
921 if (array_key_exists('is_reserved', $object)) {
922 //if group is reserved and I don't have reserved permission, suppress delete/edit
923 if ($object->is_reserved && !$reservedPermission) {
924 $action -= CRM_Core_Action::DELETE;
925 $action -= CRM_Core_Action::UPDATE;
926 $action -= CRM_Core_Action::DISABLE;
927 }
928 }
929
930 if (array_key_exists('is_active', $object)) {
931 if ($object->is_active) {
932 $action -= CRM_Core_Action::ENABLE;
933 }
934 else {
935 $values[$object->id]['class'][] = 'disabled';
936 $action -= CRM_Core_Action::VIEW;
937 $action -= CRM_Core_Action::DISABLE;
938 }
939 }
940
941 $action = $action & CRM_Core_Action::mask($groupPermissions);
942
943 $values[$object->id]['visibility'] = $visibility[$values[$object->id]['visibility']];
944
945 if (isset($values[$object->id]['group_type'])) {
946 $groupTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
947 substr($values[$object->id]['group_type'], 1, -1)
948 );
949 $types = array();
950 foreach ($groupTypes as $type) {
951 $types[] = CRM_Utils_Array::value($type, $allTypes);
952 }
953 $values[$object->id]['group_type'] = implode(', ', $types);
954 }
955 $values[$object->id]['action'] = CRM_Core_Action::formLink($newLinks,
956 $action,
957 array(
958 'id' => $object->id,
959 'ssid' => $object->saved_search_id,
960 ),
961 ts('more'),
962 FALSE,
963 'group.selector.row',
964 'Group',
965 $object->id
966 );
967
968 // If group has children, add class for link to view children
969 $values[$object->id]['is_parent'] = FALSE;
970 if (array_key_exists('children', $values[$object->id])) {
971 $values[$object->id]['class'][] = "crm-group-parent";
972 $values[$object->id]['is_parent'] = TRUE;
973 }
974
975 // If group is a child, add child class
976 if (array_key_exists('parents', $values[$object->id])) {
977 $values[$object->id]['class'][] = "crm-group-child";
978 }
979
980 if ($groupOrg) {
981 if ($object->org_id) {
982 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
983 $values[$object->id]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
984 }
985 else {
986 $values[$object->id]['org_info'] = ''; // Empty cell
987 }
988 }
989 else {
990 $values[$object->id]['org_info'] = NULL; // Collapsed column if all cells are NULL
991 }
992 if ($object->created_id) {
993 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
994 $values[$object->id]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
995 }
996
997 // By default, we try to get a count of the contacts in each group
998 // to display to the user on the Manage Group page. However, if
999 // that will result in the cache being regenerated, then dipslay
1000 // "unknown" instead to avoid a long wait for the user.
1001 if (CRM_Contact_BAO_GroupContactCache::shouldGroupBeRefreshed($object->id)) {
1002 $values[$object->id]['count'] = ts('unknown');
1003 }
1004 else {
1005 $values[$object->id]['count'] = civicrm_api3('Contact', 'getcount', array('group' => $object->id));
1006 }
1007 }
1008
1009 // CRM-16905 - Sort by count cannot be done with sql
1010 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1011 usort($values, function($a, $b) {
1012 return $a['count'] - $b['count'];
1013 });
1014 if (strpos($params['sort'], 'desc')) {
1015 $values = array_reverse($values, TRUE);
1016 }
1017 return array_slice($values, $params['offset'], $params['rowCount']);
1018 }
1019
1020 return $values;
1021 }
1022
1023 /**
1024 * This function to get hierarchical list of groups (parent followed by children)
1025 *
1026 * @param array $groupIDs
1027 * Array of group ids.
1028 *
1029 * @param NULL $parents
1030 * @param string $spacer
1031 * @param bool $titleOnly
1032 *
1033 * @return array
1034 */
1035 public static function getGroupsHierarchy(
1036 $groupIDs,
1037 $parents = NULL,
1038 $spacer = '<span class="child-indent"></span>',
1039 $titleOnly = FALSE
1040 ) {
1041 if (empty($groupIDs)) {
1042 return array();
1043 }
1044
1045 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1046 // <span class="child-icon"></span>
1047 // need to return id, title (w/ spacer), description, visibility
1048
1049 // We need to build a list of tags ordered by hierarchy and sorted by
1050 // name. The hierarchy will be communicated by an accumulation of
1051 // separators in front of the name to give it a visual offset.
1052 // Instead of recursively making mysql queries, we'll make one big
1053 // query and build the hierarchy with the algorithm below.
1054 $groups = array();
1055 $args = array(1 => array($groupIdString, 'String'));
1056 $query = "
1057 SELECT id, title, description, visibility, parents
1058 FROM civicrm_group
1059 WHERE id IN $groupIdString
1060 ";
1061 if ($parents) {
1062 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
1063 $parentArray = explode(',', $parents);
1064 $parent = self::filterActiveGroups($parentArray);
1065 $args[2] = array($parent, 'Integer');
1066 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1067 }
1068 $query .= " ORDER BY title";
1069 $dao = CRM_Core_DAO::executeQuery($query, $args);
1070
1071 // Sort the groups into the correct storage by the parent
1072 // $roots represent the current leaf nodes that need to be checked for
1073 // children. $rows represent the unplaced nodes
1074 // $tree contains the child nodes based on their parent_id.
1075 $roots = array();
1076 $tree = array();
1077 while ($dao->fetch()) {
1078 if ($dao->parents) {
1079 $parentArray = explode(',', $dao->parents);
1080 $parent = self::filterActiveGroups($parentArray);
1081 $tree[$parent][] = array(
1082 'id' => $dao->id,
1083 'title' => $dao->title,
1084 'visibility' => $dao->visibility,
1085 'description' => $dao->description,
1086 );
1087 }
1088 else {
1089 $roots[] = array(
1090 'id' => $dao->id,
1091 'title' => $dao->title,
1092 'visibility' => $dao->visibility,
1093 'description' => $dao->description,
1094 );
1095 }
1096 }
1097 $dao->free();
1098
1099 $hierarchy = array();
1100 for ($i = 0; $i < count($roots); $i++) {
1101 self::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1102 }
1103 return $hierarchy;
1104 }
1105
1106 /**
1107 * Build a list with groups on alphabetical order and child groups after the parent group.
1108 *
1109 * This is a recursive function filling the $hierarchy parameter.
1110 *
1111 * @param $hierarchy
1112 * @param $group
1113 * @param $tree
1114 * @param $titleOnly
1115 * @param $spacer
1116 * @param $level
1117 */
1118 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1119 $spaces = str_repeat($spacer, $level);
1120
1121 if ($titleOnly) {
1122 $hierarchy[$group['id']] = $spaces . $group['title'];
1123 }
1124 else {
1125 $hierarchy[$group['id']] = array(
1126 'title' => $spaces . $group['title'],
1127 'description' => $group['description'],
1128 'visibility' => $group['visibility'],
1129 );
1130 }
1131
1132 // For performance reasons we use a for loop rather than a foreach.
1133 // Metrics for performance in an installation with 2867 groups a foreach
1134 // caused the function getGroupsHierarchy with a foreach execution takes
1135 // around 2.2 seoonds (2,200 ms).
1136 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1137 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1138 for ($i = 0; $i < count($tree[$group['id']]); $i++) {
1139 self::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level + 1);
1140 }
1141 }
1142 }
1143
1144 /**
1145 * @param array $params
1146 *
1147 * @return NULL|string
1148 */
1149 public static function getGroupCount(&$params) {
1150 $whereClause = self::whereClause($params, FALSE);
1151 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1152
1153 if (!empty($params['created_by'])) {
1154 $query .= "
1155 INNER JOIN civicrm_contact createdBy
1156 ON createdBy.id = groups.created_id";
1157 }
1158 $query .= "
1159 WHERE {$whereClause}";
1160 return CRM_Core_DAO::singleValueQuery($query, $params);
1161 }
1162
1163 /**
1164 * Generate permissioned where clause for group search.
1165 * @param array $params
1166 * @param bool $sortBy
1167 * @param bool $excludeHidden
1168 *
1169 * @return string
1170 */
1171 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1172 $values = array();
1173 $title = CRM_Utils_Array::value('title', $params);
1174 if ($title) {
1175 $clauses[] = "groups.title LIKE %1";
1176 if (strpos($title, '%') !== FALSE) {
1177 $params[1] = array($title, 'String', FALSE);
1178 }
1179 else {
1180 $params[1] = array($title, 'String', TRUE);
1181 }
1182 }
1183
1184 $groupType = CRM_Utils_Array::value('group_type', $params);
1185 if ($groupType) {
1186 $types = explode(',', $groupType);
1187 if (!empty($types)) {
1188 $clauses[] = 'groups.group_type LIKE %2';
1189 $typeString = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $types) . CRM_Core_DAO::VALUE_SEPARATOR;
1190 $params[2] = array($typeString, 'String', TRUE);
1191 }
1192 }
1193
1194 $visibility = CRM_Utils_Array::value('visibility', $params);
1195 if ($visibility) {
1196 $clauses[] = 'groups.visibility = %3';
1197 $params[3] = array($visibility, 'String');
1198 }
1199
1200 $groupStatus = CRM_Utils_Array::value('status', $params);
1201 if ($groupStatus) {
1202 switch ($groupStatus) {
1203 case 1:
1204 $clauses[] = 'groups.is_active = 1';
1205 $params[4] = array($groupStatus, 'Integer');
1206 break;
1207
1208 case 2:
1209 $clauses[] = 'groups.is_active = 0';
1210 $params[4] = array($groupStatus, 'Integer');
1211 break;
1212
1213 case 3:
1214 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1215 break;
1216 }
1217 }
1218
1219 $parentsOnly = CRM_Utils_Array::value('parentsOnly', $params);
1220 if ($parentsOnly) {
1221 $clauses[] = 'groups.parents IS NULL';
1222 }
1223
1224 // only show child groups of a specific parent group
1225 $parent_id = CRM_Utils_Array::value('parent_id', $params);
1226 if ($parent_id) {
1227 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1228 $params[5] = array($parent_id, 'Integer');
1229 }
1230
1231 if ($createdBy = CRM_Utils_Array::value('created_by', $params)) {
1232 $clauses[] = "createdBy.sort_name LIKE %6";
1233 if (strpos($createdBy, '%') !== FALSE) {
1234 $params[6] = array($createdBy, 'String', FALSE);
1235 }
1236 else {
1237 $params[6] = array($createdBy, 'String', TRUE);
1238 }
1239 }
1240
1241 if (empty($clauses)) {
1242 $clauses[] = 'groups.is_active = 1';
1243 }
1244
1245 if ($excludeHidden) {
1246 $clauses[] = 'groups.is_hidden = 0';
1247 }
1248
1249 $clauses[] = self::getPermissionClause();
1250
1251 return implode(' AND ', $clauses);
1252 }
1253
1254 /**
1255 * Define action links.
1256 *
1257 * @return array
1258 * array of action links
1259 */
1260 public static function actionLinks($params) {
1261 // If component_mode is set we change the "View" link to match the requested component type
1262 if (!isset($params['component_mode'])) {
1263 $params['component_mode'] = CRM_Contact_BAO_Query::MODE_CONTACTS;
1264 }
1265 $modeValue = CRM_Contact_Form_Search::getModeValue($params['component_mode']);
1266 $links = array(
1267 CRM_Core_Action::VIEW => array(
1268 'name' => $modeValue['selectorLabel'],
1269 'url' => 'civicrm/group/search',
1270 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
1271 'title' => ts('Group Contacts'),
1272 ),
1273 CRM_Core_Action::UPDATE => array(
1274 'name' => ts('Settings'),
1275 'url' => 'civicrm/group',
1276 'qs' => 'reset=1&action=update&id=%%id%%',
1277 'title' => ts('Edit Group'),
1278 ),
1279 CRM_Core_Action::DISABLE => array(
1280 'name' => ts('Disable'),
1281 'ref' => 'crm-enable-disable',
1282 'title' => ts('Disable Group'),
1283 ),
1284 CRM_Core_Action::ENABLE => array(
1285 'name' => ts('Enable'),
1286 'ref' => 'crm-enable-disable',
1287 'title' => ts('Enable Group'),
1288 ),
1289 CRM_Core_Action::DELETE => array(
1290 'name' => ts('Delete'),
1291 'url' => 'civicrm/group',
1292 'qs' => 'reset=1&action=delete&id=%%id%%',
1293 'title' => ts('Delete Group'),
1294 ),
1295 );
1296
1297 return $links;
1298 }
1299
1300 /**
1301 * @param $whereClause
1302 * @param array $whereParams
1303 *
1304 * @return string
1305 */
1306 public function pagerAtoZ($whereClause, $whereParams) {
1307 $query = "
1308 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1309 FROM civicrm_group groups
1310 WHERE $whereClause
1311 ORDER BY LEFT(groups.title, 1)
1312 ";
1313 $dao = CRM_Core_DAO::executeQuery($query, $whereParams);
1314
1315 return CRM_Utils_PagerAToZ::getAToZBar($dao, $this->_sortByCharacter, TRUE);
1316 }
1317
1318 /**
1319 * Assign Test Value.
1320 *
1321 * @param string $fieldName
1322 * @param array $fieldDef
1323 * @param int $counter
1324 */
1325 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1326 if ($fieldName == 'children' || $fieldName == 'parents') {
1327 $this->{$fieldName} = "NULL";
1328 }
1329 else {
1330 parent::assignTestValues($fieldName, $fieldDef, $counter);
1331 }
1332 }
1333
1334 /**
1335 * Get child group ids
1336 *
1337 * @param array $regularGroupIDs
1338 * Parent Group IDs
1339 *
1340 * @return array
1341 */
1342 public static function getChildGroupIds($regularGroupIDs) {
1343 $childGroupIDs = array();
1344
1345 foreach ((array) $regularGroupIDs as $regularGroupID) {
1346 // temporary store the child group ID(s) of regular group identified by $id,
1347 // later merge with main child group array
1348 $tempChildGroupIDs = array();
1349 // check that the regular group has any child group, if not then continue
1350 if ($childrenFound = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1351 $tempChildGroupIDs[] = $childrenFound;
1352 }
1353 else {
1354 continue;
1355 }
1356 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1357 // so we need to convert it into array of child group IDs first
1358 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1359 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1360 // recursively fetch the child group IDs
1361 while (count($tempChildGroupIDs)) {
1362 $tempChildGroupIDs = self::getChildGroupIds($tempChildGroupIDs);
1363 if (count($tempChildGroupIDs)) {
1364 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1365 }
1366 }
1367 }
1368
1369 return $childGroupIDs;
1370 }
1371
1372 /**
1373 * Check parent groups and filter out the disabled ones.
1374 *
1375 * @param array $parentArray
1376 * Array of group Ids.
1377 *
1378 * @return int
1379 */
1380 public static function filterActiveGroups($parentArray) {
1381 if (count($parentArray) > 1) {
1382 $result = civicrm_api3('Group', 'get', array(
1383 'id' => array('IN' => $parentArray),
1384 'is_active' => TRUE,
1385 'return' => 'id',
1386 ));
1387 $activeParentGroupIDs = CRM_Utils_Array::collect('id', $result['values']);
1388 foreach ($parentArray as $key => $groupID) {
1389 if (!array_key_exists($groupID, $activeParentGroupIDs)) {
1390 unset($parentArray[$key]);
1391 }
1392 }
1393 }
1394
1395 return reset($parentArray);
1396 }
1397
1398 }