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