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
{
24 public function __construct() {
25 parent
::__construct();
29 * Retrieve DB object based on input parameters.
31 * It also stores all the retrieved values in the default array.
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.
38 * @return CRM_Contact_BAO_Group
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);
50 * Delete the group and all the object that connect to this group.
52 * Incredibly destructive.
54 * @param int $id Group id.
56 public static function discard($id) {
57 if (!$id ||
!is_numeric($id)) {
58 throw new CRM_Core_Exception('Invalid group request attempted');
60 CRM_Utils_Hook
::pre('delete', 'Group', $id);
62 $transaction = new CRM_Core_Transaction();
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;
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();
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();
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);
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);
88 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
90 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
91 CRM_Core_DAO
::executeQuery($query, $params);
93 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
94 CRM_Core_DAO
::executeQuery($query, $params);
96 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
97 CRM_Core_DAO
::executeQuery($query, $params);
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();
111 // delete from group table
112 $group = new CRM_Contact_DAO_Group();
116 $transaction->commit();
118 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
120 // delete the recently created Group
125 CRM_Utils_Recent
::del($groupRecent);
129 * Returns an array of the contacts in the given group.
133 public static function getGroupContacts($id) {
134 $params = [['group', 'IN', [1 => $id], 0, 0]];
135 [$contacts] = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
140 * Get the count of a members in a group with the specific status.
144 * @param string $status
145 * status of members in group
146 * @param bool $countChildGroups
149 * count of members in the group with above status
151 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
152 $groupContact = new CRM_Contact_DAO_GroupContact();
154 if ($countChildGroups) {
155 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
159 $contacts = self
::getGroupContacts($id);
161 foreach ($groupIds as $groupId) {
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
170 foreach ($contacts as $contact) {
171 if ($contact['contact_id'] == $gcontact['contact_id']) {
177 $groupContact->group_id
= $groupId;
178 if (isset($status)) {
179 $groupContact->status
= $status;
181 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
182 $count +
= $groupContact->count();
188 * Get the list of member for a group id.
190 * @param int $groupID
191 * @param bool $useCache
193 * Number to limit to (or 0 for unlimited).
196 * this array contains the list of members for this group id
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);
204 foreach ($contacts as $contact) {
205 $aMembers[$contact['contact_id']] = 1;
212 * Returns array of group object(s) matching a set of one or Group properties.
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
221 * @param int $rowCount
224 * Array of group objects.
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
230 public static function getGroups(
232 $returnProperties = NULL,
237 $dao = new CRM_Contact_DAO_Group();
238 if (!isset($params['is_active'])) {
242 foreach ($params as $k => $v) {
243 if ($k == 'name' ||
$k == 'title') {
244 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
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
. "%'");
251 elseif (is_array($v)) {
252 foreach ($v as &$num) {
255 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
263 if ($offset ||
$rowCount) {
264 $offset = ($offset > 0) ?
$offset : 0;
265 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
266 $dao->limit($offset, $rowCount);
270 $dao->orderBy($sort);
273 // return only specific fields if returnproperties are sent
274 if (!empty($returnProperties)) {
276 $dao->selectAdd(implode(',', $returnProperties));
280 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
283 while ($dao->fetch()) {
284 $group = new CRM_Contact_DAO_Group();
286 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
288 $groups[] = clone($dao);
294 * Make sure that the user has permission to access this group.
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.
305 * The permission that the user has (or NULL)
307 public static function checkPermission($id, $excludeHidden = FALSE) {
308 $allGroups = CRM_Core_PseudoConstant
::allGroup(NULL, $excludeHidden);
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
316 $permissions[] = CRM_Core_Permission
::EDIT
;
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
324 $permissions[] = CRM_Core_Permission
::VIEW
;
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
;
338 * Create a new group.
340 * @param array $params
342 * @return CRM_Contact_BAO_Group|NULL
343 * The new group BAO (if created)
345 public static function create(&$params) {
347 if (!empty($params['id'])) {
348 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
351 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
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
359 if (!empty($params['id']) && !array_key_exists('title', $params)) {
361 $groupTitle = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $params['id'], 'title', 'id');
362 $params['title'] = $groupTitle;
364 catch (CRM_Core_Exception
$groupTitleException) {
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],
378 if (count($parentIds) >= 1 && $activeParentsCount <= 1) {
379 $setDisable = self
::setIsActive($childValue, CRM_Utils_Array
::value('is_active', $params, 1));
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']);
389 if (!empty($params['parents'])) {
390 $params['parents'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['parents']);
393 // convert params if array type
394 if (isset($params['group_type'])) {
395 $params['group_type'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['group_type']);
398 $params['group_type'] = NULL;
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;
407 // this action is update
408 if ($cid && !empty($params['id'])) {
409 $params['modified_id'] = $cid;
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');
420 $group = new CRM_Contact_BAO_Group();
421 $group->copyValues($params);
423 if (empty($params['id']) &&
426 $group->name
.= "_tmp";
434 if (empty($params['id']) &&
437 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
442 // add custom field values
443 if (!empty($params['custom'])) {
444 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
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
)
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];
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
);
468 // this is always required, since we don't know when a
469 // parent group is removed
470 CRM_Contact_BAO_GroupNestingCache
::update();
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);
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
482 'group_id' => $group->id
,
483 'organization_id' => $params['organization_id'],
485 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
489 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
491 if (!empty($params['id'])) {
492 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
495 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
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
);
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
),
520 * Takes a sloppy mismash of params and creates two entities: a Group and a SavedSearch
521 * Currently only used by unit tests.
523 * @param array $params
524 * @return CRM_Contact_BAO_Group|NULL
527 public static function createSmartGroup($params) {
528 if (!empty($params['formValues'])) {
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'];
535 $ssParams['form_values'] = $params['formValues'];
536 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($ssParams);
538 $params['saved_search_id'] = $savedSearch->id
;
544 return self
::create($params);
548 * Update the is_active flag in the db.
551 * Id of the database record.
552 * @param bool $isActive
553 * Value we want to set the is_active field.
556 * true if we found and updated the object, else false
558 public static function setIsActive($id, $isActive) {
559 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
563 * Build the condition to retrieve groups.
565 * @param string $groupType
566 * Type of group(Access/Mailing) OR the key of the group.
567 * @param bool $excludeHidden exclude hidden groups.
571 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
573 if ($groupType == 'Mailing') {
574 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
576 elseif ($groupType == 'Access') {
577 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
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
;
585 if ($excludeHidden) {
586 $condition = "is_hidden = 0";
591 $condition .= " AND group_type LIKE '%$value%'";
594 $condition = "group_type LIKE '%$value%'";
602 * Get permission relevant clauses.
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')) {
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 ) ";
622 Civi
::$statics[__CLASS__
]['permission_clause'] = $clause;
624 return Civi
::$statics[__CLASS__
]['permission_clause'];
628 * Flush caches that hold group data.
630 * (Actually probably some overkill at the moment.)
632 protected static function flushCaches() {
633 CRM_Utils_System
::flushCache();
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',
640 foreach ($staticCaches as $class => $key) {
641 if (isset(Civi
::$statics[$class][$key])) {
642 unset(Civi
::$statics[$class][$key]);
650 public function __toString() {
655 * This function create the hidden smart group when user perform
656 * contact search and want to send mailing to search contacts.
658 * @param array $params
659 * ( reference ) an assoc array of name/value pairs.
662 * ( smartGroupId, ssId ) smart group id and saved search id
664 public static function createHiddenSmartGroup($params) {
665 $ssId = $params['saved_search_id'] ??
NULL;
667 //add mapping record only for search builder saved search
669 if ($params['search_context'] == 'builder') {
670 //save the mapping for search builder
672 //save record in mapping table
674 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
676 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams);
677 $mappingId = $mapping->id
;
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
;
687 //save mapping fields
688 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
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();
700 $ssId = $savedSearch->id
;
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');
710 //create group only when new saved search.
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,
720 $smartGroup = self
::create($groupParams);
721 $smartGroupId = $smartGroup->id
;
724 // Update mapping with the name and description of the hidden smart group.
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'),
732 CRM_Core_BAO_Mapping
::add($mappingParams);
735 return [$smartGroupId, $ssId];
739 * wrapper for ajax group selector.
741 * @param array $params
742 * Associated array for params record id.
745 * associated array of group list
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
751 public static function getGroupListSelector(&$params) {
753 $params['offset'] = ($params['page'] - 1) * $params['rp'];
754 $params['rowCount'] = $params['rp'];
755 $params['sort'] = $params['sortBy'] ??
NULL;
758 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
760 //skip total if we are making call to show only children
761 if (empty($params['parent_id'])) {
763 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
765 // get all the groups
766 $allGroups = CRM_Core_PseudoConstant
::allGroup();
769 // format params and add links
771 foreach ($groups as $id => $value) {
773 $group['group_id'] = $value['id'];
774 $group['count'] = $value['count'];
775 $group['title'] = $value['title'];
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']);
782 foreach ($groupIds as $gId) {
783 $title[] = $allGroups[$gId];
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']);
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]);
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';
801 $group['description'] = $value['description'] ??
NULL;
803 if (!empty($value['group_type'])) {
804 $group['group_type'] = $value['group_type'];
807 $group['group_type'] = '';
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;
815 $group['is_parent'] = $value['is_parent'];
817 array_push($groupList, $group);
821 $groupsDT['data'] = $groupList;
822 $groupsDT['recordsTotal'] = !empty($params['total']) ?
$params['total'] : NULL;
823 $groupsDT['recordsFiltered'] = !empty($params['total']) ?
$params['total'] : NULL;
829 * This function to get list of groups.
831 * @param array $params
832 * Associated array for params.
836 public static function getGroupList(&$params) {
837 $whereClause = self
::whereClause($params, FALSE);
840 if (!empty($params['rowCount']) &&
841 $params['rowCount'] > 0
843 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
846 $orderBy = ' ORDER BY `groups`.title asc';
847 if (!empty($params['sort'])) {
848 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
850 // CRM-16905 - Sort by count cannot be done with sql
851 if (strpos($params['sort'], 'count') === 0) {
852 $orderBy = $limit = '';
856 $select = $from = $where = "";
858 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
859 CRM_Core_Permission
::isMultisiteEnabled()
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 ";
867 //get the Organization ID
868 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive');
870 $where = " AND gOrg.organization_id = {$orgID}";
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
882 WHERE $whereClause {$where}
886 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
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
;
897 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
899 $links = self
::actionLinks($params);
901 $allTypes = CRM_Core_OptionGroup
::values('group_type');
904 $visibility = CRM_Core_SelectValues
::ufVisibility();
906 while ($object->fetch()) {
908 $values[$object->id
] = [
912 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
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
,
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}";
929 $action = array_sum(array_keys($newLinks));
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
;
941 if (property_exists($object, 'is_active')) {
942 if ($object->is_active
) {
943 $action -= CRM_Core_Action
::ENABLE
;
946 $values[$object->id
]['class'][] = 'disabled';
947 $action -= CRM_Core_Action
::VIEW
;
948 $action -= CRM_Core_Action
::DISABLE
;
952 $action = $action & CRM_Core_Action
::mask($groupPermissions);
954 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
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)
961 foreach ($groupTypes as $type) {
962 $types[] = $allTypes[$type] ??
NULL;
964 $values[$object->id
]['group_type'] = implode(', ', $types);
967 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
971 'ssid' => $object->saved_search_id
,
975 'group.selector.row',
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;
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";
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>";
1000 $values[$object->id
]['org_info'] = '';
1004 // Collapsed column if all cells are NULL
1005 $values[$object->id
]['org_info'] = NULL;
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>";
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');
1020 $values[$object->id
]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id
]);
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'];
1029 if (strpos($params['sort'], 'desc')) {
1030 $values = array_reverse($values, TRUE);
1032 return array_slice($values, $params['offset'], $params['rowCount']);
1039 * This function to get hierarchical list of groups (parent followed by children)
1041 * @param array $groupIDs
1042 * Array of group ids.
1044 * @param string $parents
1045 * @param string $spacer
1046 * @param bool $titleOnly
1047 * @param bool $public
1051 public static function getGroupsHierarchy(
1054 $spacer = '<span class="child-indent"></span>',
1058 if (empty($groupIDs)) {
1062 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1063 // <span class="child-icon"></span>
1064 // need to return id, title (w/ spacer), description, visibility
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.
1072 $args = [1 => [$groupIdString, 'String']];
1074 SELECT id, title, frontend_title, description, frontend_description, visibility, parents, saved_search_id
1076 WHERE id IN $groupIdString
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";
1085 $query .= " ORDER BY title";
1086 $dao = CRM_Core_DAO
::executeQuery($query, $args);
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.
1094 while ($dao->fetch()) {
1095 $title = $dao->title
;
1096 $description = $dao->description
;
1098 if (!empty($dao->frontend_title
)) {
1099 $title = $dao->frontend_title
;
1101 if (!empty($dao->frontend_description
)) {
1102 $description = $dao->frontend_description
;
1105 if ($dao->parents
) {
1106 $parentArray = explode(',', $dao->parents
);
1107 $parent = self
::filterActiveGroups($parentArray);
1108 $tree[$parent][] = [
1110 'title' => empty($dao->saved_search_id
) ?
$title : '* ' . $title,
1111 'visibility' => $dao->visibility
,
1112 'description' => $description,
1118 'title' => empty($dao->saved_search_id
) ?
$title : '* ' . $title,
1119 'visibility' => $dao->visibility
,
1120 'description' => $description,
1126 for ($i = 0; $i < count($roots); $i++
) {
1127 self
::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1134 * Build a list with groups on alphabetical order and child groups after the parent group.
1136 * This is a recursive function filling the $hierarchy parameter.
1145 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1146 $spaces = str_repeat($spacer, $level);
1149 $hierarchy[$group['id']] = $spaces . $group['title'];
1153 'id' => $group['id'],
1154 'text' => $spaces . $group['title'],
1155 'description' => $group['description'],
1156 'visibility' => $group['visibility'],
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);
1173 * @param array $params
1175 * @return NULL|string
1177 public static function getGroupCount(&$params) {
1178 $whereClause = self
::whereClause($params, FALSE);
1179 $query = "SELECT COUNT(*) FROM civicrm_group `groups`";
1181 if (!empty($params['created_by'])) {
1183 INNER JOIN civicrm_contact createdBy
1184 ON createdBy.id = `groups`.created_id";
1187 WHERE {$whereClause}";
1188 return CRM_Core_DAO
::singleValueQuery($query, $params);
1192 * Generate permissioned where clause for group search.
1193 * @param array $params
1194 * @param bool $sortBy
1195 * @param bool $excludeHidden
1199 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1201 $title = $params['title'] ??
NULL;
1203 $clauses[] = "`groups`.title LIKE %1";
1204 if (strpos($title, '%') !== FALSE) {
1205 $params[1] = [$title, 'String', FALSE];
1208 $params[1] = [$title, 'String', TRUE];
1212 $groupType = $params['group_type'] ??
NULL;
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];
1222 $visibility = $params['visibility'] ??
NULL;
1224 $clauses[] = '`groups`.visibility = %3';
1225 $params[3] = [$visibility, 'String'];
1228 $groupStatus = $params['status'] ??
NULL;
1230 switch ($groupStatus) {
1232 $clauses[] = '`groups`.is_active = 1';
1233 $params[4] = [$groupStatus, 'Integer'];
1237 $clauses[] = '`groups`.is_active = 0';
1238 $params[4] = [$groupStatus, 'Integer'];
1242 $clauses[] = '(`groups`.is_active = 0 OR `groups`.is_active = 1 )';
1247 $parentsOnly = $params['parentsOnly'] ??
NULL;
1249 $clauses[] = '`groups`.parents IS NULL';
1252 $savedSearch = $params['savedSearch'] ??
NULL;
1253 if ($savedSearch == 1) {
1254 $clauses[] = '`groups`.saved_search_id IS NOT NULL';
1256 elseif ($savedSearch == 2) {
1257 $clauses[] = '`groups`.saved_search_id IS NULL';
1260 // only show child groups of a specific parent group
1261 $parent_id = $params['parent_id'] ??
NULL;
1263 $clauses[] = '`groups`.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1264 $params[5] = [$parent_id, 'Integer'];
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];
1273 $params[6] = [$createdBy, 'String', TRUE];
1277 if (empty($clauses)) {
1278 $clauses[] = '`groups`.is_active = 1';
1281 if ($excludeHidden) {
1282 $clauses[] = '`groups`.is_hidden = 0';
1285 $clauses[] = self
::getPermissionClause();
1287 return implode(' AND ', $clauses);
1291 * Define action links.
1294 * array of action links
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
;
1301 $modeValue = CRM_Contact_Form_Search
::getModeValue($params['component_mode']);
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'),
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'),
1315 CRM_Core_Action
::DISABLE
=> [
1316 'name' => ts('Disable'),
1317 'ref' => 'crm-enable-disable',
1318 'title' => ts('Disable Group'),
1320 CRM_Core_Action
::ENABLE
=> [
1321 'name' => ts('Enable'),
1322 'ref' => 'crm-enable-disable',
1323 'title' => ts('Enable Group'),
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'),
1337 * @param $whereClause
1338 * @param array $whereParams
1342 public function pagerAtoZ($whereClause, $whereParams) {
1344 SELECT DISTINCT UPPER(LEFT(`groups`.title, 1)) as sort_name
1345 FROM civicrm_group `groups`
1347 ORDER BY LEFT(`groups`.title, 1)
1349 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1351 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1355 * Assign Test Value.
1357 * @param string $fieldName
1358 * @param array $fieldDef
1359 * @param int $counter
1361 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1362 if ($fieldName == 'children' ||
$fieldName == 'parents') {
1363 $this->{$fieldName} = "NULL";
1366 parent
::assignTestValue($fieldName, $fieldDef, $counter);
1371 * Get child group ids
1373 * @param array $regularGroupIDs
1378 public static function getChildGroupIds($regularGroupIDs) {
1379 $childGroupIDs = [];
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;
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);
1405 return $childGroupIDs;
1409 * Check parent groups and filter out the disabled ones.
1411 * @param array $parentArray
1412 * Array of group Ids.
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,
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]);
1431 return reset($parentArray);