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