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 // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table
458 'group_id' => $group->id
,
459 'organization_id' => $params['organization_id'],
461 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
465 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($group->id
);
467 CRM_Utils_Hook
::post($hook, 'Group', $group->id
, $group);
470 if (CRM_Core_Permission
::check('edit groups')) {
471 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
472 // currently same permission we are using for delete a group
473 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
476 // add the recently added group (unless hidden: CRM-6432)
477 if (!$group->is_hidden
) {
478 CRM_Utils_Recent
::add($group->title
,
479 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
491 * Takes a sloppy mismash of params and creates two entities: a Group and a SavedSearch
492 * Currently only used by unit tests.
494 * @param array $params
495 * @return CRM_Contact_BAO_Group|NULL
498 public static function createSmartGroup($params) {
499 if (!empty($params['formValues'])) {
501 // Remove group parameters from sloppy mismash
502 unset($ssParams['id'], $ssParams['name'], $ssParams['title'], $ssParams['formValues'], $ssParams['saved_search_id']);
503 if (isset($params['saved_search_id'])) {
504 $ssParams['id'] = $params['saved_search_id'];
506 $ssParams['form_values'] = $params['formValues'];
507 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($ssParams);
509 $params['saved_search_id'] = $savedSearch->id
;
515 return self
::create($params);
519 * Update the is_active flag in the db.
522 * Id of the database record.
523 * @param bool $isActive
524 * Value we want to set the is_active field.
527 * true if we found and updated the object, else false
529 public static function setIsActive($id, $isActive) {
530 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
534 * Build the condition to retrieve groups.
536 * @param string $groupType
537 * Type of group(Access/Mailing) OR the key of the group.
538 * @param bool $excludeHidden exclude hidden groups.
542 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
544 if ($groupType == 'Mailing') {
545 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
547 elseif ($groupType == 'Access') {
548 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
550 elseif (!empty($groupType)) {
551 // ie we have been given the group key
552 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
556 if ($excludeHidden) {
557 $condition = "is_hidden = 0";
562 $condition .= " AND group_type LIKE '%$value%'";
565 $condition = "group_type LIKE '%$value%'";
573 * Get permission relevant clauses.
577 public static function getPermissionClause() {
578 if (!isset(Civi
::$statics[__CLASS__
]['permission_clause'])) {
579 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
583 //get the allowed groups for the current user
584 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
585 if (!empty($groups)) {
586 $groupList = implode(', ', array_values($groups));
587 $clause = "`groups`.id IN ( $groupList ) ";
593 Civi
::$statics[__CLASS__
]['permission_clause'] = $clause;
595 return Civi
::$statics[__CLASS__
]['permission_clause'];
599 * Flush caches that hold group data.
601 * (Actually probably some overkill at the moment.)
603 protected static function flushCaches() {
604 CRM_Utils_System
::flushCache();
606 'CRM_Core_PseudoConstant' => 'groups',
607 'CRM_ACL_API' => 'group_permission',
608 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
609 'CRM_Contact_BAO_Group' => 'permission_clause',
611 foreach ($staticCaches as $class => $key) {
612 if (isset(Civi
::$statics[$class][$key])) {
613 unset(Civi
::$statics[$class][$key]);
621 public function __toString() {
626 * This function create the hidden smart group when user perform
627 * contact search and want to send mailing to search contacts.
629 * @param array $params
630 * ( reference ) an assoc array of name/value pairs.
633 * ( smartGroupId, ssId ) smart group id and saved search id
635 public static function createHiddenSmartGroup($params) {
636 $ssId = $params['saved_search_id'] ??
NULL;
638 //add mapping record only for search builder saved search
640 if ($params['search_context'] == 'builder') {
641 //save the mapping for search builder
643 //save record in mapping table
645 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
647 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams);
648 $mappingId = $mapping->id
;
651 //get the mapping id from saved search
652 $savedSearch = new CRM_Contact_BAO_SavedSearch();
653 $savedSearch->id
= $ssId;
654 $savedSearch->find(TRUE);
655 $mappingId = $savedSearch->mapping_id
;
658 //save mapping fields
659 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
662 //create/update saved search record.
663 $savedSearch = new CRM_Contact_BAO_SavedSearch();
664 $savedSearch->id
= $ssId;
665 $formValues = $params['search_context'] === 'builder' ?
$params['form_values'] : CRM_Contact_BAO_Query
::convertFormValues($params['form_values']);
666 $savedSearch->form_values
= serialize($formValues);
667 $savedSearch->mapping_id
= $mappingId;
668 $savedSearch->search_custom_id
= $params['search_custom_id'] ??
NULL;
669 $savedSearch->save();
671 $ssId = $savedSearch->id
;
676 $smartGroupId = NULL;
677 if (!empty($params['saved_search_id'])) {
678 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
681 //create group only when new saved search.
683 'title' => "Hidden Smart Group {$ssId}",
684 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
685 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
686 'group_type' => $params['group_type'] ??
NULL,
687 'visibility' => $params['visibility'] ??
NULL,
688 'saved_search_id' => $ssId,
691 $smartGroup = self
::create($groupParams);
692 $smartGroupId = $smartGroup->id
;
695 // Update mapping with the name and description of the hidden smart group.
699 'name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
700 'description' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
701 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
703 CRM_Core_BAO_Mapping
::add($mappingParams);
706 return [$smartGroupId, $ssId];
710 * wrapper for ajax group selector.
712 * @param array $params
713 * Associated array for params record id.
716 * associated array of group list
719 * @todo there seems little reason for the small number of functions that call this to pass in
720 * params that then need to be translated in this function since they are coding them when calling
722 public static function getGroupListSelector(&$params) {
724 $params['offset'] = ($params['page'] - 1) * $params['rp'];
725 $params['rowCount'] = $params['rp'];
726 $params['sort'] = $params['sortBy'] ??
NULL;
729 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
731 //skip total if we are making call to show only children
732 if (empty($params['parent_id'])) {
734 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
736 // get all the groups
737 $allGroups = CRM_Core_PseudoConstant
::allGroup();
740 // format params and add links
742 foreach ($groups as $id => $value) {
744 $group['group_id'] = $value['id'];
745 $group['count'] = $value['count'];
746 $group['title'] = $value['title'];
748 // append parent names if in search mode
749 if (empty($params['parent_id']) && !empty($value['parents'])) {
750 $group['parent_id'] = $value['parents'];
751 $groupIds = explode(',', $value['parents']);
753 foreach ($groupIds as $gId) {
754 $title[] = $allGroups[$gId];
756 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
757 $value['class'] = array_diff($value['class'], ['crm-row-parent']);
759 $group['DT_RowId'] = 'row_' . $value['id'];
760 if (empty($params['parentsOnly'])) {
761 foreach ($value['class'] as $id => $class) {
762 if ($class == 'crm-group-parent') {
763 unset($value['class'][$id]);
767 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
768 $group['DT_RowAttr'] = [];
769 $group['DT_RowAttr']['data-id'] = $value['id'];
770 $group['DT_RowAttr']['data-entity'] = 'group';
772 $group['description'] = $value['description'] ??
NULL;
774 if (!empty($value['group_type'])) {
775 $group['group_type'] = $value['group_type'];
778 $group['group_type'] = '';
781 $group['visibility'] = $value['visibility'];
782 $group['links'] = $value['action'];
783 $group['org_info'] = $value['org_info'] ??
NULL;
784 $group['created_by'] = $value['created_by'] ??
NULL;
786 $group['is_parent'] = $value['is_parent'];
788 array_push($groupList, $group);
792 $groupsDT['data'] = $groupList;
793 $groupsDT['recordsTotal'] = !empty($params['total']) ?
$params['total'] : NULL;
794 $groupsDT['recordsFiltered'] = !empty($params['total']) ?
$params['total'] : NULL;
800 * This function to get list of groups.
802 * @param array $params
803 * Associated array for params.
807 public static function getGroupList(&$params) {
808 $whereClause = self
::whereClause($params, FALSE);
811 if (!empty($params['rowCount']) &&
812 $params['rowCount'] > 0
814 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
817 $orderBy = ' ORDER BY `groups`.title asc';
818 if (!empty($params['sort'])) {
819 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
821 // CRM-16905 - Sort by count cannot be done with sql
822 if (strpos($params['sort'], 'count') === 0) {
823 $orderBy = $limit = '';
827 $select = $from = $where = "";
829 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
830 CRM_Core_Permission
::isMultisiteEnabled()
832 $select = ", contact.display_name as org_name, contact.id as org_id";
833 $from = " LEFT JOIN civicrm_group_organization gOrg
834 ON gOrg.group_id = `groups`.id
835 LEFT JOIN civicrm_contact contact
836 ON contact.id = gOrg.organization_id ";
838 //get the Organization ID
839 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive');
841 $where = " AND gOrg.organization_id = {$orgID}";
848 SELECT `groups`.*, createdBy.sort_name as created_by {$select}
849 FROM civicrm_group `groups`
850 LEFT JOIN civicrm_contact createdBy
851 ON createdBy.id = `groups`.created_id
853 WHERE $whereClause {$where}
857 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
859 //FIXME CRM-4418, now we are handling delete separately
860 //if we introduce 'delete for group' make sure to handle here.
861 $groupPermissions = [CRM_Core_Permission
::VIEW
];
862 if (CRM_Core_Permission
::check('edit groups')) {
863 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
864 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
868 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
870 $links = self
::actionLinks($params);
872 $allTypes = CRM_Core_OptionGroup
::values('group_type');
875 $visibility = CRM_Core_SelectValues
::ufVisibility();
877 while ($object->fetch()) {
879 $values[$object->id
] = [
883 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
885 if ($object->saved_search_id
) {
886 $values[$object->id
]['class'][] = "crm-smart-group";
887 // check if custom search, if so fix view link
888 $customSearchID = CRM_Core_DAO
::getFieldValue(
889 'CRM_Contact_DAO_SavedSearch',
890 $object->saved_search_id
,
894 if ($customSearchID) {
895 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
896 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
900 $action = array_sum(array_keys($newLinks));
903 if (property_exists($object, 'is_reserved')) {
904 //if group is reserved and I don't have reserved permission, suppress delete/edit
905 if ($object->is_reserved
&& !$reservedPermission) {
906 $action -= CRM_Core_Action
::DELETE
;
907 $action -= CRM_Core_Action
::UPDATE
;
908 $action -= CRM_Core_Action
::DISABLE
;
912 if (property_exists($object, 'is_active')) {
913 if ($object->is_active
) {
914 $action -= CRM_Core_Action
::ENABLE
;
917 $values[$object->id
]['class'][] = 'disabled';
918 $action -= CRM_Core_Action
::VIEW
;
919 $action -= CRM_Core_Action
::DISABLE
;
923 $action = $action & CRM_Core_Action
::mask($groupPermissions);
925 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
927 if (isset($values[$object->id
]['group_type'])) {
928 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
929 substr($values[$object->id
]['group_type'], 1, -1)
932 foreach ($groupTypes as $type) {
933 $types[] = $allTypes[$type] ??
NULL;
935 $values[$object->id
]['group_type'] = implode(', ', $types);
938 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
942 'ssid' => $object->saved_search_id
,
946 'group.selector.row',
952 // If group has children, add class for link to view children
953 $values[$object->id
]['is_parent'] = FALSE;
954 if (array_key_exists('children', $values[$object->id
])) {
955 $values[$object->id
]['class'][] = "crm-group-parent";
956 $values[$object->id
]['is_parent'] = TRUE;
959 // If group is a child, add child class
960 if (array_key_exists('parents', $values[$object->id
])) {
961 $values[$object->id
]['class'][] = "crm-group-child";
965 if ($object->org_id
) {
966 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
967 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
971 $values[$object->id
]['org_info'] = '';
975 // Collapsed column if all cells are NULL
976 $values[$object->id
]['org_info'] = NULL;
978 if ($object->created_id
) {
979 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
980 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
983 // By default, we try to get a count of the contacts in each group
984 // to display to the user on the Manage Group page. However, if
985 // that will result in the cache being regenerated, then dipslay
986 // "unknown" instead to avoid a long wait for the user.
987 if (CRM_Contact_BAO_GroupContactCache
::shouldGroupBeRefreshed($object->id
)) {
988 $values[$object->id
]['count'] = ts('unknown');
991 $values[$object->id
]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id
]);
995 // CRM-16905 - Sort by count cannot be done with sql
996 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
997 usort($values, function($a, $b) {
998 return $a['count'] - $b['count'];
1000 if (strpos($params['sort'], 'desc')) {
1001 $values = array_reverse($values, TRUE);
1003 return array_slice($values, $params['offset'], $params['rowCount']);
1010 * This function to get hierarchical list of groups (parent followed by children)
1012 * @param array $groupIDs
1013 * Array of group ids.
1015 * @param string $parents
1016 * @param string $spacer
1017 * @param bool $titleOnly
1018 * @param bool $public
1022 public static function getGroupsHierarchy(
1025 $spacer = '<span class="child-indent"></span>',
1029 if (empty($groupIDs)) {
1033 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1034 // <span class="child-icon"></span>
1035 // need to return id, title (w/ spacer), description, visibility
1037 // We need to build a list of tags ordered by hierarchy and sorted by
1038 // name. The hierarchy will be communicated by an accumulation of
1039 // separators in front of the name to give it a visual offset.
1040 // Instead of recursively making mysql queries, we'll make one big
1041 // query and build the hierarchy with the algorithm below.
1043 $args = [1 => [$groupIdString, 'String']];
1045 SELECT id, title, frontend_title, description, frontend_description, visibility, parents, saved_search_id
1047 WHERE id IN $groupIdString
1050 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
1051 $parentArray = explode(',', $parents);
1052 $parent = self
::filterActiveGroups($parentArray);
1053 $args[2] = [$parent, 'Integer'];
1054 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1056 $query .= " ORDER BY title";
1057 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1059 // Sort the groups into the correct storage by the parent
1060 // $roots represent the current leaf nodes that need to be checked for
1061 // children. $rows represent the unplaced nodes
1062 // $tree contains the child nodes based on their parent_id.
1065 while ($dao->fetch()) {
1066 $title = $dao->title
;
1067 $description = $dao->description
;
1069 if (!empty($dao->frontend_title
)) {
1070 $title = $dao->frontend_title
;
1072 if (!empty($dao->frontend_description
)) {
1073 $description = $dao->frontend_description
;
1076 if ($dao->parents
) {
1077 $parentArray = explode(',', $dao->parents
);
1078 $parent = self
::filterActiveGroups($parentArray);
1079 $tree[$parent][] = [
1081 'title' => empty($dao->saved_search_id
) ?
$title : '* ' . $title,
1082 'visibility' => $dao->visibility
,
1083 'description' => $description,
1089 'title' => empty($dao->saved_search_id
) ?
$title : '* ' . $title,
1090 'visibility' => $dao->visibility
,
1091 'description' => $description,
1097 for ($i = 0; $i < count($roots); $i++
) {
1098 self
::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1105 * Build a list with groups on alphabetical order and child groups after the parent group.
1107 * This is a recursive function filling the $hierarchy parameter.
1109 * @param array $hierarchy
1110 * @param array $group
1111 * @param array $tree
1112 * @param bool $titleOnly
1113 * @param string $spacer
1116 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1117 $spaces = str_repeat($spacer, $level);
1120 $hierarchy[$group['id']] = $spaces . $group['title'];
1124 'id' => $group['id'],
1125 'text' => $spaces . $group['title'],
1126 'description' => $group['description'],
1127 'visibility' => $group['visibility'],
1131 // For performance reasons we use a for loop rather than a foreach.
1132 // Metrics for performance in an installation with 2867 groups a foreach
1133 // caused the function getGroupsHierarchy with a foreach execution takes
1134 // around 2.2 seconds (2,200 ms).
1135 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1136 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1137 for ($i = 0; $i < count($tree[$group['id']]); $i++
) {
1138 self
::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level +
1);
1144 * @param array $params
1146 * @return NULL|string
1148 public static function getGroupCount(&$params) {
1149 $whereClause = self
::whereClause($params, FALSE);
1150 $query = "SELECT COUNT(*) FROM civicrm_group `groups`";
1152 if (!empty($params['created_by'])) {
1154 INNER JOIN civicrm_contact createdBy
1155 ON createdBy.id = `groups`.created_id";
1158 WHERE {$whereClause}";
1159 return CRM_Core_DAO
::singleValueQuery($query, $params);
1163 * Generate permissioned where clause for group search.
1164 * @param array $params
1165 * @param bool $sortBy
1166 * @param bool $excludeHidden
1170 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1172 $title = $params['title'] ??
NULL;
1174 $clauses[] = "`groups`.title LIKE %1";
1175 if (strpos($title, '%') !== FALSE) {
1176 $params[1] = [$title, 'String', FALSE];
1179 $params[1] = [$title, 'String', TRUE];
1183 $groupType = $params['group_type'] ??
NULL;
1185 $types = explode(',', $groupType);
1186 if (!empty($types)) {
1187 $clauses[] = '`groups`.group_type LIKE %2';
1188 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1189 $params[2] = [$typeString, 'String', TRUE];
1193 $visibility = $params['visibility'] ??
NULL;
1195 $clauses[] = '`groups`.visibility = %3';
1196 $params[3] = [$visibility, 'String'];
1199 $groupStatus = $params['status'] ??
NULL;
1201 switch ($groupStatus) {
1203 $clauses[] = '`groups`.is_active = 1';
1204 $params[4] = [$groupStatus, 'Integer'];
1208 $clauses[] = '`groups`.is_active = 0';
1209 $params[4] = [$groupStatus, 'Integer'];
1213 $clauses[] = '(`groups`.is_active = 0 OR `groups`.is_active = 1 )';
1218 $parentsOnly = $params['parentsOnly'] ??
NULL;
1220 $clauses[] = '`groups`.parents IS NULL';
1223 $savedSearch = $params['savedSearch'] ??
NULL;
1224 if ($savedSearch == 1) {
1225 $clauses[] = '`groups`.saved_search_id IS NOT NULL';
1227 elseif ($savedSearch == 2) {
1228 $clauses[] = '`groups`.saved_search_id IS NULL';
1231 // only show child groups of a specific parent group
1232 $parent_id = $params['parent_id'] ??
NULL;
1234 $clauses[] = '`groups`.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1235 $params[5] = [$parent_id, 'Integer'];
1238 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1239 $clauses[] = "createdBy.sort_name LIKE %6";
1240 if (strpos($createdBy, '%') !== FALSE) {
1241 $params[6] = [$createdBy, 'String', FALSE];
1244 $params[6] = [$createdBy, 'String', TRUE];
1248 if (empty($clauses)) {
1249 $clauses[] = '`groups`.is_active = 1';
1252 if ($excludeHidden) {
1253 $clauses[] = '`groups`.is_hidden = 0';
1256 $clauses[] = self
::getPermissionClause();
1258 return implode(' AND ', $clauses);
1262 * Define action links.
1265 * array of action links
1267 public static function actionLinks($params) {
1268 // If component_mode is set we change the "View" link to match the requested component type
1269 if (!isset($params['component_mode'])) {
1270 $params['component_mode'] = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
1272 $modeValue = CRM_Contact_Form_Search
::getModeValue($params['component_mode']);
1274 CRM_Core_Action
::VIEW
=> [
1275 'name' => $modeValue['selectorLabel'],
1276 'url' => 'civicrm/group/search',
1277 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
1278 'title' => ts('Group Contacts'),
1280 CRM_Core_Action
::UPDATE
=> [
1281 'name' => ts('Settings'),
1282 'url' => 'civicrm/group',
1283 'qs' => 'reset=1&action=update&id=%%id%%',
1284 'title' => ts('Edit Group'),
1286 CRM_Core_Action
::DISABLE
=> [
1287 'name' => ts('Disable'),
1288 'ref' => 'crm-enable-disable',
1289 'title' => ts('Disable Group'),
1291 CRM_Core_Action
::ENABLE
=> [
1292 'name' => ts('Enable'),
1293 'ref' => 'crm-enable-disable',
1294 'title' => ts('Enable Group'),
1296 CRM_Core_Action
::DELETE
=> [
1297 'name' => ts('Delete'),
1298 'url' => 'civicrm/group',
1299 'qs' => 'reset=1&action=delete&id=%%id%%',
1300 'title' => ts('Delete Group'),
1308 * @param $whereClause
1309 * @param array $whereParams
1313 public function pagerAtoZ($whereClause, $whereParams) {
1315 SELECT DISTINCT UPPER(LEFT(`groups`.title, 1)) as sort_name
1316 FROM civicrm_group `groups`
1318 ORDER BY LEFT(`groups`.title, 1)
1320 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1322 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1326 * Assign Test Value.
1328 * @param string $fieldName
1329 * @param array $fieldDef
1330 * @param int $counter
1332 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1333 if ($fieldName == 'children' ||
$fieldName == 'parents') {
1334 $this->{$fieldName} = "NULL";
1337 parent
::assignTestValue($fieldName, $fieldDef, $counter);
1342 * Get child group ids
1344 * @param array $regularGroupIDs
1349 public static function getChildGroupIds($regularGroupIDs) {
1350 $childGroupIDs = [];
1352 foreach ((array) $regularGroupIDs as $regularGroupID) {
1353 // temporary store the child group ID(s) of regular group identified by $id,
1354 // later merge with main child group array
1355 $tempChildGroupIDs = [];
1356 // check that the regular group has any child group, if not then continue
1357 if ($childrenFound = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1358 $tempChildGroupIDs[] = $childrenFound;
1363 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1364 // so we need to convert it into array of child group IDs first
1365 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1366 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1367 // recursively fetch the child group IDs
1368 while (count($tempChildGroupIDs)) {
1369 $tempChildGroupIDs = self
::getChildGroupIds($tempChildGroupIDs);
1370 if (count($tempChildGroupIDs)) {
1371 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1376 return $childGroupIDs;
1380 * Check parent groups and filter out the disabled ones.
1382 * @param array $parentArray
1383 * Array of group Ids.
1387 public static function filterActiveGroups($parentArray) {
1388 if (count($parentArray) > 1) {
1389 $result = civicrm_api3('Group', 'get', [
1390 'id' => ['IN' => $parentArray],
1391 'is_active' => TRUE,
1394 $activeParentGroupIDs = CRM_Utils_Array
::collect('id', $result['values']);
1395 foreach ($parentArray as $key => $groupID) {
1396 if (!array_key_exists($groupID, $activeParentGroupIDs)) {
1397 unset($parentArray[$key]);
1402 return reset($parentArray);