3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Contact_BAO_Group
extends CRM_Contact_DAO_Group
{
22 * Retrieve DB object and copy to defaults array.
24 * @param array $params
25 * Array of criteria values.
26 * @param array $defaults
27 * Array to be populated with found values.
30 * The DAO object, if found.
34 public static function retrieve($params, &$defaults) {
35 return self
::commonRetrieve(self
::class, $params, $defaults);
39 * Delete the group and all the object that connect to this group.
41 * Incredibly destructive.
43 * @param int $id Group id.
45 public static function discard($id) {
46 if (!$id ||
!is_numeric($id)) {
47 throw new CRM_Core_Exception('Invalid group request attempted');
49 CRM_Utils_Hook
::pre('delete', 'Group', $id);
51 $transaction = new CRM_Core_Transaction();
53 // added for CRM-1631 and CRM-1794
54 // delete all subscribed mails with the selected group id
55 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
56 $subscribe->group_id
= $id;
59 // delete all Subscription records with the selected group id
60 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
61 $subHistory->group_id
= $id;
62 $subHistory->delete();
64 // delete all crm_group_contact records with the selected group id
65 $groupContact = new CRM_Contact_DAO_GroupContact();
66 $groupContact->group_id
= $id;
67 $groupContact->delete();
69 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
70 $params = [1 => [$id, 'Integer']];
71 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
72 CRM_Core_DAO
::executeQuery($query, $params);
74 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
75 CRM_Core_DAO
::executeQuery($query, $params);
77 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
79 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
80 CRM_Core_DAO
::executeQuery($query, $params);
82 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
83 CRM_Core_DAO
::executeQuery($query, $params);
85 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
86 CRM_Core_DAO
::executeQuery($query, $params);
88 //check whether this group contains any saved searches and check if that saved search is appropriate to delete.
89 $groupDetails = Group
::get(FALSE)->addWhere('id', '=', $id)->execute();
90 if (!empty($groupDetails[0]['saved_search_id'])) {
91 $savedSearch = new CRM_Contact_DAO_SavedSearch();
92 $savedSearch->id
= $groupDetails[0]['saved_search_id'];
93 $savedSearch->find(TRUE);
94 // If it is a traditional saved search i.e has form values and there is no linked api_entity then delete the saved search as well.
95 if (!empty($savedSearch->form_values
) && empty($savedSearch->api_entity
) && empty($savedSearch->api_params
)) {
96 $savedSearch->delete();
100 // delete from group table
101 $group = new CRM_Contact_DAO_Group();
105 $transaction->commit();
107 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
111 * Returns an array of the contacts in the given group.
115 public static function getGroupContacts($id) {
116 $params = [['group', 'IN', [1 => $id], 0, 0]];
117 [$contacts] = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
122 * Get the count of a members in a group with the specific status.
126 * @param string $status
127 * status of members in group
128 * @param bool $countChildGroups
131 * count of members in the group with above status
133 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
134 $groupContact = new CRM_Contact_DAO_GroupContact();
136 if ($countChildGroups) {
137 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
141 $contacts = self
::getGroupContacts($id);
143 foreach ($groupIds as $groupId) {
145 $groupContacts = self
::getGroupContacts($groupId);
146 foreach ($groupContacts as $gcontact) {
147 if ($groupId != $id) {
148 // Loop through main group's contacts
149 // and subtract from the count for each contact which
150 // matches one in the present group, if it is not the
152 foreach ($contacts as $contact) {
153 if ($contact['contact_id'] == $gcontact['contact_id']) {
159 $groupContact->group_id
= $groupId;
160 if (isset($status)) {
161 $groupContact->status
= $status;
163 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
164 $count +
= $groupContact->count();
170 * Get the list of member for a group id.
172 * @param int $groupID
173 * @param bool $useCache
175 * Number to limit to (or 0 for unlimited).
178 * this array contains the list of members for this group id
180 public static function getMember($groupID, $useCache = TRUE, $limit = 0) {
181 $params = [['group', '=', $groupID, 0, 0]];
182 $returnProperties = ['contact_id'];
183 list($contacts) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache);
186 foreach ($contacts as $contact) {
187 $aMembers[$contact['contact_id']] = 1;
194 * Returns array of group object(s) matching a set of one or Group properties.
196 * @param array $params
197 * Limits the set of groups returned.
198 * @param array $returnProperties
199 * Which properties should be included in the returned group objects.
200 * (member_count should be last element.)
201 * @param string $sort
203 * @param int $rowCount
206 * Array of group objects.
209 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
210 * add in essential fields (e.g. id). This should follow a regular pattern like the others
212 public static function getGroups(
214 $returnProperties = NULL,
219 $dao = new CRM_Contact_DAO_Group();
220 if (!isset($params['is_active'])) {
224 foreach ($params as $k => $v) {
225 if ($k == 'name' ||
$k == 'title') {
226 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
228 elseif ($k == 'group_type') {
229 foreach ((array) $v as $type) {
230 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
233 elseif (is_array($v)) {
234 foreach ($v as &$num) {
237 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
245 if ($offset ||
$rowCount) {
246 $offset = ($offset > 0) ?
$offset : 0;
247 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
248 $dao->limit($offset, $rowCount);
252 $dao->orderBy($sort);
255 // return only specific fields if returnproperties are sent
256 if (!empty($returnProperties)) {
258 $dao->selectAdd(implode(',', $returnProperties));
262 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
265 while ($dao->fetch()) {
266 $group = new CRM_Contact_DAO_Group();
268 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
270 $groups[] = clone($dao);
276 * Make sure that the user has permission to access this group.
279 * The id of the object.
280 * @param bool $excludeHidden
281 * Should hidden groups be excluded.
282 * Logically this is the wrong place to filter hidden groups out as that is
283 * not a permission issue. However, as other functions may rely on that defaulting to
284 * FALSE for now & only the api call is calling with true.
287 * The permission that the user has (or NULL)
289 public static function checkPermission($id, $excludeHidden = FALSE) {
290 $allGroups = CRM_Core_PseudoConstant
::allGroup(NULL, $excludeHidden);
293 if (CRM_Core_Permission
::check('edit all contacts') ||
294 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
295 'civicrm_saved_search', $allGroups
298 $permissions[] = CRM_Core_Permission
::EDIT
;
301 if (CRM_Core_Permission
::check('view all contacts') ||
302 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
303 'civicrm_saved_search', $allGroups
306 $permissions[] = CRM_Core_Permission
::VIEW
;
309 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
310 // Note: using !empty() in if condition, restricts the scope of delete
311 // permission to groups/contacts that are editable/viewable.
312 // We can remove this !empty condition once we have ACL support for delete functionality.
313 $permissions[] = CRM_Core_Permission
::DELETE
;
320 * Create a new group.
322 * @param array $params
324 * @return CRM_Contact_BAO_Group|NULL
325 * The new group BAO (if created)
327 public static function create(&$params) {
329 'group_type' => NULL,
333 $hook = empty($params['id']) ?
'create' : 'edit';
334 CRM_Utils_Hook
::pre($hook, 'Group', $params['id'] ??
NULL, $params);
336 // If title isn't specified, retrieve it because we use it later, e.g.
337 // for RecentItems. But note we use array_key_exists not isset or empty
338 // since otherwise there would be no way to blank out an existing title.
339 // I'm not sure what the use-case is for that, but you're allowed to do it
341 if (!empty($params['id']) && !array_key_exists('title', $params)) {
343 $groupTitle = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $params['id'], 'title', 'id');
344 $params['title'] = $groupTitle;
346 catch (CRM_Core_Exception
$groupTitleException) {
351 // dev/core#287 Disable child groups if all parents are disabled.
352 if (!empty($params['id'])) {
353 $allChildGroupIds = self
::getChildGroupIds($params['id']);
354 foreach ($allChildGroupIds as $childKey => $childValue) {
355 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($childValue);
356 $activeParentsCount = civicrm_api3('Group', 'getcount', [
357 'id' => ['IN' => $parentIds],
360 if (count($parentIds) >= 1 && $activeParentsCount <= 1) {
361 self
::setIsActive($childValue, (int) ($params['is_active'] ??
1));
365 // form the name only if missing: CRM-627
366 $nameParam = $params['name'] ??
NULL;
367 if (!$nameParam && empty($params['id'])) {
368 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
371 if (!CRM_Utils_System
::isNull($params['parents'])) {
372 $params['parents'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['parents']);
375 // convert params if array type
376 if (!CRM_Utils_System
::isNull($params['group_type'])) {
377 $params['group_type'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['group_type']);
380 $session = CRM_Core_Session
::singleton();
381 $cid = $session->get('userID');
382 // this action is add
383 if ($cid && empty($params['id'])) {
384 $params['created_id'] = $cid;
386 // this action is update
387 if ($cid && !empty($params['id'])) {
388 $params['modified_id'] = $cid;
392 // Validate parents parameter when creating group.
393 if (!CRM_Utils_System
::isNull($params['parents'])) {
394 $parents = is_array($params['parents']) ?
array_keys($params['parents']) : (array) $params['parents'];
395 foreach ($parents as $parent) {
396 CRM_Utils_Type
::validate($parent, 'Integer');
399 $group = new CRM_Contact_BAO_Group();
400 $group->copyValues($params);
402 if (empty($params['id']) && !$nameParam) {
403 $group->name
.= "_tmp";
411 // Enforce unique name by appending id
412 if (empty($params['id']) && !$nameParam) {
413 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
418 // add custom field values
419 if (!empty($params['custom'])) {
420 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
423 // make the group, child of domain/site group by default.
424 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
425 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
426 if (empty($params['parents']) &&
427 $domainGroupID != $group->id
&&
428 Civi
::settings()->get('is_enabled') &&
429 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
431 // if no parent present and the group doesn't already have any parents,
432 // make sure site group goes as parent
433 $params['parents'] = [$domainGroupID];
436 if (!CRM_Utils_System
::isNull($params['parents'])) {
437 foreach ($params['parents'] as $parentId) {
438 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
439 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
444 // this is always required, since we don't know when a
445 // parent group is removed
446 CRM_Contact_BAO_GroupNestingCache
::update();
448 // update group contact cache for all parent groups
449 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
450 foreach ($parentIds as $parentId) {
451 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($parentId);
455 if (!empty($params['organization_id'])) {
456 if ($params['organization_id'] == 'null') {
457 $groupOrganization = [];
458 CRM_Contact_BAO_GroupOrganization
::retrieve($group->id
, $groupOrganization);
459 if (!empty($groupOrganization['group_organization'])) {
460 CRM_Contact_BAO_GroupOrganization
::deleteGroupOrganization($groupOrganization['group_organization']);
464 // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table
466 'group_id' => $group->id
,
467 'organization_id' => $params['organization_id'],
469 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
474 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($group->id
);
476 CRM_Utils_Hook
::post($hook, 'Group', $group->id
, $group);
479 if (CRM_Core_Permission
::check('edit groups')) {
480 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
481 // currently same permission we are using for delete a group
482 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
485 // add the recently added group (unless hidden: CRM-6432)
486 if (!$group->is_hidden
) {
487 CRM_Utils_Recent
::add($group->title
,
488 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
500 * Takes a sloppy mismash of params and creates two entities: a Group and a SavedSearch
501 * Currently only used by unit tests.
503 * @param array $params
504 * @return CRM_Contact_BAO_Group|NULL
507 public static function createSmartGroup($params) {
508 if (!empty($params['formValues'])) {
510 // Remove group parameters from sloppy mismash
511 unset($ssParams['id'], $ssParams['name'], $ssParams['title'], $ssParams['formValues'], $ssParams['saved_search_id']);
512 if (isset($params['saved_search_id'])) {
513 $ssParams['id'] = $params['saved_search_id'];
515 $ssParams['form_values'] = $params['formValues'];
516 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($ssParams);
518 $params['saved_search_id'] = $savedSearch->id
;
524 return self
::create($params);
528 * Update the is_active flag in the db.
531 * Id of the database record.
532 * @param bool $isActive
533 * Value we want to set the is_active field.
536 * true if we found and updated the object, else false
538 public static function setIsActive($id, $isActive) {
539 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
543 * Build the condition to retrieve groups.
545 * @param string $groupType
546 * Type of group(Access/Mailing) OR the key of the group.
547 * @param bool $excludeHidden exclude hidden groups.
551 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
553 if ($groupType == 'Mailing') {
554 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
556 elseif ($groupType == 'Access') {
557 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
559 elseif (!empty($groupType)) {
560 // ie we have been given the group key
561 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
565 if ($excludeHidden) {
566 $condition = "is_hidden = 0";
571 $condition .= " AND group_type LIKE '%$value%'";
574 $condition = "group_type LIKE '%$value%'";
582 * Get permission relevant clauses.
586 public static function getPermissionClause() {
587 if (!isset(Civi
::$statics[__CLASS__
]['permission_clause'])) {
588 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
592 //get the allowed groups for the current user
593 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
594 if (!empty($groups)) {
595 $groupList = implode(', ', array_values($groups));
596 $clause = "`groups`.id IN ( $groupList ) ";
602 Civi
::$statics[__CLASS__
]['permission_clause'] = $clause;
604 return Civi
::$statics[__CLASS__
]['permission_clause'];
608 * Flush caches that hold group data.
610 * (Actually probably some overkill at the moment.)
612 protected static function flushCaches() {
613 CRM_Utils_System
::flushCache();
615 'CRM_Core_PseudoConstant' => 'groups',
616 'CRM_ACL_API' => 'group_permission',
617 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
618 'CRM_Contact_BAO_Group' => 'permission_clause',
620 foreach ($staticCaches as $class => $key) {
621 if (isset(Civi
::$statics[$class][$key])) {
622 unset(Civi
::$statics[$class][$key]);
630 public function __toString() {
635 * This function create the hidden smart group when user perform
636 * contact search and want to send mailing to search contacts.
638 * @param array $params
639 * ( reference ) an assoc array of name/value pairs.
642 * ( smartGroupId, ssId ) smart group id and saved search id
644 public static function createHiddenSmartGroup($params) {
645 $ssId = $params['saved_search_id'] ??
NULL;
647 //add mapping record only for search builder saved search
649 if ($params['search_context'] == 'builder') {
650 //save the mapping for search builder
652 //save record in mapping table
654 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
656 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams);
657 $mappingId = $mapping->id
;
660 //get the mapping id from saved search
661 $savedSearch = new CRM_Contact_BAO_SavedSearch();
662 $savedSearch->id
= $ssId;
663 $savedSearch->find(TRUE);
664 $mappingId = $savedSearch->mapping_id
;
667 //save mapping fields
668 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
671 //create/update saved search record.
672 $savedSearch = new CRM_Contact_BAO_SavedSearch();
673 $savedSearch->id
= $ssId;
674 $formValues = $params['search_context'] === 'builder' ?
$params['form_values'] : CRM_Contact_BAO_Query
::convertFormValues($params['form_values']);
675 $savedSearch->form_values
= serialize($formValues);
676 $savedSearch->mapping_id
= $mappingId;
677 $savedSearch->search_custom_id
= $params['search_custom_id'] ??
NULL;
678 $savedSearch->save();
680 $ssId = $savedSearch->id
;
685 $smartGroupId = NULL;
686 if (!empty($params['saved_search_id'])) {
687 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
690 //create group only when new saved search.
692 'title' => "Hidden Smart Group {$ssId}",
693 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
694 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
695 'group_type' => $params['group_type'] ??
NULL,
696 'visibility' => $params['visibility'] ??
NULL,
697 'saved_search_id' => $ssId,
700 $smartGroup = self
::create($groupParams);
701 $smartGroupId = $smartGroup->id
;
704 // Update mapping with the name and description of the hidden smart group.
708 'name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
709 'description' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
710 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
712 CRM_Core_BAO_Mapping
::add($mappingParams);
715 return [$smartGroupId, $ssId];
719 * wrapper for ajax group selector.
721 * @param array $params
722 * Associated array for params record id.
725 * associated array of group list
728 * @todo there seems little reason for the small number of functions that call this to pass in
729 * params that then need to be translated in this function since they are coding them when calling
731 public static function getGroupListSelector(&$params) {
733 $params['offset'] = ($params['page'] - 1) * $params['rp'];
734 $params['rowCount'] = $params['rp'];
735 $params['sort'] = $params['sortBy'] ??
NULL;
738 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
740 //skip total if we are making call to show only children
741 if (empty($params['parent_id'])) {
743 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
745 // get all the groups
746 $allGroups = CRM_Core_PseudoConstant
::allGroup();
749 // format params and add links
751 foreach ($groups as $id => $value) {
753 $group['group_id'] = $value['id'];
754 $group['count'] = $value['count'];
755 $group['title'] = $value['title'];
757 // append parent names if in search mode
758 if (empty($params['parent_id']) && !empty($value['parents'])) {
759 $group['parent_id'] = $value['parents'];
760 $groupIds = explode(',', $value['parents']);
762 foreach ($groupIds as $gId) {
763 $title[] = $allGroups[$gId];
765 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
766 $value['class'] = array_diff($value['class'], ['crm-row-parent']);
768 $group['DT_RowId'] = 'row_' . $value['id'];
769 if (empty($params['parentsOnly'])) {
770 foreach ($value['class'] as $id => $class) {
771 if ($class == 'crm-group-parent') {
772 unset($value['class'][$id]);
776 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
777 $group['DT_RowAttr'] = [];
778 $group['DT_RowAttr']['data-id'] = $value['id'];
779 $group['DT_RowAttr']['data-entity'] = 'group';
781 $group['description'] = $value['description'] ??
NULL;
783 if (!empty($value['group_type'])) {
784 $group['group_type'] = $value['group_type'];
787 $group['group_type'] = '';
790 $group['visibility'] = $value['visibility'];
791 $group['links'] = $value['action'];
792 $group['org_info'] = $value['org_info'] ??
NULL;
793 $group['created_by'] = $value['created_by'] ??
NULL;
795 $group['is_parent'] = $value['is_parent'];
797 array_push($groupList, $group);
801 $groupsDT['data'] = $groupList;
802 $groupsDT['recordsTotal'] = !empty($params['total']) ?
$params['total'] : NULL;
803 $groupsDT['recordsFiltered'] = !empty($params['total']) ?
$params['total'] : NULL;
809 * This function to get list of groups.
811 * @param array $params
812 * Associated array for params.
816 public static function getGroupList(&$params) {
817 $whereClause = self
::whereClause($params, FALSE);
820 if (!empty($params['rowCount']) &&
821 $params['rowCount'] > 0
823 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
826 $orderBy = ' ORDER BY `groups`.title asc';
827 if (!empty($params['sort'])) {
828 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
830 // CRM-16905 - Sort by count cannot be done with sql
831 if (strpos($params['sort'], 'count') === 0) {
832 $orderBy = $limit = '';
836 $select = $from = $where = "";
838 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
839 CRM_Core_Permission
::isMultisiteEnabled()
841 $select = ", contact.display_name as org_name, contact.id as org_id";
842 $from = " LEFT JOIN civicrm_group_organization gOrg
843 ON gOrg.group_id = `groups`.id
844 LEFT JOIN civicrm_contact contact
845 ON contact.id = gOrg.organization_id ";
847 //get the Organization ID
848 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive');
850 $where = " AND gOrg.organization_id = {$orgID}";
857 SELECT `groups`.*, createdBy.sort_name as created_by {$select}
858 FROM civicrm_group `groups`
859 LEFT JOIN civicrm_contact createdBy
860 ON createdBy.id = `groups`.created_id
862 WHERE $whereClause {$where}
866 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
868 //FIXME CRM-4418, now we are handling delete separately
869 //if we introduce 'delete for group' make sure to handle here.
870 $groupPermissions = [CRM_Core_Permission
::VIEW
];
871 if (CRM_Core_Permission
::check('edit groups')) {
872 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
873 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
877 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
879 $links = self
::actionLinks($params);
881 $allTypes = CRM_Core_OptionGroup
::values('group_type');
884 $visibility = CRM_Core_SelectValues
::ufVisibility();
886 while ($object->fetch()) {
888 $values[$object->id
] = [
892 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
894 if ($object->saved_search_id
) {
895 $values[$object->id
]['class'][] = "crm-smart-group";
896 // check if custom search, if so fix view link
897 $customSearchID = CRM_Core_DAO
::getFieldValue(
898 'CRM_Contact_DAO_SavedSearch',
899 $object->saved_search_id
,
903 if ($customSearchID) {
904 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
905 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
909 $action = array_sum(array_keys($newLinks));
912 if (property_exists($object, 'is_reserved')) {
913 //if group is reserved and I don't have reserved permission, suppress delete/edit
914 if ($object->is_reserved
&& !$reservedPermission) {
915 $action -= CRM_Core_Action
::DELETE
;
916 $action -= CRM_Core_Action
::UPDATE
;
917 $action -= CRM_Core_Action
::DISABLE
;
921 if (property_exists($object, 'is_active')) {
922 if ($object->is_active
) {
923 $action -= CRM_Core_Action
::ENABLE
;
926 $values[$object->id
]['class'][] = 'disabled';
927 $action -= CRM_Core_Action
::VIEW
;
928 $action -= CRM_Core_Action
::DISABLE
;
932 $action = $action & CRM_Core_Action
::mask($groupPermissions);
934 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
936 if (isset($values[$object->id
]['group_type'])) {
937 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
938 substr($values[$object->id
]['group_type'], 1, -1)
941 foreach ($groupTypes as $type) {
942 $types[] = $allTypes[$type] ??
NULL;
944 $values[$object->id
]['group_type'] = implode(', ', $types);
947 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
951 'ssid' => $object->saved_search_id
,
955 'group.selector.row',
961 // If group has children, add class for link to view children
962 $values[$object->id
]['is_parent'] = FALSE;
963 if (array_key_exists('children', $values[$object->id
])) {
964 $values[$object->id
]['class'][] = "crm-group-parent";
965 $values[$object->id
]['is_parent'] = TRUE;
968 // If group is a child, add child class
969 if (array_key_exists('parents', $values[$object->id
])) {
970 $values[$object->id
]['class'][] = "crm-group-child";
974 if ($object->org_id
) {
975 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
976 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
980 $values[$object->id
]['org_info'] = '';
984 // Collapsed column if all cells are NULL
985 $values[$object->id
]['org_info'] = NULL;
987 if ($object->created_id
) {
988 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
989 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
992 // By default, we try to get a count of the contacts in each group
993 // to display to the user on the Manage Group page. However, if
994 // that will result in the cache being regenerated, then dipslay
995 // "unknown" instead to avoid a long wait for the user.
996 if (CRM_Contact_BAO_GroupContactCache
::shouldGroupBeRefreshed($object->id
)) {
997 $values[$object->id
]['count'] = ts('unknown');
1000 $values[$object->id
]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id
]);
1004 // CRM-16905 - Sort by count cannot be done with sql
1005 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1006 usort($values, function($a, $b) {
1007 return $a['count'] - $b['count'];
1009 if (strpos($params['sort'], 'desc')) {
1010 $values = array_reverse($values, TRUE);
1012 return array_slice($values, $params['offset'], $params['rowCount']);
1019 * This function to get hierarchical list of groups (parent followed by children)
1021 * @param array $groupIDs
1022 * Array of group ids.
1024 * @param string $parents
1025 * @param string $spacer
1026 * @param bool $titleOnly
1027 * @param bool $public
1031 public static function getGroupsHierarchy(
1034 $spacer = '<span class="child-indent"></span>',
1038 if (empty($groupIDs)) {
1042 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1043 // <span class="child-icon"></span>
1044 // need to return id, title (w/ spacer), description, visibility
1046 // We need to build a list of tags ordered by hierarchy and sorted by
1047 // name. The hierarchy will be communicated by an accumulation of
1048 // separators in front of the name to give it a visual offset.
1049 // Instead of recursively making mysql queries, we'll make one big
1050 // query and build the hierarchy with the algorithm below.
1052 $args = [1 => [$groupIdString, 'String']];
1054 SELECT id, title, frontend_title, description, frontend_description, visibility, parents, saved_search_id
1056 WHERE id IN $groupIdString
1059 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
1060 $parentArray = explode(',', $parents);
1061 $parent = self
::filterActiveGroups($parentArray);
1062 $args[2] = [$parent, 'Integer'];
1063 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1065 $query .= " ORDER BY title";
1066 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1068 // Sort the groups into the correct storage by the parent
1069 // $roots represent the current leaf nodes that need to be checked for
1070 // children. $rows represent the unplaced nodes
1071 // $tree contains the child nodes based on their parent_id.
1074 while ($dao->fetch()) {
1075 $title = $dao->title
;
1076 $description = $dao->description
;
1078 if (!empty($dao->frontend_title
)) {
1079 $title = $dao->frontend_title
;
1081 if (!empty($dao->frontend_description
)) {
1082 $description = $dao->frontend_description
;
1085 if ($dao->parents
) {
1086 $parentArray = explode(',', $dao->parents
);
1087 $parent = self
::filterActiveGroups($parentArray);
1088 $tree[$parent][] = [
1090 'title' => empty($dao->saved_search_id
) ?
$title : '* ' . $title,
1091 'visibility' => $dao->visibility
,
1092 'description' => $description,
1098 'title' => empty($dao->saved_search_id
) ?
$title : '* ' . $title,
1099 'visibility' => $dao->visibility
,
1100 'description' => $description,
1106 for ($i = 0; $i < count($roots); $i++
) {
1107 self
::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1114 * Build a list with groups on alphabetical order and child groups after the parent group.
1116 * This is a recursive function filling the $hierarchy parameter.
1118 * @param array $hierarchy
1119 * @param array $group
1120 * @param array $tree
1121 * @param bool $titleOnly
1122 * @param string $spacer
1125 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1126 $spaces = str_repeat($spacer, $level);
1129 $hierarchy[$group['id']] = $spaces . $group['title'];
1133 'id' => $group['id'],
1134 'text' => $spaces . $group['title'],
1135 'description' => $group['description'],
1136 'visibility' => $group['visibility'],
1140 // For performance reasons we use a for loop rather than a foreach.
1141 // Metrics for performance in an installation with 2867 groups a foreach
1142 // caused the function getGroupsHierarchy with a foreach execution takes
1143 // around 2.2 seconds (2,200 ms).
1144 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1145 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1146 for ($i = 0; $i < count($tree[$group['id']]); $i++
) {
1147 self
::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level +
1);
1153 * @param array $params
1155 * @return NULL|string
1157 public static function getGroupCount(&$params) {
1158 $whereClause = self
::whereClause($params, FALSE);
1159 $query = "SELECT COUNT(*) FROM civicrm_group `groups`";
1161 if (!empty($params['created_by'])) {
1163 INNER JOIN civicrm_contact createdBy
1164 ON createdBy.id = `groups`.created_id";
1167 WHERE {$whereClause}";
1168 return CRM_Core_DAO
::singleValueQuery($query, $params);
1172 * Generate permissioned where clause for group search.
1173 * @param array $params
1174 * @param bool $sortBy
1175 * @param bool $excludeHidden
1179 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1181 $title = $params['title'] ??
NULL;
1183 $clauses[] = "`groups`.title LIKE %1";
1184 if (strpos($title, '%') !== FALSE) {
1185 $params[1] = [$title, 'String', FALSE];
1188 $params[1] = [$title, 'String', TRUE];
1192 $groupType = $params['group_type'] ??
NULL;
1194 $types = explode(',', $groupType);
1195 if (!empty($types)) {
1196 $clauses[] = '`groups`.group_type LIKE %2';
1197 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1198 $params[2] = [$typeString, 'String', TRUE];
1202 $visibility = $params['visibility'] ??
NULL;
1204 $clauses[] = '`groups`.visibility = %3';
1205 $params[3] = [$visibility, 'String'];
1208 $groupStatus = $params['status'] ??
NULL;
1210 switch ($groupStatus) {
1212 $clauses[] = '`groups`.is_active = 1';
1213 $params[4] = [$groupStatus, 'Integer'];
1217 $clauses[] = '`groups`.is_active = 0';
1218 $params[4] = [$groupStatus, 'Integer'];
1222 $clauses[] = '(`groups`.is_active = 0 OR `groups`.is_active = 1 )';
1227 $parentsOnly = $params['parentsOnly'] ??
NULL;
1229 $clauses[] = '`groups`.parents IS NULL';
1232 $savedSearch = $params['savedSearch'] ??
NULL;
1233 if ($savedSearch == 1) {
1234 $clauses[] = '`groups`.saved_search_id IS NOT NULL';
1236 elseif ($savedSearch == 2) {
1237 $clauses[] = '`groups`.saved_search_id IS NULL';
1240 // only show child groups of a specific parent group
1241 $parent_id = $params['parent_id'] ??
NULL;
1243 $clauses[] = '`groups`.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1244 $params[5] = [$parent_id, 'Integer'];
1247 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1248 $clauses[] = "createdBy.sort_name LIKE %6";
1249 if (strpos($createdBy, '%') !== FALSE) {
1250 $params[6] = [$createdBy, 'String', FALSE];
1253 $params[6] = [$createdBy, 'String', TRUE];
1257 if (empty($clauses)) {
1258 $clauses[] = '`groups`.is_active = 1';
1261 if ($excludeHidden) {
1262 $clauses[] = '`groups`.is_hidden = 0';
1265 $clauses[] = self
::getPermissionClause();
1267 return implode(' AND ', $clauses);
1271 * Define action links.
1274 * array of action links
1276 public static function actionLinks($params) {
1277 // If component_mode is set we change the "View" link to match the requested component type
1278 if (!isset($params['component_mode'])) {
1279 $params['component_mode'] = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
1281 $modeValue = CRM_Contact_Form_Search
::getModeValue($params['component_mode']);
1283 CRM_Core_Action
::VIEW
=> [
1284 'name' => $modeValue['selectorLabel'],
1285 'url' => 'civicrm/group/search',
1286 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
1287 'title' => ts('Group Contacts'),
1289 CRM_Core_Action
::UPDATE
=> [
1290 'name' => ts('Settings'),
1291 'url' => 'civicrm/group',
1292 'qs' => 'reset=1&action=update&id=%%id%%',
1293 'title' => ts('Edit Group'),
1295 CRM_Core_Action
::DISABLE
=> [
1296 'name' => ts('Disable'),
1297 'ref' => 'crm-enable-disable',
1298 'title' => ts('Disable Group'),
1300 CRM_Core_Action
::ENABLE
=> [
1301 'name' => ts('Enable'),
1302 'ref' => 'crm-enable-disable',
1303 'title' => ts('Enable Group'),
1305 CRM_Core_Action
::DELETE
=> [
1306 'name' => ts('Delete'),
1307 'url' => 'civicrm/group',
1308 'qs' => 'reset=1&action=delete&id=%%id%%',
1309 'title' => ts('Delete Group'),
1317 * @param $whereClause
1318 * @param array $whereParams
1322 public function pagerAtoZ($whereClause, $whereParams) {
1324 SELECT DISTINCT UPPER(LEFT(`groups`.title, 1)) as sort_name
1325 FROM civicrm_group `groups`
1327 ORDER BY LEFT(`groups`.title, 1)
1329 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1331 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1335 * Assign Test Value.
1337 * @param string $fieldName
1338 * @param array $fieldDef
1339 * @param int $counter
1341 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1342 if ($fieldName == 'children' ||
$fieldName == 'parents') {
1343 $this->{$fieldName} = "NULL";
1346 parent
::assignTestValue($fieldName, $fieldDef, $counter);
1351 * Get child group ids
1353 * @param array $regularGroupIDs
1358 public static function getChildGroupIds($regularGroupIDs) {
1359 $childGroupIDs = [];
1361 foreach ((array) $regularGroupIDs as $regularGroupID) {
1362 // temporary store the child group ID(s) of regular group identified by $id,
1363 // later merge with main child group array
1364 $tempChildGroupIDs = [];
1365 // check that the regular group has any child group, if not then continue
1366 if ($childrenFound = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1367 $tempChildGroupIDs[] = $childrenFound;
1372 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1373 // so we need to convert it into array of child group IDs first
1374 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1375 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1376 // recursively fetch the child group IDs
1377 while (count($tempChildGroupIDs)) {
1378 $tempChildGroupIDs = self
::getChildGroupIds($tempChildGroupIDs);
1379 if (count($tempChildGroupIDs)) {
1380 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1385 return $childGroupIDs;
1389 * Check parent groups and filter out the disabled ones.
1391 * @param array $parentArray
1392 * Array of group Ids.
1396 public static function filterActiveGroups($parentArray) {
1397 if (count($parentArray) > 1) {
1398 $result = civicrm_api3('Group', 'get', [
1399 'id' => ['IN' => $parentArray],
1400 'is_active' => TRUE,
1403 $activeParentGroupIDs = CRM_Utils_Array
::collect('id', $result['values']);
1404 foreach ($parentArray as $key => $groupID) {
1405 if (!array_key_exists($groupID, $activeParentGroupIDs)) {
1406 unset($parentArray[$key]);
1411 return reset($parentArray);