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