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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contact_BAO_Group
extends CRM_Contact_DAO_Group
{
22 public function __construct() {
23 parent
::__construct();
27 * Retrieve DB object based on input parameters.
29 * It also stores all the retrieved values in the default array.
31 * @param array $params
32 * (reference ) an assoc array of name/value pairs.
33 * @param array $defaults
34 * (reference ) an assoc array to hold the flattened values.
36 * @return CRM_Contact_BAO_Group
38 public static function retrieve(&$params, &$defaults) {
39 $group = new CRM_Contact_DAO_Group();
40 $group->copyValues($params);
41 if ($group->find(TRUE)) {
42 CRM_Core_DAO
::storeValues($group, $defaults);
48 * Delete the group and all the object that connect to this group.
50 * Incredibly destructive.
52 * @param int $id Group id.
54 public static function discard($id) {
55 if (!$id ||
!is_numeric($id)) {
56 throw new CRM_Core_Exception('Invalid group request attempted');
58 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
60 $transaction = new CRM_Core_Transaction();
62 // added for CRM-1631 and CRM-1794
63 // delete all subscribed mails with the selected group id
64 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
65 $subscribe->group_id
= $id;
68 // delete all Subscription records with the selected group id
69 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
70 $subHistory->group_id
= $id;
71 $subHistory->delete();
73 // delete all crm_group_contact records with the selected group id
74 $groupContact = new CRM_Contact_DAO_GroupContact();
75 $groupContact->group_id
= $id;
76 $groupContact->delete();
78 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
79 $params = [1 => [$id, 'Integer']];
80 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
81 CRM_Core_DAO
::executeQuery($query, $params);
83 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
84 CRM_Core_DAO
::executeQuery($query, $params);
86 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
88 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
89 CRM_Core_DAO
::executeQuery($query, $params);
91 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
92 CRM_Core_DAO
::executeQuery($query, $params);
94 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
95 CRM_Core_DAO
::executeQuery($query, $params);
97 // delete from group table
98 $group = new CRM_Contact_DAO_Group();
102 $transaction->commit();
104 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
106 // delete the recently created Group
111 CRM_Utils_Recent
::del($groupRecent);
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 list($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 if (!empty($params['id'])) {
334 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
337 CRM_Utils_Hook
::pre('create', 'Group', 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 $setDisable = self
::setIsActive($childValue, CRM_Utils_Array
::value('is_active', $params, 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 (!empty($params['parents'])) {
376 $params['parents'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['parents']);
379 // convert params if array type
380 if (isset($params['group_type'])) {
381 $params['group_type'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['group_type']);
384 $params['group_type'] = NULL;
387 $session = CRM_Core_Session
::singleton();
388 $cid = $session->get('userID');
389 // this action is add
390 if ($cid && empty($params['id'])) {
391 $params['created_id'] = $cid;
393 // this action is update
394 if ($cid && !empty($params['id'])) {
395 $params['modified_id'] = $cid;
399 // Validate parents parameter when creating group.
400 if (!empty($params['parents'])) {
401 $parents = is_array($params['parents']) ?
array_keys($params['parents']) : (array) $params['parents'];
402 foreach ($parents as $parent) {
403 CRM_Utils_Type
::validate($parent, 'Integer');
406 $group = new CRM_Contact_BAO_Group();
407 $group->copyValues($params);
409 if (empty($params['id']) &&
412 $group->name
.= "_tmp";
420 if (empty($params['id']) &&
423 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
428 // add custom field values
429 if (!empty($params['custom'])) {
430 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
433 // make the group, child of domain/site group by default.
434 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
435 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
436 if (empty($params['parents']) &&
437 $domainGroupID != $group->id
&&
438 Civi
::settings()->get('is_enabled') &&
439 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
441 // if no parent present and the group doesn't already have any parents,
442 // make sure site group goes as parent
443 $params['parents'] = [$domainGroupID];
446 if (!empty($params['parents'])) {
447 foreach ($params['parents'] as $parentId) {
448 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
449 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
454 // this is always required, since we don't know when a
455 // parent group is removed
456 CRM_Contact_BAO_GroupNestingCache
::update();
458 // update group contact cache for all parent groups
459 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
460 foreach ($parentIds as $parentId) {
461 CRM_Contact_BAO_GroupContactCache
::add($parentId);
465 if (!empty($params['organization_id'])) {
466 // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table
468 'group_id' => $group->id
,
469 'organization_id' => $params['organization_id'],
471 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
475 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
477 if (!empty($params['id'])) {
478 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
481 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
485 if (CRM_Core_Permission
::check('edit groups')) {
486 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
487 // currently same permission we are using for delete a group
488 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
491 // add the recently added group (unless hidden: CRM-6432)
492 if (!$group->is_hidden
) {
493 CRM_Utils_Recent
::add($group->title
,
494 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
506 * Defines a new smart group.
508 * @param array $params
509 * Associative array of parameters.
511 * @return CRM_Contact_BAO_Group|NULL
512 * The new group BAO (if created)
514 public static function createSmartGroup(&$params) {
515 if (!empty($params['formValues'])) {
517 unset($ssParams['id']);
518 if (isset($ssParams['saved_search_id'])) {
519 $ssParams['id'] = $ssParams['saved_search_id'];
521 $params['form_values'] = $params['formValues'];
522 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
524 $params['saved_search_id'] = $savedSearch->id
;
530 return self
::create($params);
534 * Update the is_active flag in the db.
537 * Id of the database record.
538 * @param bool $isActive
539 * Value we want to set the is_active field.
542 * true if we found and updated the object, else false
544 public static function setIsActive($id, $isActive) {
545 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
549 * Build the condition to retrieve groups.
551 * @param string $groupType
552 * Type of group(Access/Mailing) OR the key of the group.
553 * @param bool $excludeHidden exclude hidden groups.
557 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
559 if ($groupType == 'Mailing') {
560 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
562 elseif ($groupType == 'Access') {
563 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
565 elseif (!empty($groupType)) {
566 // ie we have been given the group key
567 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
571 if ($excludeHidden) {
572 $condition = "is_hidden = 0";
577 $condition .= " AND group_type LIKE '%$value%'";
580 $condition = "group_type LIKE '%$value%'";
588 * Get permission relevant clauses.
592 public static function getPermissionClause() {
593 if (!isset(Civi
::$statics[__CLASS__
]['permission_clause'])) {
594 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
598 //get the allowed groups for the current user
599 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
600 if (!empty($groups)) {
601 $groupList = implode(', ', array_values($groups));
602 $clause = "`groups`.id IN ( $groupList ) ";
608 Civi
::$statics[__CLASS__
]['permission_clause'] = $clause;
610 return Civi
::$statics[__CLASS__
]['permission_clause'];
614 * Flush caches that hold group data.
616 * (Actually probably some overkill at the moment.)
618 protected static function flushCaches() {
619 CRM_Utils_System
::flushCache();
621 'CRM_Core_PseudoConstant' => 'groups',
622 'CRM_ACL_API' => 'group_permission',
623 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
624 'CRM_Contact_BAO_Group' => 'permission_clause',
626 foreach ($staticCaches as $class => $key) {
627 if (isset(Civi
::$statics[$class][$key])) {
628 unset(Civi
::$statics[$class][$key]);
636 public function __toString() {
641 * This function create the hidden smart group when user perform
642 * contact search and want to send mailing to search contacts.
644 * @param array $params
645 * ( reference ) an assoc array of name/value pairs.
648 * ( smartGroupId, ssId ) smart group id and saved search id
650 public static function createHiddenSmartGroup($params) {
651 $ssId = $params['saved_search_id'] ??
NULL;
653 //add mapping record only for search builder saved search
655 if ($params['search_context'] == 'builder') {
656 //save the mapping for search builder
658 //save record in mapping table
660 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
662 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams);
663 $mappingId = $mapping->id
;
666 //get the mapping id from saved search
667 $savedSearch = new CRM_Contact_BAO_SavedSearch();
668 $savedSearch->id
= $ssId;
669 $savedSearch->find(TRUE);
670 $mappingId = $savedSearch->mapping_id
;
673 //save mapping fields
674 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
677 //create/update saved search record.
678 $savedSearch = new CRM_Contact_BAO_SavedSearch();
679 $savedSearch->id
= $ssId;
680 $formValues = $params['search_context'] === 'builder' ?
$params['form_values'] : CRM_Contact_BAO_Query
::convertFormValues($params['form_values']);
681 $savedSearch->form_values
= serialize($formValues);
682 $savedSearch->mapping_id
= $mappingId;
683 $savedSearch->search_custom_id
= $params['search_custom_id'] ??
NULL;
684 $savedSearch->save();
686 $ssId = $savedSearch->id
;
691 $smartGroupId = NULL;
692 if (!empty($params['saved_search_id'])) {
693 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
696 //create group only when new saved search.
698 'title' => "Hidden Smart Group {$ssId}",
699 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
700 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
701 'group_type' => $params['group_type'] ??
NULL,
702 'visibility' => $params['visibility'] ??
NULL,
703 'saved_search_id' => $ssId,
706 $smartGroup = self
::create($groupParams);
707 $smartGroupId = $smartGroup->id
;
710 // Update mapping with the name and description of the hidden smart group.
714 'name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
715 'description' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
716 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
718 CRM_Core_BAO_Mapping
::add($mappingParams);
721 return [$smartGroupId, $ssId];
725 * wrapper for ajax group selector.
727 * @param array $params
728 * Associated array for params record id.
731 * associated array of group list
734 * @todo there seems little reason for the small number of functions that call this to pass in
735 * params that then need to be translated in this function since they are coding them when calling
737 public static function getGroupListSelector(&$params) {
739 $params['offset'] = ($params['page'] - 1) * $params['rp'];
740 $params['rowCount'] = $params['rp'];
741 $params['sort'] = $params['sortBy'] ??
NULL;
744 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
746 //skip total if we are making call to show only children
747 if (empty($params['parent_id'])) {
749 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
751 // get all the groups
752 $allGroups = CRM_Core_PseudoConstant
::allGroup();
755 // format params and add links
757 foreach ($groups as $id => $value) {
759 $group['group_id'] = $value['id'];
760 $group['count'] = $value['count'];
761 $group['title'] = $value['title'];
763 // append parent names if in search mode
764 if (empty($params['parent_id']) && !empty($value['parents'])) {
765 $group['parent_id'] = $value['parents'];
766 $groupIds = explode(',', $value['parents']);
768 foreach ($groupIds as $gId) {
769 $title[] = $allGroups[$gId];
771 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
772 $value['class'] = array_diff($value['class'], ['crm-row-parent']);
774 $group['DT_RowId'] = 'row_' . $value['id'];
775 if (empty($params['parentsOnly'])) {
776 foreach ($value['class'] as $id => $class) {
777 if ($class == 'crm-group-parent') {
778 unset($value['class'][$id]);
782 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
783 $group['DT_RowAttr'] = [];
784 $group['DT_RowAttr']['data-id'] = $value['id'];
785 $group['DT_RowAttr']['data-entity'] = 'group';
787 $group['description'] = $value['description'] ??
NULL;
789 if (!empty($value['group_type'])) {
790 $group['group_type'] = $value['group_type'];
793 $group['group_type'] = '';
796 $group['visibility'] = $value['visibility'];
797 $group['links'] = $value['action'];
798 $group['org_info'] = $value['org_info'] ??
NULL;
799 $group['created_by'] = $value['created_by'] ??
NULL;
801 $group['is_parent'] = $value['is_parent'];
803 array_push($groupList, $group);
807 $groupsDT['data'] = $groupList;
808 $groupsDT['recordsTotal'] = !empty($params['total']) ?
$params['total'] : NULL;
809 $groupsDT['recordsFiltered'] = !empty($params['total']) ?
$params['total'] : NULL;
815 * This function to get list of groups.
817 * @param array $params
818 * Associated array for params.
822 public static function getGroupList(&$params) {
823 $whereClause = self
::whereClause($params, FALSE);
826 if (!empty($params['rowCount']) &&
827 $params['rowCount'] > 0
829 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
832 $orderBy = ' ORDER BY `groups`.title asc';
833 if (!empty($params['sort'])) {
834 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
836 // CRM-16905 - Sort by count cannot be done with sql
837 if (strpos($params['sort'], 'count') === 0) {
838 $orderBy = $limit = '';
842 $select = $from = $where = "";
844 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
845 CRM_Core_Permission
::isMultisiteEnabled()
847 $select = ", contact.display_name as org_name, contact.id as org_id";
848 $from = " LEFT JOIN civicrm_group_organization gOrg
849 ON gOrg.group_id = `groups`.id
850 LEFT JOIN civicrm_contact contact
851 ON contact.id = gOrg.organization_id ";
853 //get the Organization ID
854 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive');
856 $where = " AND gOrg.organization_id = {$orgID}";
863 SELECT `groups`.*, createdBy.sort_name as created_by {$select}
864 FROM civicrm_group `groups`
865 LEFT JOIN civicrm_contact createdBy
866 ON createdBy.id = `groups`.created_id
868 WHERE $whereClause {$where}
872 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
874 //FIXME CRM-4418, now we are handling delete separately
875 //if we introduce 'delete for group' make sure to handle here.
876 $groupPermissions = [CRM_Core_Permission
::VIEW
];
877 if (CRM_Core_Permission
::check('edit groups')) {
878 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
879 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
883 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
885 $links = self
::actionLinks($params);
887 $allTypes = CRM_Core_OptionGroup
::values('group_type');
890 $visibility = CRM_Core_SelectValues
::ufVisibility();
892 while ($object->fetch()) {
894 $values[$object->id
] = [
898 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
900 if ($object->saved_search_id
) {
901 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
902 // check if custom search, if so fix view link
903 $customSearchID = CRM_Core_DAO
::getFieldValue(
904 'CRM_Contact_DAO_SavedSearch',
905 $object->saved_search_id
,
909 if ($customSearchID) {
910 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
911 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
915 $action = array_sum(array_keys($newLinks));
918 if (property_exists($object, 'is_reserved')) {
919 //if group is reserved and I don't have reserved permission, suppress delete/edit
920 if ($object->is_reserved
&& !$reservedPermission) {
921 $action -= CRM_Core_Action
::DELETE
;
922 $action -= CRM_Core_Action
::UPDATE
;
923 $action -= CRM_Core_Action
::DISABLE
;
927 if (property_exists($object, 'is_active')) {
928 if ($object->is_active
) {
929 $action -= CRM_Core_Action
::ENABLE
;
932 $values[$object->id
]['class'][] = 'disabled';
933 $action -= CRM_Core_Action
::VIEW
;
934 $action -= CRM_Core_Action
::DISABLE
;
938 $action = $action & CRM_Core_Action
::mask($groupPermissions);
940 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
942 if (isset($values[$object->id
]['group_type'])) {
943 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
944 substr($values[$object->id
]['group_type'], 1, -1)
947 foreach ($groupTypes as $type) {
948 $types[] = $allTypes[$type] ??
NULL;
950 $values[$object->id
]['group_type'] = implode(', ', $types);
953 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
957 'ssid' => $object->saved_search_id
,
961 'group.selector.row',
967 // If group has children, add class for link to view children
968 $values[$object->id
]['is_parent'] = FALSE;
969 if (array_key_exists('children', $values[$object->id
])) {
970 $values[$object->id
]['class'][] = "crm-group-parent";
971 $values[$object->id
]['is_parent'] = TRUE;
974 // If group is a child, add child class
975 if (array_key_exists('parents', $values[$object->id
])) {
976 $values[$object->id
]['class'][] = "crm-group-child";
980 if ($object->org_id
) {
981 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
982 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
986 $values[$object->id
]['org_info'] = '';
990 // Collapsed column if all cells are NULL
991 $values[$object->id
]['org_info'] = NULL;
993 if ($object->created_id
) {
994 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
995 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
998 // By default, we try to get a count of the contacts in each group
999 // to display to the user on the Manage Group page. However, if
1000 // that will result in the cache being regenerated, then dipslay
1001 // "unknown" instead to avoid a long wait for the user.
1002 if (CRM_Contact_BAO_GroupContactCache
::shouldGroupBeRefreshed($object->id
)) {
1003 $values[$object->id
]['count'] = ts('unknown');
1006 $values[$object->id
]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id
]);
1010 // CRM-16905 - Sort by count cannot be done with sql
1011 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1012 usort($values, function($a, $b) {
1013 return $a['count'] - $b['count'];
1015 if (strpos($params['sort'], 'desc')) {
1016 $values = array_reverse($values, TRUE);
1018 return array_slice($values, $params['offset'], $params['rowCount']);
1025 * This function to get hierarchical list of groups (parent followed by children)
1027 * @param array $groupIDs
1028 * Array of group ids.
1030 * @param string $parents
1031 * @param string $spacer
1032 * @param bool $titleOnly
1036 public static function getGroupsHierarchy(
1039 $spacer = '<span class="child-indent"></span>',
1042 if (empty($groupIDs)) {
1046 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1047 // <span class="child-icon"></span>
1048 // need to return id, title (w/ spacer), description, visibility
1050 // We need to build a list of tags ordered by hierarchy and sorted by
1051 // name. The hierarchy will be communicated by an accumulation of
1052 // separators in front of the name to give it a visual offset.
1053 // Instead of recursively making mysql queries, we'll make one big
1054 // query and build the hierarchy with the algorithm below.
1056 $args = [1 => [$groupIdString, 'String']];
1058 SELECT id, title, description, visibility, parents, saved_search_id
1060 WHERE id IN $groupIdString
1063 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
1064 $parentArray = explode(',', $parents);
1065 $parent = self
::filterActiveGroups($parentArray);
1066 $args[2] = [$parent, 'Integer'];
1067 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1069 $query .= " ORDER BY title";
1070 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1072 // Sort the groups into the correct storage by the parent
1073 // $roots represent the current leaf nodes that need to be checked for
1074 // children. $rows represent the unplaced nodes
1075 // $tree contains the child nodes based on their parent_id.
1078 while ($dao->fetch()) {
1079 if ($dao->parents
) {
1080 $parentArray = explode(',', $dao->parents
);
1081 $parent = self
::filterActiveGroups($parentArray);
1082 $tree[$parent][] = [
1084 'title' => empty($dao->saved_search_id
) ?
$dao->title
: '* ' . $dao->title
,
1085 'visibility' => $dao->visibility
,
1086 'description' => $dao->description
,
1092 'title' => empty($dao->saved_search_id
) ?
$dao->title
: '* ' . $dao->title
,
1093 'visibility' => $dao->visibility
,
1094 'description' => $dao->description
,
1100 for ($i = 0; $i < count($roots); $i++
) {
1101 self
::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1108 * Build a list with groups on alphabetical order and child groups after the parent group.
1110 * This is a recursive function filling the $hierarchy parameter.
1119 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1120 $spaces = str_repeat($spacer, $level);
1123 $hierarchy[$group['id']] = $spaces . $group['title'];
1127 'id' => $group['id'],
1128 'text' => $spaces . $group['title'],
1129 'description' => $group['description'],
1130 'visibility' => $group['visibility'],
1134 // For performance reasons we use a for loop rather than a foreach.
1135 // Metrics for performance in an installation with 2867 groups a foreach
1136 // caused the function getGroupsHierarchy with a foreach execution takes
1137 // around 2.2 seoonds (2,200 ms).
1138 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1139 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1140 for ($i = 0; $i < count($tree[$group['id']]); $i++
) {
1141 self
::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level +
1);
1147 * @param array $params
1149 * @return NULL|string
1151 public static function getGroupCount(&$params) {
1152 $whereClause = self
::whereClause($params, FALSE);
1153 $query = "SELECT COUNT(*) FROM civicrm_group `groups`";
1155 if (!empty($params['created_by'])) {
1157 INNER JOIN civicrm_contact createdBy
1158 ON createdBy.id = `groups`.created_id";
1161 WHERE {$whereClause}";
1162 return CRM_Core_DAO
::singleValueQuery($query, $params);
1166 * Generate permissioned where clause for group search.
1167 * @param array $params
1168 * @param bool $sortBy
1169 * @param bool $excludeHidden
1173 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1175 $title = $params['title'] ??
NULL;
1177 $clauses[] = "`groups`.title LIKE %1";
1178 if (strpos($title, '%') !== FALSE) {
1179 $params[1] = [$title, 'String', FALSE];
1182 $params[1] = [$title, 'String', TRUE];
1186 $groupType = $params['group_type'] ??
NULL;
1188 $types = explode(',', $groupType);
1189 if (!empty($types)) {
1190 $clauses[] = '`groups`.group_type LIKE %2';
1191 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1192 $params[2] = [$typeString, 'String', TRUE];
1196 $visibility = $params['visibility'] ??
NULL;
1198 $clauses[] = '`groups`.visibility = %3';
1199 $params[3] = [$visibility, 'String'];
1202 $groupStatus = $params['status'] ??
NULL;
1204 switch ($groupStatus) {
1206 $clauses[] = '`groups`.is_active = 1';
1207 $params[4] = [$groupStatus, 'Integer'];
1211 $clauses[] = '`groups`.is_active = 0';
1212 $params[4] = [$groupStatus, 'Integer'];
1216 $clauses[] = '(`groups`.is_active = 0 OR `groups`.is_active = 1 )';
1221 $parentsOnly = $params['parentsOnly'] ??
NULL;
1223 $clauses[] = '`groups`.parents IS NULL';
1226 $savedSearch = $params['savedSearch'] ??
NULL;
1227 if ($savedSearch == 1) {
1228 $clauses[] = '`groups`.saved_search_id IS NOT NULL';
1230 elseif ($savedSearch == 2) {
1231 $clauses[] = '`groups`.saved_search_id IS NULL';
1234 // only show child groups of a specific parent group
1235 $parent_id = $params['parent_id'] ??
NULL;
1237 $clauses[] = '`groups`.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1238 $params[5] = [$parent_id, 'Integer'];
1241 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1242 $clauses[] = "createdBy.sort_name LIKE %6";
1243 if (strpos($createdBy, '%') !== FALSE) {
1244 $params[6] = [$createdBy, 'String', FALSE];
1247 $params[6] = [$createdBy, 'String', TRUE];
1251 if (empty($clauses)) {
1252 $clauses[] = '`groups`.is_active = 1';
1255 if ($excludeHidden) {
1256 $clauses[] = '`groups`.is_hidden = 0';
1259 $clauses[] = self
::getPermissionClause();
1261 return implode(' AND ', $clauses);
1265 * Define action links.
1268 * array of action links
1270 public static function actionLinks($params) {
1271 // If component_mode is set we change the "View" link to match the requested component type
1272 if (!isset($params['component_mode'])) {
1273 $params['component_mode'] = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
1275 $modeValue = CRM_Contact_Form_Search
::getModeValue($params['component_mode']);
1277 CRM_Core_Action
::VIEW
=> [
1278 'name' => $modeValue['selectorLabel'],
1279 'url' => 'civicrm/group/search',
1280 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
1281 'title' => ts('Group Contacts'),
1283 CRM_Core_Action
::UPDATE
=> [
1284 'name' => ts('Settings'),
1285 'url' => 'civicrm/group',
1286 'qs' => 'reset=1&action=update&id=%%id%%',
1287 'title' => ts('Edit Group'),
1289 CRM_Core_Action
::DISABLE
=> [
1290 'name' => ts('Disable'),
1291 'ref' => 'crm-enable-disable',
1292 'title' => ts('Disable Group'),
1294 CRM_Core_Action
::ENABLE
=> [
1295 'name' => ts('Enable'),
1296 'ref' => 'crm-enable-disable',
1297 'title' => ts('Enable Group'),
1299 CRM_Core_Action
::DELETE
=> [
1300 'name' => ts('Delete'),
1301 'url' => 'civicrm/group',
1302 'qs' => 'reset=1&action=delete&id=%%id%%',
1303 'title' => ts('Delete Group'),
1311 * @param $whereClause
1312 * @param array $whereParams
1316 public function pagerAtoZ($whereClause, $whereParams) {
1318 SELECT DISTINCT UPPER(LEFT(`groups`.title, 1)) as sort_name
1319 FROM civicrm_group `groups`
1321 ORDER BY LEFT(`groups`.title, 1)
1323 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1325 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1329 * Assign Test Value.
1331 * @param string $fieldName
1332 * @param array $fieldDef
1333 * @param int $counter
1335 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1336 if ($fieldName == 'children' ||
$fieldName == 'parents') {
1337 $this->{$fieldName} = "NULL";
1340 parent
::assignTestValue($fieldName, $fieldDef, $counter);
1345 * Get child group ids
1347 * @param array $regularGroupIDs
1352 public static function getChildGroupIds($regularGroupIDs) {
1353 $childGroupIDs = [];
1355 foreach ((array) $regularGroupIDs as $regularGroupID) {
1356 // temporary store the child group ID(s) of regular group identified by $id,
1357 // later merge with main child group array
1358 $tempChildGroupIDs = [];
1359 // check that the regular group has any child group, if not then continue
1360 if ($childrenFound = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1361 $tempChildGroupIDs[] = $childrenFound;
1366 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1367 // so we need to convert it into array of child group IDs first
1368 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1369 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1370 // recursively fetch the child group IDs
1371 while (count($tempChildGroupIDs)) {
1372 $tempChildGroupIDs = self
::getChildGroupIds($tempChildGroupIDs);
1373 if (count($tempChildGroupIDs)) {
1374 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1379 return $childGroupIDs;
1383 * Check parent groups and filter out the disabled ones.
1385 * @param array $parentArray
1386 * Array of group Ids.
1390 public static function filterActiveGroups($parentArray) {
1391 if (count($parentArray) > 1) {
1392 $result = civicrm_api3('Group', 'get', [
1393 'id' => ['IN' => $parentArray],
1394 'is_active' => TRUE,
1397 $activeParentGroupIDs = CRM_Utils_Array
::collect('id', $result['values']);
1398 foreach ($parentArray as $key => $groupID) {
1399 if (!array_key_exists($groupID, $activeParentGroupIDs)) {
1400 unset($parentArray[$key]);
1405 return reset($parentArray);