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