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