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