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 based on input parameters.
24 * It also stores all the retrieved values in the default array.
26 * @param array $params
27 * (reference ) an assoc array of name/value pairs.
28 * @param array $defaults
29 * (reference ) an assoc array to hold the flattened values.
31 * @return CRM_Contact_BAO_Group
33 public static function retrieve(&$params, &$defaults) {
34 $group = new CRM_Contact_DAO_Group();
35 $group->copyValues($params);
36 if ($group->find(TRUE)) {
37 CRM_Core_DAO
::storeValues($group, $defaults);
43 * Delete the group and all the object that connect to this group.
45 * Incredibly destructive.
47 * @param int $id Group id.
49 public static function discard($id) {
50 if (!$id ||
!is_numeric($id)) {
51 throw new CRM_Core_Exception('Invalid group request attempted');
53 CRM_Utils_Hook
::pre('delete', 'Group', $id);
55 $transaction = new CRM_Core_Transaction();
57 // added for CRM-1631 and CRM-1794
58 // delete all subscribed mails with the selected group id
59 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
60 $subscribe->group_id
= $id;
63 // delete all Subscription records with the selected group id
64 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
65 $subHistory->group_id
= $id;
66 $subHistory->delete();
68 // delete all crm_group_contact records with the selected group id
69 $groupContact = new CRM_Contact_DAO_GroupContact();
70 $groupContact->group_id
= $id;
71 $groupContact->delete();
73 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
74 $params = [1 => [$id, 'Integer']];
75 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
76 CRM_Core_DAO
::executeQuery($query, $params);
78 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
79 CRM_Core_DAO
::executeQuery($query, $params);
81 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
83 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
84 CRM_Core_DAO
::executeQuery($query, $params);
86 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
87 CRM_Core_DAO
::executeQuery($query, $params);
89 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
90 CRM_Core_DAO
::executeQuery($query, $params);
92 //check whether this group contains any saved searches and check if that saved search is appropriate to delete.
93 $groupDetails = Group
::get(FALSE)->addWhere('id', '=', $id)->execute();
94 if (!empty($groupDetails[0]['saved_search_id'])) {
95 $savedSearch = new CRM_Contact_DAO_SavedSearch();
96 $savedSearch->id
= $groupDetails[0]['saved_search_id'];
97 $savedSearch->find(TRUE);
98 // 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.
99 if (!empty($savedSearch->form_values
) && empty($savedSearch->api_entity
) && empty($savedSearch->api_params
)) {
100 $savedSearch->delete();
104 // delete from group table
105 $group = new CRM_Contact_DAO_Group();
109 $transaction->commit();
111 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
115 * Returns an array of the contacts in the given group.
119 public static function getGroupContacts($id) {
120 $params = [['group', 'IN', [1 => $id], 0, 0]];
121 [$contacts] = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
126 * Get the count of a members in a group with the specific status.
130 * @param string $status
131 * status of members in group
132 * @param bool $countChildGroups
135 * count of members in the group with above status
137 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
138 $groupContact = new CRM_Contact_DAO_GroupContact();
140 if ($countChildGroups) {
141 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
145 $contacts = self
::getGroupContacts($id);
147 foreach ($groupIds as $groupId) {
149 $groupContacts = self
::getGroupContacts($groupId);
150 foreach ($groupContacts as $gcontact) {
151 if ($groupId != $id) {
152 // Loop through main group's contacts
153 // and subtract from the count for each contact which
154 // matches one in the present group, if it is not the
156 foreach ($contacts as $contact) {
157 if ($contact['contact_id'] == $gcontact['contact_id']) {
163 $groupContact->group_id
= $groupId;
164 if (isset($status)) {
165 $groupContact->status
= $status;
167 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
168 $count +
= $groupContact->count();
174 * Get the list of member for a group id.
176 * @param int $groupID
177 * @param bool $useCache
179 * Number to limit to (or 0 for unlimited).
182 * this array contains the list of members for this group id
184 public static function getMember($groupID, $useCache = TRUE, $limit = 0) {
185 $params = [['group', '=', $groupID, 0, 0]];
186 $returnProperties = ['contact_id'];
187 list($contacts) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache);
190 foreach ($contacts as $contact) {
191 $aMembers[$contact['contact_id']] = 1;
198 * Returns array of group object(s) matching a set of one or Group properties.
200 * @param array $params
201 * Limits the set of groups returned.
202 * @param array $returnProperties
203 * Which properties should be included in the returned group objects.
204 * (member_count should be last element.)
205 * @param string $sort
207 * @param int $rowCount
210 * Array of group objects.
213 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
214 * add in essential fields (e.g. id). This should follow a regular pattern like the others
216 public static function getGroups(
218 $returnProperties = NULL,
223 $dao = new CRM_Contact_DAO_Group();
224 if (!isset($params['is_active'])) {
228 foreach ($params as $k => $v) {
229 if ($k == 'name' ||
$k == 'title') {
230 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
232 elseif ($k == 'group_type') {
233 foreach ((array) $v as $type) {
234 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
237 elseif (is_array($v)) {
238 foreach ($v as &$num) {
241 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
249 if ($offset ||
$rowCount) {
250 $offset = ($offset > 0) ?
$offset : 0;
251 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
252 $dao->limit($offset, $rowCount);
256 $dao->orderBy($sort);
259 // return only specific fields if returnproperties are sent
260 if (!empty($returnProperties)) {
262 $dao->selectAdd(implode(',', $returnProperties));
266 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
269 while ($dao->fetch()) {
270 $group = new CRM_Contact_DAO_Group();
272 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
274 $groups[] = clone($dao);
280 * Make sure that the user has permission to access this group.
283 * The id of the object.
284 * @param bool $excludeHidden
285 * Should hidden groups be excluded.
286 * Logically this is the wrong place to filter hidden groups out as that is
287 * not a permission issue. However, as other functions may rely on that defaulting to
288 * FALSE for now & only the api call is calling with true.
291 * The permission that the user has (or NULL)
293 public static function checkPermission($id, $excludeHidden = FALSE) {
294 $allGroups = CRM_Core_PseudoConstant
::allGroup(NULL, $excludeHidden);
297 if (CRM_Core_Permission
::check('edit all contacts') ||
298 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
299 'civicrm_saved_search', $allGroups
302 $permissions[] = CRM_Core_Permission
::EDIT
;
305 if (CRM_Core_Permission
::check('view all contacts') ||
306 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
307 'civicrm_saved_search', $allGroups
310 $permissions[] = CRM_Core_Permission
::VIEW
;
313 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
314 // Note: using !empty() in if condition, restricts the scope of delete
315 // permission to groups/contacts that are editable/viewable.
316 // We can remove this !empty condition once we have ACL support for delete functionality.
317 $permissions[] = CRM_Core_Permission
::DELETE
;
324 * Create a new group.
326 * @param array $params
328 * @return CRM_Contact_BAO_Group|NULL
329 * The new group BAO (if created)
331 public static function create(&$params) {
333 'group_type' => NULL,
337 $hook = empty($params['id']) ?
'create' : 'edit';
338 CRM_Utils_Hook
::pre($hook, 'Group', $params['id'] ??
NULL, $params);
340 // If title isn't specified, retrieve it because we use it later, e.g.
341 // for RecentItems. But note we use array_key_exists not isset or empty
342 // since otherwise there would be no way to blank out an existing title.
343 // I'm not sure what the use-case is for that, but you're allowed to do it
345 if (!empty($params['id']) && !array_key_exists('title', $params)) {
347 $groupTitle = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $params['id'], 'title', 'id');
348 $params['title'] = $groupTitle;
350 catch (CRM_Core_Exception
$groupTitleException) {
355 // dev/core#287 Disable child groups if all parents are disabled.
356 if (!empty($params['id'])) {
357 $allChildGroupIds = self
::getChildGroupIds($params['id']);
358 foreach ($allChildGroupIds as $childKey => $childValue) {
359 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($childValue);
360 $activeParentsCount = civicrm_api3('Group', 'getcount', [
361 'id' => ['IN' => $parentIds],
364 if (count($parentIds) >= 1 && $activeParentsCount <= 1) {
365 self
::setIsActive($childValue, (int) ($params['is_active'] ??
1));
369 // form the name only if missing: CRM-627
370 $nameParam = $params['name'] ??
NULL;
371 if (!$nameParam && empty($params['id'])) {
372 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
375 if (!CRM_Utils_System
::isNull($params['parents'])) {
376 $params['parents'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['parents']);
379 // convert params if array type
380 if (!CRM_Utils_System
::isNull($params['group_type'])) {
381 $params['group_type'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['group_type']);
384 $session = CRM_Core_Session
::singleton();
385 $cid = $session->get('userID');
386 // this action is add
387 if ($cid && empty($params['id'])) {
388 $params['created_id'] = $cid;
390 // this action is update
391 if ($cid && !empty($params['id'])) {
392 $params['modified_id'] = $cid;
396 // Validate parents parameter when creating group.
397 if (!CRM_Utils_System
::isNull($params['parents'])) {
398 $parents = is_array($params['parents']) ?
array_keys($params['parents']) : (array) $params['parents'];
399 foreach ($parents as $parent) {
400 CRM_Utils_Type
::validate($parent, 'Integer');
403 $group = new CRM_Contact_BAO_Group();
404 $group->copyValues($params);
406 if (empty($params['id']) && !$nameParam) {
407 $group->name
.= "_tmp";
415 // Enforce unique name by appending id
416 if (empty($params['id']) && !$nameParam) {
417 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
422 // add custom field values
423 if (!empty($params['custom'])) {
424 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
427 // make the group, child of domain/site group by default.
428 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
429 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
430 if (empty($params['parents']) &&
431 $domainGroupID != $group->id
&&
432 Civi
::settings()->get('is_enabled') &&
433 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
435 // if no parent present and the group doesn't already have any parents,
436 // make sure site group goes as parent
437 $params['parents'] = [$domainGroupID];
440 if (!CRM_Utils_System
::isNull($params['parents'])) {
441 foreach ($params['parents'] as $parentId) {
442 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
443 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
448 // this is always required, since we don't know when a
449 // parent group is removed
450 CRM_Contact_BAO_GroupNestingCache
::update();
452 // update group contact cache for all parent groups
453 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
454 foreach ($parentIds as $parentId) {
455 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($parentId);
459 if (!empty($params['organization_id'])) {
460 // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table
462 'group_id' => $group->id
,
463 'organization_id' => $params['organization_id'],
465 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
469 CRM_Contact_BAO_GroupContactCache
::invalidateGroupContactCache($group->id
);
471 CRM_Utils_Hook
::post($hook, 'Group', $group->id
, $group);
474 if (CRM_Core_Permission
::check('edit groups')) {
475 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
476 // currently same permission we are using for delete a group
477 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
480 // add the recently added group (unless hidden: CRM-6432)
481 if (!$group->is_hidden
) {
482 CRM_Utils_Recent
::add($group->title
,
483 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
495 * Takes a sloppy mismash of params and creates two entities: a Group and a SavedSearch
496 * Currently only used by unit tests.
498 * @param array $params
499 * @return CRM_Contact_BAO_Group|NULL
502 public static function createSmartGroup($params) {
503 if (!empty($params['formValues'])) {
505 // Remove group parameters from sloppy mismash
506 unset($ssParams['id'], $ssParams['name'], $ssParams['title'], $ssParams['formValues'], $ssParams['saved_search_id']);
507 if (isset($params['saved_search_id'])) {
508 $ssParams['id'] = $params['saved_search_id'];
510 $ssParams['form_values'] = $params['formValues'];
511 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($ssParams);
513 $params['saved_search_id'] = $savedSearch->id
;
519 return self
::create($params);
523 * Update the is_active flag in the db.
526 * Id of the database record.
527 * @param bool $isActive
528 * Value we want to set the is_active field.
531 * true if we found and updated the object, else false
533 public static function setIsActive($id, $isActive) {
534 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
538 * Build the condition to retrieve groups.
540 * @param string $groupType
541 * Type of group(Access/Mailing) OR the key of the group.
542 * @param bool $excludeHidden exclude hidden groups.
546 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
548 if ($groupType == 'Mailing') {
549 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
551 elseif ($groupType == 'Access') {
552 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
554 elseif (!empty($groupType)) {
555 // ie we have been given the group key
556 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
560 if ($excludeHidden) {
561 $condition = "is_hidden = 0";
566 $condition .= " AND group_type LIKE '%$value%'";
569 $condition = "group_type LIKE '%$value%'";
577 * Get permission relevant clauses.
581 public static function getPermissionClause() {
582 if (!isset(Civi
::$statics[__CLASS__
]['permission_clause'])) {
583 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
587 //get the allowed groups for the current user
588 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
589 if (!empty($groups)) {
590 $groupList = implode(', ', array_values($groups));
591 $clause = "`groups`.id IN ( $groupList ) ";
597 Civi
::$statics[__CLASS__
]['permission_clause'] = $clause;
599 return Civi
::$statics[__CLASS__
]['permission_clause'];
603 * Flush caches that hold group data.
605 * (Actually probably some overkill at the moment.)
607 protected static function flushCaches() {
608 CRM_Utils_System
::flushCache();
610 'CRM_Core_PseudoConstant' => 'groups',
611 'CRM_ACL_API' => 'group_permission',
612 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
613 'CRM_Contact_BAO_Group' => 'permission_clause',
615 foreach ($staticCaches as $class => $key) {
616 if (isset(Civi
::$statics[$class][$key])) {
617 unset(Civi
::$statics[$class][$key]);
625 public function __toString() {
630 * This function create the hidden smart group when user perform
631 * contact search and want to send mailing to search contacts.
633 * @param array $params
634 * ( reference ) an assoc array of name/value pairs.
637 * ( smartGroupId, ssId ) smart group id and saved search id
639 public static function createHiddenSmartGroup($params) {
640 $ssId = $params['saved_search_id'] ??
NULL;
642 //add mapping record only for search builder saved search
644 if ($params['search_context'] == 'builder') {
645 //save the mapping for search builder
647 //save record in mapping table
649 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
651 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams);
652 $mappingId = $mapping->id
;
655 //get the mapping id from saved search
656 $savedSearch = new CRM_Contact_BAO_SavedSearch();
657 $savedSearch->id
= $ssId;
658 $savedSearch->find(TRUE);
659 $mappingId = $savedSearch->mapping_id
;
662 //save mapping fields
663 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
666 //create/update saved search record.
667 $savedSearch = new CRM_Contact_BAO_SavedSearch();
668 $savedSearch->id
= $ssId;
669 $formValues = $params['search_context'] === 'builder' ?
$params['form_values'] : CRM_Contact_BAO_Query
::convertFormValues($params['form_values']);
670 $savedSearch->form_values
= serialize($formValues);
671 $savedSearch->mapping_id
= $mappingId;
672 $savedSearch->search_custom_id
= $params['search_custom_id'] ??
NULL;
673 $savedSearch->save();
675 $ssId = $savedSearch->id
;
680 $smartGroupId = NULL;
681 if (!empty($params['saved_search_id'])) {
682 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
685 //create group only when new saved search.
687 'title' => "Hidden Smart Group {$ssId}",
688 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
689 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
690 'group_type' => $params['group_type'] ??
NULL,
691 'visibility' => $params['visibility'] ??
NULL,
692 'saved_search_id' => $ssId,
695 $smartGroup = self
::create($groupParams);
696 $smartGroupId = $smartGroup->id
;
699 // Update mapping with the name and description of the hidden smart group.
703 'name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
704 'description' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
705 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
707 CRM_Core_BAO_Mapping
::add($mappingParams);
710 return [$smartGroupId, $ssId];
714 * wrapper for ajax group selector.
716 * @param array $params
717 * Associated array for params record id.
720 * associated array of group list
723 * @todo there seems little reason for the small number of functions that call this to pass in
724 * params that then need to be translated in this function since they are coding them when calling
726 public static function getGroupListSelector(&$params) {
728 $params['offset'] = ($params['page'] - 1) * $params['rp'];
729 $params['rowCount'] = $params['rp'];
730 $params['sort'] = $params['sortBy'] ??
NULL;
733 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
735 //skip total if we are making call to show only children
736 if (empty($params['parent_id'])) {
738 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
740 // get all the groups
741 $allGroups = CRM_Core_PseudoConstant
::allGroup();
744 // format params and add links
746 foreach ($groups as $id => $value) {
748 $group['group_id'] = $value['id'];
749 $group['count'] = $value['count'];
750 $group['title'] = $value['title'];
752 // append parent names if in search mode
753 if (empty($params['parent_id']) && !empty($value['parents'])) {
754 $group['parent_id'] = $value['parents'];
755 $groupIds = explode(',', $value['parents']);
757 foreach ($groupIds as $gId) {
758 $title[] = $allGroups[$gId];
760 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
761 $value['class'] = array_diff($value['class'], ['crm-row-parent']);
763 $group['DT_RowId'] = 'row_' . $value['id'];
764 if (empty($params['parentsOnly'])) {
765 foreach ($value['class'] as $id => $class) {
766 if ($class == 'crm-group-parent') {
767 unset($value['class'][$id]);
771 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
772 $group['DT_RowAttr'] = [];
773 $group['DT_RowAttr']['data-id'] = $value['id'];
774 $group['DT_RowAttr']['data-entity'] = 'group';
776 $group['description'] = $value['description'] ??
NULL;
778 if (!empty($value['group_type'])) {
779 $group['group_type'] = $value['group_type'];
782 $group['group_type'] = '';
785 $group['visibility'] = $value['visibility'];
786 $group['links'] = $value['action'];
787 $group['org_info'] = $value['org_info'] ??
NULL;
788 $group['created_by'] = $value['created_by'] ??
NULL;
790 $group['is_parent'] = $value['is_parent'];
792 array_push($groupList, $group);
796 $groupsDT['data'] = $groupList;
797 $groupsDT['recordsTotal'] = !empty($params['total']) ?
$params['total'] : NULL;
798 $groupsDT['recordsFiltered'] = !empty($params['total']) ?
$params['total'] : NULL;
804 * This function to get list of groups.
806 * @param array $params
807 * Associated array for params.
811 public static function getGroupList(&$params) {
812 $whereClause = self
::whereClause($params, FALSE);
815 if (!empty($params['rowCount']) &&
816 $params['rowCount'] > 0
818 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
821 $orderBy = ' ORDER BY `groups`.title asc';
822 if (!empty($params['sort'])) {
823 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
825 // CRM-16905 - Sort by count cannot be done with sql
826 if (strpos($params['sort'], 'count') === 0) {
827 $orderBy = $limit = '';
831 $select = $from = $where = "";
833 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
834 CRM_Core_Permission
::isMultisiteEnabled()
836 $select = ", contact.display_name as org_name, contact.id as org_id";
837 $from = " LEFT JOIN civicrm_group_organization gOrg
838 ON gOrg.group_id = `groups`.id
839 LEFT JOIN civicrm_contact contact
840 ON contact.id = gOrg.organization_id ";
842 //get the Organization ID
843 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive');
845 $where = " AND gOrg.organization_id = {$orgID}";
852 SELECT `groups`.*, createdBy.sort_name as created_by {$select}
853 FROM civicrm_group `groups`
854 LEFT JOIN civicrm_contact createdBy
855 ON createdBy.id = `groups`.created_id
857 WHERE $whereClause {$where}
861 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
863 //FIXME CRM-4418, now we are handling delete separately
864 //if we introduce 'delete for group' make sure to handle here.
865 $groupPermissions = [CRM_Core_Permission
::VIEW
];
866 if (CRM_Core_Permission
::check('edit groups')) {
867 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
868 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
872 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
874 $links = self
::actionLinks($params);
876 $allTypes = CRM_Core_OptionGroup
::values('group_type');
879 $visibility = CRM_Core_SelectValues
::ufVisibility();
881 while ($object->fetch()) {
883 $values[$object->id
] = [
887 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
889 if ($object->saved_search_id
) {
890 $values[$object->id
]['class'][] = "crm-smart-group";
891 // check if custom search, if so fix view link
892 $customSearchID = CRM_Core_DAO
::getFieldValue(
893 'CRM_Contact_DAO_SavedSearch',
894 $object->saved_search_id
,
898 if ($customSearchID) {
899 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
900 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
904 $action = array_sum(array_keys($newLinks));
907 if (property_exists($object, 'is_reserved')) {
908 //if group is reserved and I don't have reserved permission, suppress delete/edit
909 if ($object->is_reserved
&& !$reservedPermission) {
910 $action -= CRM_Core_Action
::DELETE
;
911 $action -= CRM_Core_Action
::UPDATE
;
912 $action -= CRM_Core_Action
::DISABLE
;
916 if (property_exists($object, 'is_active')) {
917 if ($object->is_active
) {
918 $action -= CRM_Core_Action
::ENABLE
;
921 $values[$object->id
]['class'][] = 'disabled';
922 $action -= CRM_Core_Action
::VIEW
;
923 $action -= CRM_Core_Action
::DISABLE
;
927 $action = $action & CRM_Core_Action
::mask($groupPermissions);
929 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
931 if (isset($values[$object->id
]['group_type'])) {
932 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
933 substr($values[$object->id
]['group_type'], 1, -1)
936 foreach ($groupTypes as $type) {
937 $types[] = $allTypes[$type] ??
NULL;
939 $values[$object->id
]['group_type'] = implode(', ', $types);
942 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
946 'ssid' => $object->saved_search_id
,
950 'group.selector.row',
956 // If group has children, add class for link to view children
957 $values[$object->id
]['is_parent'] = FALSE;
958 if (array_key_exists('children', $values[$object->id
])) {
959 $values[$object->id
]['class'][] = "crm-group-parent";
960 $values[$object->id
]['is_parent'] = TRUE;
963 // If group is a child, add child class
964 if (array_key_exists('parents', $values[$object->id
])) {
965 $values[$object->id
]['class'][] = "crm-group-child";
969 if ($object->org_id
) {
970 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
971 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
975 $values[$object->id
]['org_info'] = '';
979 // Collapsed column if all cells are NULL
980 $values[$object->id
]['org_info'] = NULL;
982 if ($object->created_id
) {
983 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
984 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
987 // By default, we try to get a count of the contacts in each group
988 // to display to the user on the Manage Group page. However, if
989 // that will result in the cache being regenerated, then dipslay
990 // "unknown" instead to avoid a long wait for the user.
991 if (CRM_Contact_BAO_GroupContactCache
::shouldGroupBeRefreshed($object->id
)) {
992 $values[$object->id
]['count'] = ts('unknown');
995 $values[$object->id
]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id
]);
999 // CRM-16905 - Sort by count cannot be done with sql
1000 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1001 usort($values, function($a, $b) {
1002 return $a['count'] - $b['count'];
1004 if (strpos($params['sort'], 'desc')) {
1005 $values = array_reverse($values, TRUE);
1007 return array_slice($values, $params['offset'], $params['rowCount']);
1014 * This function to get hierarchical list of groups (parent followed by children)
1016 * @param array $groupIDs
1017 * Array of group ids.
1019 * @param string $parents
1020 * @param string $spacer
1021 * @param bool $titleOnly
1022 * @param bool $public
1026 public static function getGroupsHierarchy(
1029 $spacer = '<span class="child-indent"></span>',
1033 if (empty($groupIDs)) {
1037 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1038 // <span class="child-icon"></span>
1039 // need to return id, title (w/ spacer), description, visibility
1041 // We need to build a list of tags ordered by hierarchy and sorted by
1042 // name. The hierarchy will be communicated by an accumulation of
1043 // separators in front of the name to give it a visual offset.
1044 // Instead of recursively making mysql queries, we'll make one big
1045 // query and build the hierarchy with the algorithm below.
1047 $args = [1 => [$groupIdString, 'String']];
1049 SELECT id, title, frontend_title, description, frontend_description, visibility, parents, saved_search_id
1051 WHERE id IN $groupIdString
1054 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
1055 $parentArray = explode(',', $parents);
1056 $parent = self
::filterActiveGroups($parentArray);
1057 $args[2] = [$parent, 'Integer'];
1058 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1060 $query .= " ORDER BY title";
1061 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1063 // Sort the groups into the correct storage by the parent
1064 // $roots represent the current leaf nodes that need to be checked for
1065 // children. $rows represent the unplaced nodes
1066 // $tree contains the child nodes based on their parent_id.
1069 while ($dao->fetch()) {
1070 $title = $dao->title
;
1071 $description = $dao->description
;
1073 if (!empty($dao->frontend_title
)) {
1074 $title = $dao->frontend_title
;
1076 if (!empty($dao->frontend_description
)) {
1077 $description = $dao->frontend_description
;
1080 if ($dao->parents
) {
1081 $parentArray = explode(',', $dao->parents
);
1082 $parent = self
::filterActiveGroups($parentArray);
1083 $tree[$parent][] = [
1085 'title' => empty($dao->saved_search_id
) ?
$title : '* ' . $title,
1086 'visibility' => $dao->visibility
,
1087 'description' => $description,
1093 'title' => empty($dao->saved_search_id
) ?
$title : '* ' . $title,
1094 'visibility' => $dao->visibility
,
1095 'description' => $description,
1101 for ($i = 0; $i < count($roots); $i++
) {
1102 self
::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1109 * Build a list with groups on alphabetical order and child groups after the parent group.
1111 * This is a recursive function filling the $hierarchy parameter.
1113 * @param array $hierarchy
1114 * @param array $group
1115 * @param array $tree
1116 * @param bool $titleOnly
1117 * @param string $spacer
1120 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1121 $spaces = str_repeat($spacer, $level);
1124 $hierarchy[$group['id']] = $spaces . $group['title'];
1128 'id' => $group['id'],
1129 'text' => $spaces . $group['title'],
1130 'description' => $group['description'],
1131 'visibility' => $group['visibility'],
1135 // For performance reasons we use a for loop rather than a foreach.
1136 // Metrics for performance in an installation with 2867 groups a foreach
1137 // caused the function getGroupsHierarchy with a foreach execution takes
1138 // around 2.2 seconds (2,200 ms).
1139 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1140 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1141 for ($i = 0; $i < count($tree[$group['id']]); $i++
) {
1142 self
::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level +
1);
1148 * @param array $params
1150 * @return NULL|string
1152 public static function getGroupCount(&$params) {
1153 $whereClause = self
::whereClause($params, FALSE);
1154 $query = "SELECT COUNT(*) FROM civicrm_group `groups`";
1156 if (!empty($params['created_by'])) {
1158 INNER JOIN civicrm_contact createdBy
1159 ON createdBy.id = `groups`.created_id";
1162 WHERE {$whereClause}";
1163 return CRM_Core_DAO
::singleValueQuery($query, $params);
1167 * Generate permissioned where clause for group search.
1168 * @param array $params
1169 * @param bool $sortBy
1170 * @param bool $excludeHidden
1174 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1176 $title = $params['title'] ??
NULL;
1178 $clauses[] = "`groups`.title LIKE %1";
1179 if (strpos($title, '%') !== FALSE) {
1180 $params[1] = [$title, 'String', FALSE];
1183 $params[1] = [$title, 'String', TRUE];
1187 $groupType = $params['group_type'] ??
NULL;
1189 $types = explode(',', $groupType);
1190 if (!empty($types)) {
1191 $clauses[] = '`groups`.group_type LIKE %2';
1192 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1193 $params[2] = [$typeString, 'String', TRUE];
1197 $visibility = $params['visibility'] ??
NULL;
1199 $clauses[] = '`groups`.visibility = %3';
1200 $params[3] = [$visibility, 'String'];
1203 $groupStatus = $params['status'] ??
NULL;
1205 switch ($groupStatus) {
1207 $clauses[] = '`groups`.is_active = 1';
1208 $params[4] = [$groupStatus, 'Integer'];
1212 $clauses[] = '`groups`.is_active = 0';
1213 $params[4] = [$groupStatus, 'Integer'];
1217 $clauses[] = '(`groups`.is_active = 0 OR `groups`.is_active = 1 )';
1222 $parentsOnly = $params['parentsOnly'] ??
NULL;
1224 $clauses[] = '`groups`.parents IS NULL';
1227 $savedSearch = $params['savedSearch'] ??
NULL;
1228 if ($savedSearch == 1) {
1229 $clauses[] = '`groups`.saved_search_id IS NOT NULL';
1231 elseif ($savedSearch == 2) {
1232 $clauses[] = '`groups`.saved_search_id IS NULL';
1235 // only show child groups of a specific parent group
1236 $parent_id = $params['parent_id'] ??
NULL;
1238 $clauses[] = '`groups`.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1239 $params[5] = [$parent_id, 'Integer'];
1242 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1243 $clauses[] = "createdBy.sort_name LIKE %6";
1244 if (strpos($createdBy, '%') !== FALSE) {
1245 $params[6] = [$createdBy, 'String', FALSE];
1248 $params[6] = [$createdBy, 'String', TRUE];
1252 if (empty($clauses)) {
1253 $clauses[] = '`groups`.is_active = 1';
1256 if ($excludeHidden) {
1257 $clauses[] = '`groups`.is_hidden = 0';
1260 $clauses[] = self
::getPermissionClause();
1262 return implode(' AND ', $clauses);
1266 * Define action links.
1269 * array of action links
1271 public static function actionLinks($params) {
1272 // If component_mode is set we change the "View" link to match the requested component type
1273 if (!isset($params['component_mode'])) {
1274 $params['component_mode'] = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
1276 $modeValue = CRM_Contact_Form_Search
::getModeValue($params['component_mode']);
1278 CRM_Core_Action
::VIEW
=> [
1279 'name' => $modeValue['selectorLabel'],
1280 'url' => 'civicrm/group/search',
1281 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
1282 'title' => ts('Group Contacts'),
1284 CRM_Core_Action
::UPDATE
=> [
1285 'name' => ts('Settings'),
1286 'url' => 'civicrm/group',
1287 'qs' => 'reset=1&action=update&id=%%id%%',
1288 'title' => ts('Edit Group'),
1290 CRM_Core_Action
::DISABLE
=> [
1291 'name' => ts('Disable'),
1292 'ref' => 'crm-enable-disable',
1293 'title' => ts('Disable Group'),
1295 CRM_Core_Action
::ENABLE
=> [
1296 'name' => ts('Enable'),
1297 'ref' => 'crm-enable-disable',
1298 'title' => ts('Enable Group'),
1300 CRM_Core_Action
::DELETE
=> [
1301 'name' => ts('Delete'),
1302 'url' => 'civicrm/group',
1303 'qs' => 'reset=1&action=delete&id=%%id%%',
1304 'title' => ts('Delete Group'),
1312 * @param $whereClause
1313 * @param array $whereParams
1317 public function pagerAtoZ($whereClause, $whereParams) {
1319 SELECT DISTINCT UPPER(LEFT(`groups`.title, 1)) as sort_name
1320 FROM civicrm_group `groups`
1322 ORDER BY LEFT(`groups`.title, 1)
1324 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1326 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1330 * Assign Test Value.
1332 * @param string $fieldName
1333 * @param array $fieldDef
1334 * @param int $counter
1336 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1337 if ($fieldName == 'children' ||
$fieldName == 'parents') {
1338 $this->{$fieldName} = "NULL";
1341 parent
::assignTestValue($fieldName, $fieldDef, $counter);
1346 * Get child group ids
1348 * @param array $regularGroupIDs
1353 public static function getChildGroupIds($regularGroupIDs) {
1354 $childGroupIDs = [];
1356 foreach ((array) $regularGroupIDs as $regularGroupID) {
1357 // temporary store the child group ID(s) of regular group identified by $id,
1358 // later merge with main child group array
1359 $tempChildGroupIDs = [];
1360 // check that the regular group has any child group, if not then continue
1361 if ($childrenFound = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1362 $tempChildGroupIDs[] = $childrenFound;
1367 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1368 // so we need to convert it into array of child group IDs first
1369 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1370 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1371 // recursively fetch the child group IDs
1372 while (count($tempChildGroupIDs)) {
1373 $tempChildGroupIDs = self
::getChildGroupIds($tempChildGroupIDs);
1374 if (count($tempChildGroupIDs)) {
1375 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1380 return $childGroupIDs;
1384 * Check parent groups and filter out the disabled ones.
1386 * @param array $parentArray
1387 * Array of group Ids.
1391 public static function filterActiveGroups($parentArray) {
1392 if (count($parentArray) > 1) {
1393 $result = civicrm_api3('Group', 'get', [
1394 'id' => ['IN' => $parentArray],
1395 'is_active' => TRUE,
1398 $activeParentGroupIDs = CRM_Utils_Array
::collect('id', $result['values']);
1399 foreach ($parentArray as $key => $groupID) {
1400 if (!array_key_exists($groupID, $activeParentGroupIDs)) {
1401 unset($parentArray[$key]);
1406 return reset($parentArray);