Merge pull request #23581 from colemanw/removeUnused
[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 if ($params['organization_id'] == 'null') {
457 $groupOrganization = [];
458 CRM_Contact_BAO_GroupOrganization::retrieve($group->id, $groupOrganization);
459 if (!empty($groupOrganization['group_organization'])) {
460 CRM_Contact_BAO_GroupOrganization::deleteGroupOrganization($groupOrganization['group_organization']);
461 }
462 }
463 else {
464 // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table
465 $groupOrg = [
466 'group_id' => $group->id,
467 'organization_id' => $params['organization_id'],
468 ];
469 CRM_Contact_BAO_GroupOrganization::add($groupOrg);
470 }
471 }
472
473 self::flushCaches();
474 CRM_Contact_BAO_GroupContactCache::invalidateGroupContactCache($group->id);
475
476 CRM_Utils_Hook::post($hook, 'Group', $group->id, $group);
477
478 $recentOther = [];
479 if (CRM_Core_Permission::check('edit groups')) {
480 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=update&id=' . $group->id);
481 // currently same permission we are using for delete a group
482 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id);
483 }
484
485 // add the recently added group (unless hidden: CRM-6432)
486 if (!$group->is_hidden) {
487 CRM_Utils_Recent::add($group->title,
488 CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id),
489 $group->id,
490 'Group',
491 NULL,
492 NULL,
493 $recentOther
494 );
495 }
496 return $group;
497 }
498
499 /**
500 * Takes a sloppy mismash of params and creates two entities: a Group and a SavedSearch
501 * Currently only used by unit tests.
502 *
503 * @param array $params
504 * @return CRM_Contact_BAO_Group|NULL
505 * @deprecated
506 */
507 public static function createSmartGroup($params) {
508 if (!empty($params['formValues'])) {
509 $ssParams = $params;
510 // Remove group parameters from sloppy mismash
511 unset($ssParams['id'], $ssParams['name'], $ssParams['title'], $ssParams['formValues'], $ssParams['saved_search_id']);
512 if (isset($params['saved_search_id'])) {
513 $ssParams['id'] = $params['saved_search_id'];
514 }
515 $ssParams['form_values'] = $params['formValues'];
516 $savedSearch = CRM_Contact_BAO_SavedSearch::create($ssParams);
517
518 $params['saved_search_id'] = $savedSearch->id;
519 }
520 else {
521 return NULL;
522 }
523
524 return self::create($params);
525 }
526
527 /**
528 * Update the is_active flag in the db.
529 *
530 * @param int $id
531 * Id of the database record.
532 * @param bool $isActive
533 * Value we want to set the is_active field.
534 *
535 * @return bool
536 * true if we found and updated the object, else false
537 */
538 public static function setIsActive($id, $isActive) {
539 return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
540 }
541
542 /**
543 * Build the condition to retrieve groups.
544 *
545 * @param string $groupType
546 * Type of group(Access/Mailing) OR the key of the group.
547 * @param bool $excludeHidden exclude hidden groups.
548 *
549 * @return string
550 */
551 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
552 $value = NULL;
553 if ($groupType == 'Mailing') {
554 $value = CRM_Core_DAO::VALUE_SEPARATOR . '2' . CRM_Core_DAO::VALUE_SEPARATOR;
555 }
556 elseif ($groupType == 'Access') {
557 $value = CRM_Core_DAO::VALUE_SEPARATOR . '1' . CRM_Core_DAO::VALUE_SEPARATOR;
558 }
559 elseif (!empty($groupType)) {
560 // ie we have been given the group key
561 $value = CRM_Core_DAO::VALUE_SEPARATOR . $groupType . CRM_Core_DAO::VALUE_SEPARATOR;
562 }
563
564 $condition = NULL;
565 if ($excludeHidden) {
566 $condition = "is_hidden = 0";
567 }
568
569 if ($value) {
570 if ($condition) {
571 $condition .= " AND group_type LIKE '%$value%'";
572 }
573 else {
574 $condition = "group_type LIKE '%$value%'";
575 }
576 }
577
578 return $condition;
579 }
580
581 /**
582 * Get permission relevant clauses.
583 *
584 * @return array
585 */
586 public static function getPermissionClause() {
587 if (!isset(Civi::$statics[__CLASS__]['permission_clause'])) {
588 if (CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts')) {
589 $clause = 1;
590 }
591 else {
592 //get the allowed groups for the current user
593 $groups = CRM_ACL_API::group(CRM_ACL_API::VIEW);
594 if (!empty($groups)) {
595 $groupList = implode(', ', array_values($groups));
596 $clause = "`groups`.id IN ( $groupList ) ";
597 }
598 else {
599 $clause = '1 = 0';
600 }
601 }
602 Civi::$statics[__CLASS__]['permission_clause'] = $clause;
603 }
604 return Civi::$statics[__CLASS__]['permission_clause'];
605 }
606
607 /**
608 * Flush caches that hold group data.
609 *
610 * (Actually probably some overkill at the moment.)
611 */
612 protected static function flushCaches() {
613 CRM_Utils_System::flushCache();
614 $staticCaches = [
615 'CRM_Core_PseudoConstant' => 'groups',
616 'CRM_ACL_API' => 'group_permission',
617 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
618 'CRM_Contact_BAO_Group' => 'permission_clause',
619 ];
620 foreach ($staticCaches as $class => $key) {
621 if (isset(Civi::$statics[$class][$key])) {
622 unset(Civi::$statics[$class][$key]);
623 }
624 }
625 }
626
627 /**
628 * @return string
629 */
630 public function __toString() {
631 return $this->title;
632 }
633
634 /**
635 * This function create the hidden smart group when user perform
636 * contact search and want to send mailing to search contacts.
637 *
638 * @param array $params
639 * ( reference ) an assoc array of name/value pairs.
640 *
641 * @return array
642 * ( smartGroupId, ssId ) smart group id and saved search id
643 */
644 public static function createHiddenSmartGroup($params) {
645 $ssId = $params['saved_search_id'] ?? NULL;
646
647 //add mapping record only for search builder saved search
648 $mappingId = NULL;
649 if ($params['search_context'] == 'builder') {
650 //save the mapping for search builder
651 if (!$ssId) {
652 //save record in mapping table
653 $mappingParams = [
654 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
655 ];
656 $mapping = CRM_Core_BAO_Mapping::add($mappingParams);
657 $mappingId = $mapping->id;
658 }
659 else {
660 //get the mapping id from saved search
661 $savedSearch = new CRM_Contact_BAO_SavedSearch();
662 $savedSearch->id = $ssId;
663 $savedSearch->find(TRUE);
664 $mappingId = $savedSearch->mapping_id;
665 }
666
667 //save mapping fields
668 CRM_Core_BAO_Mapping::saveMappingFields($params['form_values'], $mappingId);
669 }
670
671 //create/update saved search record.
672 $savedSearch = new CRM_Contact_BAO_SavedSearch();
673 $savedSearch->id = $ssId;
674 $formValues = $params['search_context'] === 'builder' ? $params['form_values'] : CRM_Contact_BAO_Query::convertFormValues($params['form_values']);
675 $savedSearch->form_values = serialize($formValues);
676 $savedSearch->mapping_id = $mappingId;
677 $savedSearch->search_custom_id = $params['search_custom_id'] ?? NULL;
678 $savedSearch->save();
679
680 $ssId = $savedSearch->id;
681 if (!$ssId) {
682 return NULL;
683 }
684
685 $smartGroupId = NULL;
686 if (!empty($params['saved_search_id'])) {
687 $smartGroupId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
688 }
689 else {
690 //create group only when new saved search.
691 $groupParams = [
692 'title' => "Hidden Smart Group {$ssId}",
693 'is_active' => CRM_Utils_Array::value('is_active', $params, 1),
694 'is_hidden' => CRM_Utils_Array::value('is_hidden', $params, 1),
695 'group_type' => $params['group_type'] ?? NULL,
696 'visibility' => $params['visibility'] ?? NULL,
697 'saved_search_id' => $ssId,
698 ];
699
700 $smartGroup = self::create($groupParams);
701 $smartGroupId = $smartGroup->id;
702 }
703
704 // Update mapping with the name and description of the hidden smart group.
705 if ($mappingId) {
706 $mappingParams = [
707 'id' => $mappingId,
708 'name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
709 'description' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
710 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
711 ];
712 CRM_Core_BAO_Mapping::add($mappingParams);
713 }
714
715 return [$smartGroupId, $ssId];
716 }
717
718 /**
719 * wrapper for ajax group selector.
720 *
721 * @param array $params
722 * Associated array for params record id.
723 *
724 * @return array
725 * associated array of group list
726 * -rp = rowcount
727 * -page= offset
728 * @todo there seems little reason for the small number of functions that call this to pass in
729 * params that then need to be translated in this function since they are coding them when calling
730 */
731 public static function getGroupListSelector(&$params) {
732 // format the params
733 $params['offset'] = ($params['page'] - 1) * $params['rp'];
734 $params['rowCount'] = $params['rp'];
735 $params['sort'] = $params['sortBy'] ?? NULL;
736
737 // get groups
738 $groups = CRM_Contact_BAO_Group::getGroupList($params);
739
740 //skip total if we are making call to show only children
741 if (empty($params['parent_id'])) {
742 // add total
743 $params['total'] = CRM_Contact_BAO_Group::getGroupCount($params);
744
745 // get all the groups
746 $allGroups = CRM_Core_PseudoConstant::allGroup();
747 }
748
749 // format params and add links
750 $groupList = [];
751 foreach ($groups as $id => $value) {
752 $group = [];
753 $group['group_id'] = $value['id'];
754 $group['count'] = $value['count'];
755 $group['title'] = $value['title'];
756
757 // append parent names if in search mode
758 if (empty($params['parent_id']) && !empty($value['parents'])) {
759 $group['parent_id'] = $value['parents'];
760 $groupIds = explode(',', $value['parents']);
761 $title = [];
762 foreach ($groupIds as $gId) {
763 $title[] = $allGroups[$gId];
764 }
765 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
766 $value['class'] = array_diff($value['class'], ['crm-row-parent']);
767 }
768 $group['DT_RowId'] = 'row_' . $value['id'];
769 if (empty($params['parentsOnly'])) {
770 foreach ($value['class'] as $id => $class) {
771 if ($class == 'crm-group-parent') {
772 unset($value['class'][$id]);
773 }
774 }
775 }
776 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
777 $group['DT_RowAttr'] = [];
778 $group['DT_RowAttr']['data-id'] = $value['id'];
779 $group['DT_RowAttr']['data-entity'] = 'group';
780
781 $group['description'] = $value['description'] ?? NULL;
782
783 if (!empty($value['group_type'])) {
784 $group['group_type'] = $value['group_type'];
785 }
786 else {
787 $group['group_type'] = '';
788 }
789
790 $group['visibility'] = $value['visibility'];
791 $group['links'] = $value['action'];
792 $group['org_info'] = $value['org_info'] ?? NULL;
793 $group['created_by'] = $value['created_by'] ?? NULL;
794
795 $group['is_parent'] = $value['is_parent'];
796
797 array_push($groupList, $group);
798 }
799
800 $groupsDT = [];
801 $groupsDT['data'] = $groupList;
802 $groupsDT['recordsTotal'] = !empty($params['total']) ? $params['total'] : NULL;
803 $groupsDT['recordsFiltered'] = !empty($params['total']) ? $params['total'] : NULL;
804
805 return $groupsDT;
806 }
807
808 /**
809 * This function to get list of groups.
810 *
811 * @param array $params
812 * Associated array for params.
813 *
814 * @return array
815 */
816 public static function getGroupList(&$params) {
817 $whereClause = self::whereClause($params, FALSE);
818
819 $limit = "";
820 if (!empty($params['rowCount']) &&
821 $params['rowCount'] > 0
822 ) {
823 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
824 }
825
826 $orderBy = ' ORDER BY `groups`.title asc';
827 if (!empty($params['sort'])) {
828 $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
829
830 // CRM-16905 - Sort by count cannot be done with sql
831 if (strpos($params['sort'], 'count') === 0) {
832 $orderBy = $limit = '';
833 }
834 }
835
836 $select = $from = $where = "";
837 $groupOrg = FALSE;
838 if (CRM_Core_Permission::check('administer Multiple Organizations') &&
839 CRM_Core_Permission::isMultisiteEnabled()
840 ) {
841 $select = ", contact.display_name as org_name, contact.id as org_id";
842 $from = " LEFT JOIN civicrm_group_organization gOrg
843 ON gOrg.group_id = `groups`.id
844 LEFT JOIN civicrm_contact contact
845 ON contact.id = gOrg.organization_id ";
846
847 //get the Organization ID
848 $orgID = CRM_Utils_Request::retrieve('oid', 'Positive');
849 if ($orgID) {
850 $where = " AND gOrg.organization_id = {$orgID}";
851 }
852
853 $groupOrg = TRUE;
854 }
855
856 $query = "
857 SELECT `groups`.*, createdBy.sort_name as created_by {$select}
858 FROM civicrm_group `groups`
859 LEFT JOIN civicrm_contact createdBy
860 ON createdBy.id = `groups`.created_id
861 {$from}
862 WHERE $whereClause {$where}
863 {$orderBy}
864 {$limit}";
865
866 $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
867
868 //FIXME CRM-4418, now we are handling delete separately
869 //if we introduce 'delete for group' make sure to handle here.
870 $groupPermissions = [CRM_Core_Permission::VIEW];
871 if (CRM_Core_Permission::check('edit groups')) {
872 $groupPermissions[] = CRM_Core_Permission::EDIT;
873 $groupPermissions[] = CRM_Core_Permission::DELETE;
874 }
875
876 // CRM-9936
877 $reservedPermission = CRM_Core_Permission::check('administer reserved groups');
878
879 $links = self::actionLinks($params);
880
881 $allTypes = CRM_Core_OptionGroup::values('group_type');
882 $values = [];
883
884 $visibility = CRM_Core_SelectValues::ufVisibility();
885
886 while ($object->fetch()) {
887 $newLinks = $links;
888 $values[$object->id] = [
889 'class' => [],
890 'count' => '0',
891 ];
892 CRM_Core_DAO::storeValues($object, $values[$object->id]);
893
894 if ($object->saved_search_id) {
895 $values[$object->id]['class'][] = "crm-smart-group";
896 // check if custom search, if so fix view link
897 $customSearchID = CRM_Core_DAO::getFieldValue(
898 'CRM_Contact_DAO_SavedSearch',
899 $object->saved_search_id,
900 'search_custom_id'
901 );
902
903 if ($customSearchID) {
904 $newLinks[CRM_Core_Action::VIEW]['url'] = 'civicrm/contact/search/custom';
905 $newLinks[CRM_Core_Action::VIEW]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
906 }
907 }
908
909 $action = array_sum(array_keys($newLinks));
910
911 // CRM-9936
912 if (property_exists($object, 'is_reserved')) {
913 //if group is reserved and I don't have reserved permission, suppress delete/edit
914 if ($object->is_reserved && !$reservedPermission) {
915 $action -= CRM_Core_Action::DELETE;
916 $action -= CRM_Core_Action::UPDATE;
917 $action -= CRM_Core_Action::DISABLE;
918 }
919 }
920
921 if (property_exists($object, 'is_active')) {
922 if ($object->is_active) {
923 $action -= CRM_Core_Action::ENABLE;
924 }
925 else {
926 $values[$object->id]['class'][] = 'disabled';
927 $action -= CRM_Core_Action::VIEW;
928 $action -= CRM_Core_Action::DISABLE;
929 }
930 }
931
932 $action = $action & CRM_Core_Action::mask($groupPermissions);
933
934 $values[$object->id]['visibility'] = $visibility[$values[$object->id]['visibility']];
935
936 if (isset($values[$object->id]['group_type'])) {
937 $groupTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
938 substr($values[$object->id]['group_type'], 1, -1)
939 );
940 $types = [];
941 foreach ($groupTypes as $type) {
942 $types[] = $allTypes[$type] ?? NULL;
943 }
944 $values[$object->id]['group_type'] = implode(', ', $types);
945 }
946 if ($action) {
947 $values[$object->id]['action'] = CRM_Core_Action::formLink($newLinks,
948 $action,
949 [
950 'id' => $object->id,
951 'ssid' => $object->saved_search_id,
952 ],
953 ts('more'),
954 FALSE,
955 'group.selector.row',
956 'Group',
957 $object->id
958 );
959 }
960
961 // If group has children, add class for link to view children
962 $values[$object->id]['is_parent'] = FALSE;
963 if (array_key_exists('children', $values[$object->id])) {
964 $values[$object->id]['class'][] = "crm-group-parent";
965 $values[$object->id]['is_parent'] = TRUE;
966 }
967
968 // If group is a child, add child class
969 if (array_key_exists('parents', $values[$object->id])) {
970 $values[$object->id]['class'][] = "crm-group-child";
971 }
972
973 if ($groupOrg) {
974 if ($object->org_id) {
975 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
976 $values[$object->id]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
977 }
978 else {
979 // Empty cell
980 $values[$object->id]['org_info'] = '';
981 }
982 }
983 else {
984 // Collapsed column if all cells are NULL
985 $values[$object->id]['org_info'] = NULL;
986 }
987 if ($object->created_id) {
988 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
989 $values[$object->id]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
990 }
991
992 // By default, we try to get a count of the contacts in each group
993 // to display to the user on the Manage Group page. However, if
994 // that will result in the cache being regenerated, then dipslay
995 // "unknown" instead to avoid a long wait for the user.
996 if (CRM_Contact_BAO_GroupContactCache::shouldGroupBeRefreshed($object->id)) {
997 $values[$object->id]['count'] = ts('unknown');
998 }
999 else {
1000 $values[$object->id]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id]);
1001 }
1002 }
1003
1004 // CRM-16905 - Sort by count cannot be done with sql
1005 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1006 usort($values, function($a, $b) {
1007 return $a['count'] - $b['count'];
1008 });
1009 if (strpos($params['sort'], 'desc')) {
1010 $values = array_reverse($values, TRUE);
1011 }
1012 return array_slice($values, $params['offset'], $params['rowCount']);
1013 }
1014
1015 return $values;
1016 }
1017
1018 /**
1019 * This function to get hierarchical list of groups (parent followed by children)
1020 *
1021 * @param array $groupIDs
1022 * Array of group ids.
1023 *
1024 * @param string $parents
1025 * @param string $spacer
1026 * @param bool $titleOnly
1027 * @param bool $public
1028 *
1029 * @return array
1030 */
1031 public static function getGroupsHierarchy(
1032 $groupIDs,
1033 $parents = NULL,
1034 $spacer = '<span class="child-indent"></span>',
1035 $titleOnly = FALSE,
1036 $public = FALSE
1037 ) {
1038 if (empty($groupIDs)) {
1039 return [];
1040 }
1041
1042 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1043 // <span class="child-icon"></span>
1044 // need to return id, title (w/ spacer), description, visibility
1045
1046 // We need to build a list of tags ordered by hierarchy and sorted by
1047 // name. The hierarchy will be communicated by an accumulation of
1048 // separators in front of the name to give it a visual offset.
1049 // Instead of recursively making mysql queries, we'll make one big
1050 // query and build the hierarchy with the algorithm below.
1051 $groups = [];
1052 $args = [1 => [$groupIdString, 'String']];
1053 $query = "
1054 SELECT id, title, frontend_title, description, frontend_description, visibility, parents, saved_search_id
1055 FROM civicrm_group
1056 WHERE id IN $groupIdString
1057 ";
1058 if ($parents) {
1059 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
1060 $parentArray = explode(',', $parents);
1061 $parent = self::filterActiveGroups($parentArray);
1062 $args[2] = [$parent, 'Integer'];
1063 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1064 }
1065 $query .= " ORDER BY title";
1066 $dao = CRM_Core_DAO::executeQuery($query, $args);
1067
1068 // Sort the groups into the correct storage by the parent
1069 // $roots represent the current leaf nodes that need to be checked for
1070 // children. $rows represent the unplaced nodes
1071 // $tree contains the child nodes based on their parent_id.
1072 $roots = [];
1073 $tree = [];
1074 while ($dao->fetch()) {
1075 $title = $dao->title;
1076 $description = $dao->description;
1077 if ($public) {
1078 if (!empty($dao->frontend_title)) {
1079 $title = $dao->frontend_title;
1080 }
1081 if (!empty($dao->frontend_description)) {
1082 $description = $dao->frontend_description;
1083 }
1084 }
1085 if ($dao->parents) {
1086 $parentArray = explode(',', $dao->parents);
1087 $parent = self::filterActiveGroups($parentArray);
1088 $tree[$parent][] = [
1089 'id' => $dao->id,
1090 'title' => empty($dao->saved_search_id) ? $title : '* ' . $title,
1091 'visibility' => $dao->visibility,
1092 'description' => $description,
1093 ];
1094 }
1095 else {
1096 $roots[] = [
1097 'id' => $dao->id,
1098 'title' => empty($dao->saved_search_id) ? $title : '* ' . $title,
1099 'visibility' => $dao->visibility,
1100 'description' => $description,
1101 ];
1102 }
1103 }
1104
1105 $hierarchy = [];
1106 for ($i = 0; $i < count($roots); $i++) {
1107 self::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1108 }
1109
1110 return $hierarchy;
1111 }
1112
1113 /**
1114 * Build a list with groups on alphabetical order and child groups after the parent group.
1115 *
1116 * This is a recursive function filling the $hierarchy parameter.
1117 *
1118 * @param array $hierarchy
1119 * @param array $group
1120 * @param array $tree
1121 * @param bool $titleOnly
1122 * @param string $spacer
1123 * @param int $level
1124 */
1125 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1126 $spaces = str_repeat($spacer, $level);
1127
1128 if ($titleOnly) {
1129 $hierarchy[$group['id']] = $spaces . $group['title'];
1130 }
1131 else {
1132 $hierarchy[] = [
1133 'id' => $group['id'],
1134 'text' => $spaces . $group['title'],
1135 'description' => $group['description'],
1136 'visibility' => $group['visibility'],
1137 ];
1138 }
1139
1140 // For performance reasons we use a for loop rather than a foreach.
1141 // Metrics for performance in an installation with 2867 groups a foreach
1142 // caused the function getGroupsHierarchy with a foreach execution takes
1143 // around 2.2 seconds (2,200 ms).
1144 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1145 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1146 for ($i = 0; $i < count($tree[$group['id']]); $i++) {
1147 self::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level + 1);
1148 }
1149 }
1150 }
1151
1152 /**
1153 * @param array $params
1154 *
1155 * @return NULL|string
1156 */
1157 public static function getGroupCount(&$params) {
1158 $whereClause = self::whereClause($params, FALSE);
1159 $query = "SELECT COUNT(*) FROM civicrm_group `groups`";
1160
1161 if (!empty($params['created_by'])) {
1162 $query .= "
1163 INNER JOIN civicrm_contact createdBy
1164 ON createdBy.id = `groups`.created_id";
1165 }
1166 $query .= "
1167 WHERE {$whereClause}";
1168 return CRM_Core_DAO::singleValueQuery($query, $params);
1169 }
1170
1171 /**
1172 * Generate permissioned where clause for group search.
1173 * @param array $params
1174 * @param bool $sortBy
1175 * @param bool $excludeHidden
1176 *
1177 * @return string
1178 */
1179 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1180 $values = [];
1181 $title = $params['title'] ?? NULL;
1182 if ($title) {
1183 $clauses[] = "`groups`.title LIKE %1";
1184 if (strpos($title, '%') !== FALSE) {
1185 $params[1] = [$title, 'String', FALSE];
1186 }
1187 else {
1188 $params[1] = [$title, 'String', TRUE];
1189 }
1190 }
1191
1192 $groupType = $params['group_type'] ?? NULL;
1193 if ($groupType) {
1194 $types = explode(',', $groupType);
1195 if (!empty($types)) {
1196 $clauses[] = '`groups`.group_type LIKE %2';
1197 $typeString = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $types) . CRM_Core_DAO::VALUE_SEPARATOR;
1198 $params[2] = [$typeString, 'String', TRUE];
1199 }
1200 }
1201
1202 $visibility = $params['visibility'] ?? NULL;
1203 if ($visibility) {
1204 $clauses[] = '`groups`.visibility = %3';
1205 $params[3] = [$visibility, 'String'];
1206 }
1207
1208 $groupStatus = $params['status'] ?? NULL;
1209 if ($groupStatus) {
1210 switch ($groupStatus) {
1211 case 1:
1212 $clauses[] = '`groups`.is_active = 1';
1213 $params[4] = [$groupStatus, 'Integer'];
1214 break;
1215
1216 case 2:
1217 $clauses[] = '`groups`.is_active = 0';
1218 $params[4] = [$groupStatus, 'Integer'];
1219 break;
1220
1221 case 3:
1222 $clauses[] = '(`groups`.is_active = 0 OR `groups`.is_active = 1 )';
1223 break;
1224 }
1225 }
1226
1227 $parentsOnly = $params['parentsOnly'] ?? NULL;
1228 if ($parentsOnly) {
1229 $clauses[] = '`groups`.parents IS NULL';
1230 }
1231
1232 $savedSearch = $params['savedSearch'] ?? NULL;
1233 if ($savedSearch == 1) {
1234 $clauses[] = '`groups`.saved_search_id IS NOT NULL';
1235 }
1236 elseif ($savedSearch == 2) {
1237 $clauses[] = '`groups`.saved_search_id IS NULL';
1238 }
1239
1240 // only show child groups of a specific parent group
1241 $parent_id = $params['parent_id'] ?? NULL;
1242 if ($parent_id) {
1243 $clauses[] = '`groups`.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1244 $params[5] = [$parent_id, 'Integer'];
1245 }
1246
1247 if ($createdBy = CRM_Utils_Array::value('created_by', $params)) {
1248 $clauses[] = "createdBy.sort_name LIKE %6";
1249 if (strpos($createdBy, '%') !== FALSE) {
1250 $params[6] = [$createdBy, 'String', FALSE];
1251 }
1252 else {
1253 $params[6] = [$createdBy, 'String', TRUE];
1254 }
1255 }
1256
1257 if (empty($clauses)) {
1258 $clauses[] = '`groups`.is_active = 1';
1259 }
1260
1261 if ($excludeHidden) {
1262 $clauses[] = '`groups`.is_hidden = 0';
1263 }
1264
1265 $clauses[] = self::getPermissionClause();
1266
1267 return implode(' AND ', $clauses);
1268 }
1269
1270 /**
1271 * Define action links.
1272 *
1273 * @return array
1274 * array of action links
1275 */
1276 public static function actionLinks($params) {
1277 // If component_mode is set we change the "View" link to match the requested component type
1278 if (!isset($params['component_mode'])) {
1279 $params['component_mode'] = CRM_Contact_BAO_Query::MODE_CONTACTS;
1280 }
1281 $modeValue = CRM_Contact_Form_Search::getModeValue($params['component_mode']);
1282 $links = [
1283 CRM_Core_Action::VIEW => [
1284 'name' => $modeValue['selectorLabel'],
1285 'url' => 'civicrm/group/search',
1286 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
1287 'title' => ts('Group Contacts'),
1288 ],
1289 CRM_Core_Action::UPDATE => [
1290 'name' => ts('Settings'),
1291 'url' => 'civicrm/group',
1292 'qs' => 'reset=1&action=update&id=%%id%%',
1293 'title' => ts('Edit Group'),
1294 ],
1295 CRM_Core_Action::DISABLE => [
1296 'name' => ts('Disable'),
1297 'ref' => 'crm-enable-disable',
1298 'title' => ts('Disable Group'),
1299 ],
1300 CRM_Core_Action::ENABLE => [
1301 'name' => ts('Enable'),
1302 'ref' => 'crm-enable-disable',
1303 'title' => ts('Enable Group'),
1304 ],
1305 CRM_Core_Action::DELETE => [
1306 'name' => ts('Delete'),
1307 'url' => 'civicrm/group',
1308 'qs' => 'reset=1&action=delete&id=%%id%%',
1309 'title' => ts('Delete Group'),
1310 ],
1311 ];
1312
1313 return $links;
1314 }
1315
1316 /**
1317 * @param $whereClause
1318 * @param array $whereParams
1319 *
1320 * @return string
1321 */
1322 public function pagerAtoZ($whereClause, $whereParams) {
1323 $query = "
1324 SELECT DISTINCT UPPER(LEFT(`groups`.title, 1)) as sort_name
1325 FROM civicrm_group `groups`
1326 WHERE $whereClause
1327 ORDER BY LEFT(`groups`.title, 1)
1328 ";
1329 $dao = CRM_Core_DAO::executeQuery($query, $whereParams);
1330
1331 return CRM_Utils_PagerAToZ::getAToZBar($dao, $this->_sortByCharacter, TRUE);
1332 }
1333
1334 /**
1335 * Assign Test Value.
1336 *
1337 * @param string $fieldName
1338 * @param array $fieldDef
1339 * @param int $counter
1340 */
1341 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1342 if ($fieldName == 'children' || $fieldName == 'parents') {
1343 $this->{$fieldName} = "NULL";
1344 }
1345 else {
1346 parent::assignTestValue($fieldName, $fieldDef, $counter);
1347 }
1348 }
1349
1350 /**
1351 * Get child group ids
1352 *
1353 * @param array $regularGroupIDs
1354 * Parent Group IDs
1355 *
1356 * @return array
1357 */
1358 public static function getChildGroupIds($regularGroupIDs) {
1359 $childGroupIDs = [];
1360
1361 foreach ((array) $regularGroupIDs as $regularGroupID) {
1362 // temporary store the child group ID(s) of regular group identified by $id,
1363 // later merge with main child group array
1364 $tempChildGroupIDs = [];
1365 // check that the regular group has any child group, if not then continue
1366 if ($childrenFound = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1367 $tempChildGroupIDs[] = $childrenFound;
1368 }
1369 else {
1370 continue;
1371 }
1372 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1373 // so we need to convert it into array of child group IDs first
1374 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1375 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1376 // recursively fetch the child group IDs
1377 while (count($tempChildGroupIDs)) {
1378 $tempChildGroupIDs = self::getChildGroupIds($tempChildGroupIDs);
1379 if (count($tempChildGroupIDs)) {
1380 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1381 }
1382 }
1383 }
1384
1385 return $childGroupIDs;
1386 }
1387
1388 /**
1389 * Check parent groups and filter out the disabled ones.
1390 *
1391 * @param array $parentArray
1392 * Array of group Ids.
1393 *
1394 * @return int
1395 */
1396 public static function filterActiveGroups($parentArray) {
1397 if (count($parentArray) > 1) {
1398 $result = civicrm_api3('Group', 'get', [
1399 'id' => ['IN' => $parentArray],
1400 'is_active' => TRUE,
1401 'return' => 'id',
1402 ]);
1403 $activeParentGroupIDs = CRM_Utils_Array::collect('id', $result['values']);
1404 foreach ($parentArray as $key => $groupID) {
1405 if (!array_key_exists($groupID, $activeParentGroupIDs)) {
1406 unset($parentArray[$key]);
1407 }
1408 }
1409 }
1410
1411 return reset($parentArray);
1412 }
1413
1414 }