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 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
57 $transaction = new CRM_Core_Transaction();
59 // added for CRM-1631 and CRM-1794
60 // delete all subscribed mails with the selected group id
61 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
62 $subscribe->group_id
= $id;
65 // delete all Subscription records with the selected group id
66 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
67 $subHistory->group_id
= $id;
68 $subHistory->delete();
70 // delete all crm_group_contact records with the selected group id
71 $groupContact = new CRM_Contact_DAO_GroupContact();
72 $groupContact->group_id
= $id;
73 $groupContact->delete();
75 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
76 $params = [1 => [$id, 'Integer']];
77 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
78 CRM_Core_DAO
::executeQuery($query, $params);
80 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
81 CRM_Core_DAO
::executeQuery($query, $params);
83 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
85 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
86 CRM_Core_DAO
::executeQuery($query, $params);
88 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
89 CRM_Core_DAO
::executeQuery($query, $params);
91 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
92 CRM_Core_DAO
::executeQuery($query, $params);
94 // delete from group table
95 $group = new CRM_Contact_DAO_Group();
99 $transaction->commit();
101 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
103 // delete the recently created Group
108 CRM_Utils_Recent
::del($groupRecent);
112 * Returns an array of the contacts in the given group.
116 public static function getGroupContacts($id) {
117 $params = [['group', 'IN', [1 => $id], 0, 0]];
118 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, ['contact_id']);
123 * Get the count of a members in a group with the specific status.
127 * @param string $status
128 * status of members in group
129 * @param bool $countChildGroups
132 * count of members in the group with above status
134 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
135 $groupContact = new CRM_Contact_DAO_GroupContact();
137 if ($countChildGroups) {
138 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
142 $contacts = self
::getGroupContacts($id);
144 foreach ($groupIds as $groupId) {
146 $groupContacts = self
::getGroupContacts($groupId);
147 foreach ($groupContacts as $gcontact) {
148 if ($groupId != $id) {
149 // Loop through main group's contacts
150 // and subtract from the count for each contact which
151 // matches one in the present group, if it is not the
153 foreach ($contacts as $contact) {
154 if ($contact['contact_id'] == $gcontact['contact_id']) {
160 $groupContact->group_id
= $groupId;
161 if (isset($status)) {
162 $groupContact->status
= $status;
164 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
165 $count +
= $groupContact->count();
171 * Get the list of member for a group id.
173 * @param int $groupID
174 * @param bool $useCache
176 * Number to limit to (or 0 for unlimited).
179 * this array contains the list of members for this group id
181 public static function getMember($groupID, $useCache = TRUE, $limit = 0) {
182 $params = [['group', '=', $groupID, 0, 0]];
183 $returnProperties = ['contact_id'];
184 list($contacts) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache);
187 foreach ($contacts as $contact) {
188 $aMembers[$contact['contact_id']] = 1;
195 * Returns array of group object(s) matching a set of one or Group properties.
197 * @param array $params
198 * Limits the set of groups returned.
199 * @param array $returnProperties
200 * Which properties should be included in the returned group objects.
201 * (member_count should be last element.)
202 * @param string $sort
204 * @param int $rowCount
207 * Array of group objects.
210 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
211 * add in essential fields (e.g. id). This should follow a regular pattern like the others
213 public static function getGroups(
215 $returnProperties = NULL,
220 $dao = new CRM_Contact_DAO_Group();
221 if (!isset($params['is_active'])) {
225 foreach ($params as $k => $v) {
226 if ($k == 'name' ||
$k == 'title') {
227 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
229 elseif ($k == 'group_type') {
230 foreach ((array) $v as $type) {
231 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
234 elseif (is_array($v)) {
235 foreach ($v as &$num) {
238 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
246 if ($offset ||
$rowCount) {
247 $offset = ($offset > 0) ?
$offset : 0;
248 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
249 $dao->limit($offset, $rowCount);
253 $dao->orderBy($sort);
256 // return only specific fields if returnproperties are sent
257 if (!empty($returnProperties)) {
259 $dao->selectAdd(implode(',', $returnProperties));
263 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
266 while ($dao->fetch()) {
267 $group = new CRM_Contact_DAO_Group();
269 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
271 $groups[] = clone($dao);
277 * Make sure that the user has permission to access this group.
280 * The id of the object.
281 * @param bool $excludeHidden
282 * Should hidden groups be excluded.
283 * Logically this is the wrong place to filter hidden groups out as that is
284 * not a permission issue. However, as other functions may rely on that defaulting to
285 * FALSE for now & only the api call is calling with true.
288 * The permission that the user has (or NULL)
290 public static function checkPermission($id, $excludeHidden = FALSE) {
291 $allGroups = CRM_Core_PseudoConstant
::allGroup(NULL, $excludeHidden);
294 if (CRM_Core_Permission
::check('edit all contacts') ||
295 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
296 'civicrm_saved_search', $allGroups
299 $permissions[] = CRM_Core_Permission
::EDIT
;
302 if (CRM_Core_Permission
::check('view all contacts') ||
303 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
304 'civicrm_saved_search', $allGroups
307 $permissions[] = CRM_Core_Permission
::VIEW
;
310 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
311 // Note: using !empty() in if condition, restricts the scope of delete
312 // permission to groups/contacts that are editable/viewable.
313 // We can remove this !empty condition once we have ACL support for delete functionality.
314 $permissions[] = CRM_Core_Permission
::DELETE
;
321 * Create a new group.
323 * @param array $params
325 * @return CRM_Contact_BAO_Group|NULL
326 * The new group BAO (if created)
328 public static function create(&$params) {
330 if (!empty($params['id'])) {
331 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
334 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
337 // If title isn't specified, retrieve it because we use it later, e.g.
338 // for RecentItems. But note we use array_key_exists not isset or empty
339 // since otherwise there would be no way to blank out an existing title.
340 // I'm not sure what the use-case is for that, but you're allowed to do it
342 if (!empty($params['id']) && !array_key_exists('title', $params)) {
344 $groupTitle = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $params['id'], 'title', 'id');
345 $params['title'] = $groupTitle;
347 catch (CRM_Core_Exception
$groupTitleException) {
352 // dev/core#287 Disable child groups if all parents are disabled.
353 if (!empty($params['id'])) {
354 $allChildGroupIds = self
::getChildGroupIds($params['id']);
355 foreach ($allChildGroupIds as $childKey => $childValue) {
356 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($childValue);
357 $activeParentsCount = civicrm_api3('Group', 'getcount', [
358 'id' => ['IN' => $parentIds],
361 if (count($parentIds) >= 1 && $activeParentsCount <= 1) {
362 $setDisable = self
::setIsActive($childValue, CRM_Utils_Array
::value('is_active', $params, 1));
366 // form the name only if missing: CRM-627
367 $nameParam = $params['name'] ??
NULL;
368 if (!$nameParam && empty($params['id'])) {
369 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
372 if (!empty($params['parents'])) {
373 $params['parents'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['parents']);
376 // convert params if array type
377 if (isset($params['group_type'])) {
378 $params['group_type'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['group_type']);
381 $params['group_type'] = NULL;
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 (!empty($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']) &&
409 $group->name
.= "_tmp";
417 if (empty($params['id']) &&
420 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
425 // add custom field values
426 if (!empty($params['custom'])) {
427 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
430 // make the group, child of domain/site group by default.
431 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
432 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
433 if (empty($params['parents']) &&
434 $domainGroupID != $group->id
&&
435 Civi
::settings()->get('is_enabled') &&
436 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
438 // if no parent present and the group doesn't already have any parents,
439 // make sure site group goes as parent
440 $params['parents'] = [$domainGroupID];
443 if (!empty($params['parents'])) {
444 foreach ($params['parents'] as $parentId) {
445 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
446 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
451 // this is always required, since we don't know when a
452 // parent group is removed
453 CRM_Contact_BAO_GroupNestingCache
::update();
455 // update group contact cache for all parent groups
456 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
457 foreach ($parentIds as $parentId) {
458 CRM_Contact_BAO_GroupContactCache
::add($parentId);
462 if (!empty($params['organization_id'])) {
463 // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table
465 'group_id' => $group->id
,
466 'organization_id' => $params['organization_id'],
468 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
472 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
474 if (!empty($params['id'])) {
475 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
478 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
482 if (CRM_Core_Permission
::check('edit groups')) {
483 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
484 // currently same permission we are using for delete a group
485 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
488 // add the recently added group (unless hidden: CRM-6432)
489 if (!$group->is_hidden
) {
490 CRM_Utils_Recent
::add($group->title
,
491 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
503 * Defines a new smart group.
505 * @param array $params
506 * Associative array of parameters.
508 * @return CRM_Contact_BAO_Group|NULL
509 * The new group BAO (if created)
511 public static function createSmartGroup(&$params) {
512 if (!empty($params['formValues'])) {
514 unset($ssParams['id']);
515 if (isset($ssParams['saved_search_id'])) {
516 $ssParams['id'] = $ssParams['saved_search_id'];
518 $params['form_values'] = $params['formValues'];
519 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
521 $params['saved_search_id'] = $savedSearch->id
;
527 return self
::create($params);
531 * Update the is_active flag in the db.
534 * Id of the database record.
535 * @param bool $isActive
536 * Value we want to set the is_active field.
539 * true if we found and updated the object, else false
541 public static function setIsActive($id, $isActive) {
542 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
546 * Build the condition to retrieve groups.
548 * @param string $groupType
549 * Type of group(Access/Mailing) OR the key of the group.
550 * @param bool $excludeHidden exclude hidden groups.
554 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
556 if ($groupType == 'Mailing') {
557 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
559 elseif ($groupType == 'Access') {
560 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
562 elseif (!empty($groupType)) {
563 // ie we have been given the group key
564 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
568 if ($excludeHidden) {
569 $condition = "is_hidden = 0";
574 $condition .= " AND group_type LIKE '%$value%'";
577 $condition = "group_type LIKE '%$value%'";
585 * Get permission relevant clauses.
589 public static function getPermissionClause() {
590 if (!isset(Civi
::$statics[__CLASS__
]['permission_clause'])) {
591 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
595 //get the allowed groups for the current user
596 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
597 if (!empty($groups)) {
598 $groupList = implode(', ', array_values($groups));
599 $clause = "`groups`.id IN ( $groupList ) ";
605 Civi
::$statics[__CLASS__
]['permission_clause'] = $clause;
607 return Civi
::$statics[__CLASS__
]['permission_clause'];
611 * Flush caches that hold group data.
613 * (Actually probably some overkill at the moment.)
615 protected static function flushCaches() {
616 CRM_Utils_System
::flushCache();
618 'CRM_Core_PseudoConstant' => 'groups',
619 'CRM_ACL_API' => 'group_permission',
620 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
621 'CRM_Contact_BAO_Group' => 'permission_clause',
623 foreach ($staticCaches as $class => $key) {
624 if (isset(Civi
::$statics[$class][$key])) {
625 unset(Civi
::$statics[$class][$key]);
633 public function __toString() {
638 * This function create the hidden smart group when user perform
639 * contact search and want to send mailing to search contacts.
641 * @param array $params
642 * ( reference ) an assoc array of name/value pairs.
645 * ( smartGroupId, ssId ) smart group id and saved search id
647 public static function createHiddenSmartGroup($params) {
648 $ssId = $params['saved_search_id'] ??
NULL;
650 //add mapping record only for search builder saved search
652 if ($params['search_context'] == 'builder') {
653 //save the mapping for search builder
655 //save record in mapping table
657 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
659 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams);
660 $mappingId = $mapping->id
;
663 //get the mapping id from saved search
664 $savedSearch = new CRM_Contact_BAO_SavedSearch();
665 $savedSearch->id
= $ssId;
666 $savedSearch->find(TRUE);
667 $mappingId = $savedSearch->mapping_id
;
670 //save mapping fields
671 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
674 //create/update saved search record.
675 $savedSearch = new CRM_Contact_BAO_SavedSearch();
676 $savedSearch->id
= $ssId;
677 $formValues = $params['search_context'] === 'builder' ?
$params['form_values'] : CRM_Contact_BAO_Query
::convertFormValues($params['form_values']);
678 $savedSearch->form_values
= serialize($formValues);
679 $savedSearch->mapping_id
= $mappingId;
680 $savedSearch->search_custom_id
= $params['search_custom_id'] ??
NULL;
681 $savedSearch->save();
683 $ssId = $savedSearch->id
;
688 $smartGroupId = NULL;
689 if (!empty($params['saved_search_id'])) {
690 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
693 //create group only when new saved search.
695 'title' => "Hidden Smart Group {$ssId}",
696 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
697 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
698 'group_type' => $params['group_type'] ??
NULL,
699 'visibility' => $params['visibility'] ??
NULL,
700 'saved_search_id' => $ssId,
703 $smartGroup = self
::create($groupParams);
704 $smartGroupId = $smartGroup->id
;
707 // Update mapping with the name and description of the hidden smart group.
711 'name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
712 'description' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
713 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
715 CRM_Core_BAO_Mapping
::add($mappingParams);
718 return [$smartGroupId, $ssId];
722 * wrapper for ajax group selector.
724 * @param array $params
725 * Associated array for params record id.
728 * associated array of group list
731 * @todo there seems little reason for the small number of functions that call this to pass in
732 * params that then need to be translated in this function since they are coding them when calling
734 public static function getGroupListSelector(&$params) {
736 $params['offset'] = ($params['page'] - 1) * $params['rp'];
737 $params['rowCount'] = $params['rp'];
738 $params['sort'] = $params['sortBy'] ??
NULL;
741 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
743 //skip total if we are making call to show only children
744 if (empty($params['parent_id'])) {
746 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
748 // get all the groups
749 $allGroups = CRM_Core_PseudoConstant
::allGroup();
752 // format params and add links
754 foreach ($groups as $id => $value) {
756 $group['group_id'] = $value['id'];
757 $group['count'] = $value['count'];
758 $group['title'] = $value['title'];
760 // append parent names if in search mode
761 if (empty($params['parent_id']) && !empty($value['parents'])) {
762 $group['parent_id'] = $value['parents'];
763 $groupIds = explode(',', $value['parents']);
765 foreach ($groupIds as $gId) {
766 $title[] = $allGroups[$gId];
768 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
769 $value['class'] = array_diff($value['class'], ['crm-row-parent']);
771 $group['DT_RowId'] = 'row_' . $value['id'];
772 if (empty($params['parentsOnly'])) {
773 foreach ($value['class'] as $id => $class) {
774 if ($class == 'crm-group-parent') {
775 unset($value['class'][$id]);
779 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
780 $group['DT_RowAttr'] = [];
781 $group['DT_RowAttr']['data-id'] = $value['id'];
782 $group['DT_RowAttr']['data-entity'] = 'group';
784 $group['description'] = $value['description'] ??
NULL;
786 if (!empty($value['group_type'])) {
787 $group['group_type'] = $value['group_type'];
790 $group['group_type'] = '';
793 $group['visibility'] = $value['visibility'];
794 $group['links'] = $value['action'];
795 $group['org_info'] = $value['org_info'] ??
NULL;
796 $group['created_by'] = $value['created_by'] ??
NULL;
798 $group['is_parent'] = $value['is_parent'];
800 array_push($groupList, $group);
804 $groupsDT['data'] = $groupList;
805 $groupsDT['recordsTotal'] = !empty($params['total']) ?
$params['total'] : NULL;
806 $groupsDT['recordsFiltered'] = !empty($params['total']) ?
$params['total'] : NULL;
812 * This function to get list of groups.
814 * @param array $params
815 * Associated array for params.
819 public static function getGroupList(&$params) {
820 $whereClause = self
::whereClause($params, FALSE);
823 if (!empty($params['rowCount']) &&
824 $params['rowCount'] > 0
826 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
829 $orderBy = ' ORDER BY `groups`.title asc';
830 if (!empty($params['sort'])) {
831 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
833 // CRM-16905 - Sort by count cannot be done with sql
834 if (strpos($params['sort'], 'count') === 0) {
835 $orderBy = $limit = '';
839 $select = $from = $where = "";
841 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
842 CRM_Core_Permission
::isMultisiteEnabled()
844 $select = ", contact.display_name as org_name, contact.id as org_id";
845 $from = " LEFT JOIN civicrm_group_organization gOrg
846 ON gOrg.group_id = `groups`.id
847 LEFT JOIN civicrm_contact contact
848 ON contact.id = gOrg.organization_id ";
850 //get the Organization ID
851 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive');
853 $where = " AND gOrg.organization_id = {$orgID}";
860 SELECT `groups`.*, createdBy.sort_name as created_by {$select}
861 FROM civicrm_group `groups`
862 LEFT JOIN civicrm_contact createdBy
863 ON createdBy.id = `groups`.created_id
865 WHERE $whereClause {$where}
869 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
871 //FIXME CRM-4418, now we are handling delete separately
872 //if we introduce 'delete for group' make sure to handle here.
873 $groupPermissions = [CRM_Core_Permission
::VIEW
];
874 if (CRM_Core_Permission
::check('edit groups')) {
875 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
876 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
880 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
882 $links = self
::actionLinks($params);
884 $allTypes = CRM_Core_OptionGroup
::values('group_type');
887 $visibility = CRM_Core_SelectValues
::ufVisibility();
889 while ($object->fetch()) {
891 $values[$object->id
] = [
895 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
897 if ($object->saved_search_id
) {
898 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
899 // check if custom search, if so fix view link
900 $customSearchID = CRM_Core_DAO
::getFieldValue(
901 'CRM_Contact_DAO_SavedSearch',
902 $object->saved_search_id
,
906 if ($customSearchID) {
907 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
908 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
912 $action = array_sum(array_keys($newLinks));
915 if (array_key_exists('is_reserved', $object)) {
916 //if group is reserved and I don't have reserved permission, suppress delete/edit
917 if ($object->is_reserved
&& !$reservedPermission) {
918 $action -= CRM_Core_Action
::DELETE
;
919 $action -= CRM_Core_Action
::UPDATE
;
920 $action -= CRM_Core_Action
::DISABLE
;
924 if (array_key_exists('is_active', $object)) {
925 if ($object->is_active
) {
926 $action -= CRM_Core_Action
::ENABLE
;
929 $values[$object->id
]['class'][] = 'disabled';
930 $action -= CRM_Core_Action
::VIEW
;
931 $action -= CRM_Core_Action
::DISABLE
;
935 $action = $action & CRM_Core_Action
::mask($groupPermissions);
937 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
939 if (isset($values[$object->id
]['group_type'])) {
940 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
941 substr($values[$object->id
]['group_type'], 1, -1)
944 foreach ($groupTypes as $type) {
945 $types[] = $allTypes[$type] ??
NULL;
947 $values[$object->id
]['group_type'] = implode(', ', $types);
950 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
954 'ssid' => $object->saved_search_id
,
958 'group.selector.row',
964 // If group has children, add class for link to view children
965 $values[$object->id
]['is_parent'] = FALSE;
966 if (array_key_exists('children', $values[$object->id
])) {
967 $values[$object->id
]['class'][] = "crm-group-parent";
968 $values[$object->id
]['is_parent'] = TRUE;
971 // If group is a child, add child class
972 if (array_key_exists('parents', $values[$object->id
])) {
973 $values[$object->id
]['class'][] = "crm-group-child";
977 if ($object->org_id
) {
978 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
979 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
983 $values[$object->id
]['org_info'] = '';
987 // Collapsed column if all cells are NULL
988 $values[$object->id
]['org_info'] = NULL;
990 if ($object->created_id
) {
991 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
992 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
995 // By default, we try to get a count of the contacts in each group
996 // to display to the user on the Manage Group page. However, if
997 // that will result in the cache being regenerated, then dipslay
998 // "unknown" instead to avoid a long wait for the user.
999 if (CRM_Contact_BAO_GroupContactCache
::shouldGroupBeRefreshed($object->id
)) {
1000 $values[$object->id
]['count'] = ts('unknown');
1003 $values[$object->id
]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id
]);
1007 // CRM-16905 - Sort by count cannot be done with sql
1008 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1009 usort($values, function($a, $b) {
1010 return $a['count'] - $b['count'];
1012 if (strpos($params['sort'], 'desc')) {
1013 $values = array_reverse($values, TRUE);
1015 return array_slice($values, $params['offset'], $params['rowCount']);
1022 * This function to get hierarchical list of groups (parent followed by children)
1024 * @param array $groupIDs
1025 * Array of group ids.
1027 * @param string $parents
1028 * @param string $spacer
1029 * @param bool $titleOnly
1033 public static function getGroupsHierarchy(
1036 $spacer = '<span class="child-indent"></span>',
1039 if (empty($groupIDs)) {
1043 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1044 // <span class="child-icon"></span>
1045 // need to return id, title (w/ spacer), description, visibility
1047 // We need to build a list of tags ordered by hierarchy and sorted by
1048 // name. The hierarchy will be communicated by an accumulation of
1049 // separators in front of the name to give it a visual offset.
1050 // Instead of recursively making mysql queries, we'll make one big
1051 // query and build the hierarchy with the algorithm below.
1053 $args = [1 => [$groupIdString, 'String']];
1055 SELECT id, title, description, visibility, parents
1057 WHERE id IN $groupIdString
1060 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
1061 $parentArray = explode(',', $parents);
1062 $parent = self
::filterActiveGroups($parentArray);
1063 $args[2] = [$parent, 'Integer'];
1064 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1066 $query .= " ORDER BY title";
1067 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1069 // Sort the groups into the correct storage by the parent
1070 // $roots represent the current leaf nodes that need to be checked for
1071 // children. $rows represent the unplaced nodes
1072 // $tree contains the child nodes based on their parent_id.
1075 while ($dao->fetch()) {
1076 if ($dao->parents
) {
1077 $parentArray = explode(',', $dao->parents
);
1078 $parent = self
::filterActiveGroups($parentArray);
1079 $tree[$parent][] = [
1081 'title' => $dao->title
,
1082 'visibility' => $dao->visibility
,
1083 'description' => $dao->description
,
1089 'title' => $dao->title
,
1090 'visibility' => $dao->visibility
,
1091 'description' => $dao->description
,
1097 for ($i = 0; $i < count($roots); $i++
) {
1098 self
::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1104 * Build a list with groups on alphabetical order and child groups after the parent group.
1106 * This is a recursive function filling the $hierarchy parameter.
1115 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1116 $spaces = str_repeat($spacer, $level);
1119 $hierarchy[$group['id']] = $spaces . $group['title'];
1122 $hierarchy[$group['id']] = [
1123 'title' => $spaces . $group['title'],
1124 'description' => $group['description'],
1125 'visibility' => $group['visibility'],
1129 // For performance reasons we use a for loop rather than a foreach.
1130 // Metrics for performance in an installation with 2867 groups a foreach
1131 // caused the function getGroupsHierarchy with a foreach execution takes
1132 // around 2.2 seoonds (2,200 ms).
1133 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1134 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1135 for ($i = 0; $i < count($tree[$group['id']]); $i++
) {
1136 self
::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level +
1);
1142 * @param array $params
1144 * @return NULL|string
1146 public static function getGroupCount(&$params) {
1147 $whereClause = self
::whereClause($params, FALSE);
1148 $query = "SELECT COUNT(*) FROM civicrm_group `groups`";
1150 if (!empty($params['created_by'])) {
1152 INNER JOIN civicrm_contact createdBy
1153 ON createdBy.id = `groups`.created_id";
1156 WHERE {$whereClause}";
1157 return CRM_Core_DAO
::singleValueQuery($query, $params);
1161 * Generate permissioned where clause for group search.
1162 * @param array $params
1163 * @param bool $sortBy
1164 * @param bool $excludeHidden
1168 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1170 $title = $params['title'] ??
NULL;
1172 $clauses[] = "`groups`.title LIKE %1";
1173 if (strpos($title, '%') !== FALSE) {
1174 $params[1] = [$title, 'String', FALSE];
1177 $params[1] = [$title, 'String', TRUE];
1181 $groupType = $params['group_type'] ??
NULL;
1183 $types = explode(',', $groupType);
1184 if (!empty($types)) {
1185 $clauses[] = '`groups`.group_type LIKE %2';
1186 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1187 $params[2] = [$typeString, 'String', TRUE];
1191 $visibility = $params['visibility'] ??
NULL;
1193 $clauses[] = '`groups`.visibility = %3';
1194 $params[3] = [$visibility, 'String'];
1197 $groupStatus = $params['status'] ??
NULL;
1199 switch ($groupStatus) {
1201 $clauses[] = '`groups`.is_active = 1';
1202 $params[4] = [$groupStatus, 'Integer'];
1206 $clauses[] = '`groups`.is_active = 0';
1207 $params[4] = [$groupStatus, 'Integer'];
1211 $clauses[] = '(`groups`.is_active = 0 OR `groups`.is_active = 1 )';
1216 $parentsOnly = $params['parentsOnly'] ??
NULL;
1218 $clauses[] = '`groups`.parents IS NULL';
1221 // only show child groups of a specific parent group
1222 $parent_id = $params['parent_id'] ??
NULL;
1224 $clauses[] = '`groups`.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1225 $params[5] = [$parent_id, 'Integer'];
1228 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1229 $clauses[] = "createdBy.sort_name LIKE %6";
1230 if (strpos($createdBy, '%') !== FALSE) {
1231 $params[6] = [$createdBy, 'String', FALSE];
1234 $params[6] = [$createdBy, 'String', TRUE];
1238 if (empty($clauses)) {
1239 $clauses[] = '`groups`.is_active = 1';
1242 if ($excludeHidden) {
1243 $clauses[] = '`groups`.is_hidden = 0';
1246 $clauses[] = self
::getPermissionClause();
1248 return implode(' AND ', $clauses);
1252 * Define action links.
1255 * array of action links
1257 public static function actionLinks($params) {
1258 // If component_mode is set we change the "View" link to match the requested component type
1259 if (!isset($params['component_mode'])) {
1260 $params['component_mode'] = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
1262 $modeValue = CRM_Contact_Form_Search
::getModeValue($params['component_mode']);
1264 CRM_Core_Action
::VIEW
=> [
1265 'name' => $modeValue['selectorLabel'],
1266 'url' => 'civicrm/group/search',
1267 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
1268 'title' => ts('Group Contacts'),
1270 CRM_Core_Action
::UPDATE
=> [
1271 'name' => ts('Settings'),
1272 'url' => 'civicrm/group',
1273 'qs' => 'reset=1&action=update&id=%%id%%',
1274 'title' => ts('Edit Group'),
1276 CRM_Core_Action
::DISABLE
=> [
1277 'name' => ts('Disable'),
1278 'ref' => 'crm-enable-disable',
1279 'title' => ts('Disable Group'),
1281 CRM_Core_Action
::ENABLE
=> [
1282 'name' => ts('Enable'),
1283 'ref' => 'crm-enable-disable',
1284 'title' => ts('Enable Group'),
1286 CRM_Core_Action
::DELETE
=> [
1287 'name' => ts('Delete'),
1288 'url' => 'civicrm/group',
1289 'qs' => 'reset=1&action=delete&id=%%id%%',
1290 'title' => ts('Delete Group'),
1298 * @param $whereClause
1299 * @param array $whereParams
1303 public function pagerAtoZ($whereClause, $whereParams) {
1305 SELECT DISTINCT UPPER(LEFT(`groups`.title, 1)) as sort_name
1306 FROM civicrm_group `groups`
1308 ORDER BY LEFT(`groups`.title, 1)
1310 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1312 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1316 * Assign Test Value.
1318 * @param string $fieldName
1319 * @param array $fieldDef
1320 * @param int $counter
1322 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1323 if ($fieldName == 'children' ||
$fieldName == 'parents') {
1324 $this->{$fieldName} = "NULL";
1327 parent
::assignTestValues($fieldName, $fieldDef, $counter);
1332 * Get child group ids
1334 * @param array $regularGroupIDs
1339 public static function getChildGroupIds($regularGroupIDs) {
1340 $childGroupIDs = [];
1342 foreach ((array) $regularGroupIDs as $regularGroupID) {
1343 // temporary store the child group ID(s) of regular group identified by $id,
1344 // later merge with main child group array
1345 $tempChildGroupIDs = [];
1346 // check that the regular group has any child group, if not then continue
1347 if ($childrenFound = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1348 $tempChildGroupIDs[] = $childrenFound;
1353 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1354 // so we need to convert it into array of child group IDs first
1355 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1356 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1357 // recursively fetch the child group IDs
1358 while (count($tempChildGroupIDs)) {
1359 $tempChildGroupIDs = self
::getChildGroupIds($tempChildGroupIDs);
1360 if (count($tempChildGroupIDs)) {
1361 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1366 return $childGroupIDs;
1370 * Check parent groups and filter out the disabled ones.
1372 * @param array $parentArray
1373 * Array of group Ids.
1377 public static function filterActiveGroups($parentArray) {
1378 if (count($parentArray) > 1) {
1379 $result = civicrm_api3('Group', 'get', [
1380 'id' => ['IN' => $parentArray],
1381 'is_active' => TRUE,
1384 $activeParentGroupIDs = CRM_Utils_Array
::collect('id', $result['values']);
1385 foreach ($parentArray as $key => $groupID) {
1386 if (!array_key_exists($groupID, $activeParentGroupIDs)) {
1387 unset($parentArray[$key]);
1392 return reset($parentArray);