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 // dev/core#287 Disable child groups if all parents are disabled.
338 if (!empty($params['id'])) {
339 $allChildGroupIds = self
::getChildGroupIds($params['id']);
340 foreach ($allChildGroupIds as $childKey => $childValue) {
341 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($childValue);
342 $activeParentsCount = civicrm_api3('Group', 'getcount', [
343 'id' => ['IN' => $parentIds],
346 if (count($parentIds) >= 1 && $activeParentsCount <= 1) {
347 $setDisable = self
::setIsActive($childValue, CRM_Utils_Array
::value('is_active', $params, 1));
351 // form the name only if missing: CRM-627
352 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
353 if (!$nameParam && empty($params['id'])) {
354 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
357 if (!empty($params['parents'])) {
358 $params['parents'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['parents']);
361 // convert params if array type
362 if (isset($params['group_type'])) {
363 $params['group_type'] = CRM_Utils_Array
::convertCheckboxFormatToArray((array) $params['group_type']);
366 $params['group_type'] = NULL;
369 $session = CRM_Core_Session
::singleton();
370 $cid = $session->get('userID');
371 // this action is add
372 if ($cid && empty($params['id'])) {
373 $params['created_id'] = $cid;
375 // this action is update
376 if ($cid && !empty($params['id'])) {
377 $params['modified_id'] = $cid;
381 // Validate parents parameter when creating group.
382 if (!empty($params['parents'])) {
383 $parents = is_array($params['parents']) ?
array_keys($params['parents']) : (array) $params['parents'];
384 foreach ($parents as $parent) {
385 CRM_Utils_Type
::validate($parent, 'Integer');
388 $group = new CRM_Contact_BAO_Group();
389 $group->copyValues($params, TRUE);
391 if (empty($params['id']) &&
394 $group->name
.= "_tmp";
402 if (empty($params['id']) &&
405 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
410 // add custom field values
411 if (!empty($params['custom'])) {
412 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
415 // make the group, child of domain/site group by default.
416 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
417 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
418 if (empty($params['parents']) &&
419 $domainGroupID != $group->id
&&
420 Civi
::settings()->get('is_enabled') &&
421 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
423 // if no parent present and the group doesn't already have any parents,
424 // make sure site group goes as parent
425 $params['parents'] = [$domainGroupID];
428 if (!empty($params['parents'])) {
429 foreach ($params['parents'] as $parentId) {
430 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
431 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
436 // this is always required, since we don't know when a
437 // parent group is removed
438 CRM_Contact_BAO_GroupNestingCache
::update();
440 // update group contact cache for all parent groups
441 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
442 foreach ($parentIds as $parentId) {
443 CRM_Contact_BAO_GroupContactCache
::add($parentId);
447 if (!empty($params['organization_id'])) {
448 // dev/core#382 Keeping the id here can cause db errors as it tries to update the wrong record in the Organization table
450 'group_id' => $group->id
,
451 'organization_id' => $params['organization_id'],
453 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
457 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
459 if (!empty($params['id'])) {
460 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
463 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
467 if (CRM_Core_Permission
::check('edit groups')) {
468 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
469 // currently same permission we are using for delete a group
470 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
473 // add the recently added group (unless hidden: CRM-6432)
474 if (!$group->is_hidden
) {
475 CRM_Utils_Recent
::add($group->title
,
476 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
488 * Defines a new smart group.
490 * @param array $params
491 * Associative array of parameters.
493 * @return CRM_Contact_BAO_Group|NULL
494 * The new group BAO (if created)
496 public static function createSmartGroup(&$params) {
497 if (!empty($params['formValues'])) {
499 unset($ssParams['id']);
500 if (isset($ssParams['saved_search_id'])) {
501 $ssParams['id'] = $ssParams['saved_search_id'];
504 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
506 $params['saved_search_id'] = $savedSearch->id
;
512 return self
::create($params);
516 * Update the is_active flag in the db.
519 * Id of the database record.
520 * @param bool $isActive
521 * Value we want to set the is_active field.
524 * true if we found and updated the object, else false
526 public static function setIsActive($id, $isActive) {
527 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
531 * Build the condition to retrieve groups.
533 * @param string $groupType
534 * Type of group(Access/Mailing) OR the key of the group.
535 * @param bool $excludeHidden exclude hidden groups.
539 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
541 if ($groupType == 'Mailing') {
542 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
544 elseif ($groupType == 'Access') {
545 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
547 elseif (!empty($groupType)) {
548 // ie we have been given the group key
549 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
553 if ($excludeHidden) {
554 $condition = "is_hidden = 0";
559 $condition .= " AND group_type LIKE '%$value%'";
562 $condition = "group_type LIKE '%$value%'";
570 * Get permission relevant clauses.
574 public static function getPermissionClause() {
575 if (!isset(Civi
::$statics[__CLASS__
]['permission_clause'])) {
576 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
580 //get the allowed groups for the current user
581 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
582 if (!empty($groups)) {
583 $groupList = implode(', ', array_values($groups));
584 $clause = "groups.id IN ( $groupList ) ";
590 Civi
::$statics[__CLASS__
]['permission_clause'] = $clause;
592 return Civi
::$statics[__CLASS__
]['permission_clause'];
596 * Flush caches that hold group data.
598 * (Actually probably some overkill at the moment.)
600 protected static function flushCaches() {
601 CRM_Utils_System
::flushCache();
603 'CRM_Core_PseudoConstant' => 'groups',
604 'CRM_ACL_API' => 'group_permission',
605 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
606 'CRM_Contact_BAO_Group' => 'permission_clause',
608 foreach ($staticCaches as $class => $key) {
609 if (isset(Civi
::$statics[$class][$key])) {
610 unset(Civi
::$statics[$class][$key]);
618 public function __toString() {
623 * This function create the hidden smart group when user perform
624 * contact search and want to send mailing to search contacts.
626 * @param array $params
627 * ( reference ) an assoc array of name/value pairs.
630 * ( smartGroupId, ssId ) smart group id and saved search id
632 public static function createHiddenSmartGroup($params) {
633 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
635 //add mapping record only for search builder saved search
637 if ($params['search_context'] == 'builder') {
638 //save the mapping for search builder
640 //save record in mapping table
642 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
644 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams);
645 $mappingId = $mapping->id
;
648 //get the mapping id from saved search
649 $savedSearch = new CRM_Contact_BAO_SavedSearch();
650 $savedSearch->id
= $ssId;
651 $savedSearch->find(TRUE);
652 $mappingId = $savedSearch->mapping_id
;
655 //save mapping fields
656 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
659 //create/update saved search record.
660 $savedSearch = new CRM_Contact_BAO_SavedSearch();
661 $savedSearch->id
= $ssId;
662 $formValues = $params['search_context'] === 'builder' ?
$params['form_values'] : CRM_Contact_BAO_Query
::convertFormValues($params['form_values']);
663 $savedSearch->form_values
= serialize($formValues);
664 $savedSearch->mapping_id
= $mappingId;
665 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
666 $savedSearch->save();
668 $ssId = $savedSearch->id
;
673 $smartGroupId = NULL;
674 if (!empty($params['saved_search_id'])) {
675 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
678 //create group only when new saved search.
680 'title' => "Hidden Smart Group {$ssId}",
681 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
682 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
683 'group_type' => CRM_Utils_Array
::value('group_type', $params),
684 'visibility' => CRM_Utils_Array
::value('visibility', $params),
685 'saved_search_id' => $ssId,
688 $smartGroup = self
::create($groupParams);
689 $smartGroupId = $smartGroup->id
;
692 // Update mapping with the name and description of the hidden smart group.
696 'name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
697 'description' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
698 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Search Builder'),
700 CRM_Core_BAO_Mapping
::add($mappingParams);
703 return [$smartGroupId, $ssId];
707 * wrapper for ajax group selector.
709 * @param array $params
710 * Associated array for params record id.
713 * associated array of group list
716 * @todo there seems little reason for the small number of functions that call this to pass in
717 * params that then need to be translated in this function since they are coding them when calling
719 public static function getGroupListSelector(&$params) {
721 $params['offset'] = ($params['page'] - 1) * $params['rp'];
722 $params['rowCount'] = $params['rp'];
723 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
726 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
728 //skip total if we are making call to show only children
729 if (empty($params['parent_id'])) {
731 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
733 // get all the groups
734 $allGroups = CRM_Core_PseudoConstant
::allGroup();
737 // format params and add links
739 foreach ($groups as $id => $value) {
741 $group['group_id'] = $value['id'];
742 $group['count'] = $value['count'];
743 $group['title'] = $value['title'];
745 // append parent names if in search mode
746 if (empty($params['parent_id']) && !empty($value['parents'])) {
747 $group['parent_id'] = $value['parents'];
748 $groupIds = explode(',', $value['parents']);
750 foreach ($groupIds as $gId) {
751 $title[] = $allGroups[$gId];
753 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
754 $value['class'] = array_diff($value['class'], ['crm-row-parent']);
756 $group['DT_RowId'] = 'row_' . $value['id'];
757 if (empty($params['parentsOnly'])) {
758 foreach ($value['class'] as $id => $class) {
759 if ($class == 'crm-group-parent') {
760 unset($value['class'][$id]);
764 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
765 $group['DT_RowAttr'] = [];
766 $group['DT_RowAttr']['data-id'] = $value['id'];
767 $group['DT_RowAttr']['data-entity'] = 'group';
769 $group['description'] = CRM_Utils_Array
::value('description', $value);
771 if (!empty($value['group_type'])) {
772 $group['group_type'] = $value['group_type'];
775 $group['group_type'] = '';
778 $group['visibility'] = $value['visibility'];
779 $group['links'] = $value['action'];
780 $group['org_info'] = CRM_Utils_Array
::value('org_info', $value);
781 $group['created_by'] = CRM_Utils_Array
::value('created_by', $value);
783 $group['is_parent'] = $value['is_parent'];
785 array_push($groupList, $group);
789 $groupsDT['data'] = $groupList;
790 $groupsDT['recordsTotal'] = !empty($params['total']) ?
$params['total'] : NULL;
791 $groupsDT['recordsFiltered'] = !empty($params['total']) ?
$params['total'] : NULL;
797 * This function to get list of groups.
799 * @param array $params
800 * Associated array for params.
804 public static function getGroupList(&$params) {
805 $whereClause = self
::whereClause($params, FALSE);
808 if (!empty($params['rowCount']) &&
809 $params['rowCount'] > 0
811 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
814 $orderBy = ' ORDER BY groups.title asc';
815 if (!empty($params['sort'])) {
816 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
818 // CRM-16905 - Sort by count cannot be done with sql
819 if (strpos($params['sort'], 'count') === 0) {
820 $orderBy = $limit = '';
824 $select = $from = $where = "";
826 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
827 CRM_Core_Permission
::isMultisiteEnabled()
829 $select = ", contact.display_name as org_name, contact.id as org_id";
830 $from = " LEFT JOIN civicrm_group_organization gOrg
831 ON gOrg.group_id = groups.id
832 LEFT JOIN civicrm_contact contact
833 ON contact.id = gOrg.organization_id ";
835 //get the Organization ID
836 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive');
838 $where = " AND gOrg.organization_id = {$orgID}";
845 SELECT groups.*, createdBy.sort_name as created_by {$select}
846 FROM civicrm_group groups
847 LEFT JOIN civicrm_contact createdBy
848 ON createdBy.id = groups.created_id
850 WHERE $whereClause {$where}
854 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
856 //FIXME CRM-4418, now we are handling delete separately
857 //if we introduce 'delete for group' make sure to handle here.
858 $groupPermissions = [CRM_Core_Permission
::VIEW
];
859 if (CRM_Core_Permission
::check('edit groups')) {
860 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
861 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
865 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
867 $links = self
::actionLinks($params);
869 $allTypes = CRM_Core_OptionGroup
::values('group_type');
872 $visibility = CRM_Core_SelectValues
::ufVisibility();
874 while ($object->fetch()) {
876 $values[$object->id
] = [
880 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
882 if ($object->saved_search_id
) {
883 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
884 // check if custom search, if so fix view link
885 $customSearchID = CRM_Core_DAO
::getFieldValue(
886 'CRM_Contact_DAO_SavedSearch',
887 $object->saved_search_id
,
891 if ($customSearchID) {
892 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
893 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
897 $action = array_sum(array_keys($newLinks));
900 if (array_key_exists('is_reserved', $object)) {
901 //if group is reserved and I don't have reserved permission, suppress delete/edit
902 if ($object->is_reserved
&& !$reservedPermission) {
903 $action -= CRM_Core_Action
::DELETE
;
904 $action -= CRM_Core_Action
::UPDATE
;
905 $action -= CRM_Core_Action
::DISABLE
;
909 if (array_key_exists('is_active', $object)) {
910 if ($object->is_active
) {
911 $action -= CRM_Core_Action
::ENABLE
;
914 $values[$object->id
]['class'][] = 'disabled';
915 $action -= CRM_Core_Action
::VIEW
;
916 $action -= CRM_Core_Action
::DISABLE
;
920 $action = $action & CRM_Core_Action
::mask($groupPermissions);
922 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
924 if (isset($values[$object->id
]['group_type'])) {
925 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
926 substr($values[$object->id
]['group_type'], 1, -1)
929 foreach ($groupTypes as $type) {
930 $types[] = CRM_Utils_Array
::value($type, $allTypes);
932 $values[$object->id
]['group_type'] = implode(', ', $types);
935 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
939 'ssid' => $object->saved_search_id
,
943 'group.selector.row',
949 // If group has children, add class for link to view children
950 $values[$object->id
]['is_parent'] = FALSE;
951 if (array_key_exists('children', $values[$object->id
])) {
952 $values[$object->id
]['class'][] = "crm-group-parent";
953 $values[$object->id
]['is_parent'] = TRUE;
956 // If group is a child, add child class
957 if (array_key_exists('parents', $values[$object->id
])) {
958 $values[$object->id
]['class'][] = "crm-group-child";
962 if ($object->org_id
) {
963 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
964 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
968 $values[$object->id
]['org_info'] = '';
972 // Collapsed column if all cells are NULL
973 $values[$object->id
]['org_info'] = NULL;
975 if ($object->created_id
) {
976 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
977 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
980 // By default, we try to get a count of the contacts in each group
981 // to display to the user on the Manage Group page. However, if
982 // that will result in the cache being regenerated, then dipslay
983 // "unknown" instead to avoid a long wait for the user.
984 if (CRM_Contact_BAO_GroupContactCache
::shouldGroupBeRefreshed($object->id
)) {
985 $values[$object->id
]['count'] = ts('unknown');
988 $values[$object->id
]['count'] = civicrm_api3('Contact', 'getcount', ['group' => $object->id
]);
992 // CRM-16905 - Sort by count cannot be done with sql
993 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
994 usort($values, function($a, $b) {
995 return $a['count'] - $b['count'];
997 if (strpos($params['sort'], 'desc')) {
998 $values = array_reverse($values, TRUE);
1000 return array_slice($values, $params['offset'], $params['rowCount']);
1007 * This function to get hierarchical list of groups (parent followed by children)
1009 * @param array $groupIDs
1010 * Array of group ids.
1012 * @param string $parents
1013 * @param string $spacer
1014 * @param bool $titleOnly
1018 public static function getGroupsHierarchy(
1021 $spacer = '<span class="child-indent"></span>',
1024 if (empty($groupIDs)) {
1028 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1029 // <span class="child-icon"></span>
1030 // need to return id, title (w/ spacer), description, visibility
1032 // We need to build a list of tags ordered by hierarchy and sorted by
1033 // name. The hierarchy will be communicated by an accumulation of
1034 // separators in front of the name to give it a visual offset.
1035 // Instead of recursively making mysql queries, we'll make one big
1036 // query and build the hierarchy with the algorithm below.
1038 $args = [1 => [$groupIdString, 'String']];
1040 SELECT id, title, description, visibility, parents
1042 WHERE id IN $groupIdString
1045 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5').
1046 $parentArray = explode(',', $parents);
1047 $parent = self
::filterActiveGroups($parentArray);
1048 $args[2] = [$parent, 'Integer'];
1049 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1051 $query .= " ORDER BY title";
1052 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1054 // Sort the groups into the correct storage by the parent
1055 // $roots represent the current leaf nodes that need to be checked for
1056 // children. $rows represent the unplaced nodes
1057 // $tree contains the child nodes based on their parent_id.
1060 while ($dao->fetch()) {
1061 if ($dao->parents
) {
1062 $parentArray = explode(',', $dao->parents
);
1063 $parent = self
::filterActiveGroups($parentArray);
1064 $tree[$parent][] = [
1066 'title' => $dao->title
,
1067 'visibility' => $dao->visibility
,
1068 'description' => $dao->description
,
1074 'title' => $dao->title
,
1075 'visibility' => $dao->visibility
,
1076 'description' => $dao->description
,
1082 for ($i = 0; $i < count($roots); $i++
) {
1083 self
::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1089 * Build a list with groups on alphabetical order and child groups after the parent group.
1091 * This is a recursive function filling the $hierarchy parameter.
1100 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1101 $spaces = str_repeat($spacer, $level);
1104 $hierarchy[$group['id']] = $spaces . $group['title'];
1107 $hierarchy[$group['id']] = [
1108 'title' => $spaces . $group['title'],
1109 'description' => $group['description'],
1110 'visibility' => $group['visibility'],
1114 // For performance reasons we use a for loop rather than a foreach.
1115 // Metrics for performance in an installation with 2867 groups a foreach
1116 // caused the function getGroupsHierarchy with a foreach execution takes
1117 // around 2.2 seoonds (2,200 ms).
1118 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1119 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1120 for ($i = 0; $i < count($tree[$group['id']]); $i++
) {
1121 self
::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level +
1);
1127 * @param array $params
1129 * @return NULL|string
1131 public static function getGroupCount(&$params) {
1132 $whereClause = self
::whereClause($params, FALSE);
1133 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1135 if (!empty($params['created_by'])) {
1137 INNER JOIN civicrm_contact createdBy
1138 ON createdBy.id = groups.created_id";
1141 WHERE {$whereClause}";
1142 return CRM_Core_DAO
::singleValueQuery($query, $params);
1146 * Generate permissioned where clause for group search.
1147 * @param array $params
1148 * @param bool $sortBy
1149 * @param bool $excludeHidden
1153 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1155 $title = CRM_Utils_Array
::value('title', $params);
1157 $clauses[] = "groups.title LIKE %1";
1158 if (strpos($title, '%') !== FALSE) {
1159 $params[1] = [$title, 'String', FALSE];
1162 $params[1] = [$title, 'String', TRUE];
1166 $groupType = CRM_Utils_Array
::value('group_type', $params);
1168 $types = explode(',', $groupType);
1169 if (!empty($types)) {
1170 $clauses[] = 'groups.group_type LIKE %2';
1171 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1172 $params[2] = [$typeString, 'String', TRUE];
1176 $visibility = CRM_Utils_Array
::value('visibility', $params);
1178 $clauses[] = 'groups.visibility = %3';
1179 $params[3] = [$visibility, 'String'];
1182 $groupStatus = CRM_Utils_Array
::value('status', $params);
1184 switch ($groupStatus) {
1186 $clauses[] = 'groups.is_active = 1';
1187 $params[4] = [$groupStatus, 'Integer'];
1191 $clauses[] = 'groups.is_active = 0';
1192 $params[4] = [$groupStatus, 'Integer'];
1196 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1201 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1203 $clauses[] = 'groups.parents IS NULL';
1206 // only show child groups of a specific parent group
1207 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1209 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1210 $params[5] = [$parent_id, 'Integer'];
1213 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1214 $clauses[] = "createdBy.sort_name LIKE %6";
1215 if (strpos($createdBy, '%') !== FALSE) {
1216 $params[6] = [$createdBy, 'String', FALSE];
1219 $params[6] = [$createdBy, 'String', TRUE];
1223 if (empty($clauses)) {
1224 $clauses[] = 'groups.is_active = 1';
1227 if ($excludeHidden) {
1228 $clauses[] = 'groups.is_hidden = 0';
1231 $clauses[] = self
::getPermissionClause();
1233 return implode(' AND ', $clauses);
1237 * Define action links.
1240 * array of action links
1242 public static function actionLinks($params) {
1243 // If component_mode is set we change the "View" link to match the requested component type
1244 if (!isset($params['component_mode'])) {
1245 $params['component_mode'] = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
1247 $modeValue = CRM_Contact_Form_Search
::getModeValue($params['component_mode']);
1249 CRM_Core_Action
::VIEW
=> [
1250 'name' => $modeValue['selectorLabel'],
1251 'url' => 'civicrm/group/search',
1252 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%&component_mode=' . $params['component_mode'],
1253 'title' => ts('Group Contacts'),
1255 CRM_Core_Action
::UPDATE
=> [
1256 'name' => ts('Settings'),
1257 'url' => 'civicrm/group',
1258 'qs' => 'reset=1&action=update&id=%%id%%',
1259 'title' => ts('Edit Group'),
1261 CRM_Core_Action
::DISABLE
=> [
1262 'name' => ts('Disable'),
1263 'ref' => 'crm-enable-disable',
1264 'title' => ts('Disable Group'),
1266 CRM_Core_Action
::ENABLE
=> [
1267 'name' => ts('Enable'),
1268 'ref' => 'crm-enable-disable',
1269 'title' => ts('Enable Group'),
1271 CRM_Core_Action
::DELETE
=> [
1272 'name' => ts('Delete'),
1273 'url' => 'civicrm/group',
1274 'qs' => 'reset=1&action=delete&id=%%id%%',
1275 'title' => ts('Delete Group'),
1283 * @param $whereClause
1284 * @param array $whereParams
1288 public function pagerAtoZ($whereClause, $whereParams) {
1290 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1291 FROM civicrm_group groups
1293 ORDER BY LEFT(groups.title, 1)
1295 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1297 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1301 * Assign Test Value.
1303 * @param string $fieldName
1304 * @param array $fieldDef
1305 * @param int $counter
1307 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1308 if ($fieldName == 'children' ||
$fieldName == 'parents') {
1309 $this->{$fieldName} = "NULL";
1312 parent
::assignTestValues($fieldName, $fieldDef, $counter);
1317 * Get child group ids
1319 * @param array $regularGroupIDs
1324 public static function getChildGroupIds($regularGroupIDs) {
1325 $childGroupIDs = [];
1327 foreach ((array) $regularGroupIDs as $regularGroupID) {
1328 // temporary store the child group ID(s) of regular group identified by $id,
1329 // later merge with main child group array
1330 $tempChildGroupIDs = [];
1331 // check that the regular group has any child group, if not then continue
1332 if ($childrenFound = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1333 $tempChildGroupIDs[] = $childrenFound;
1338 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1339 // so we need to convert it into array of child group IDs first
1340 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1341 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1342 // recursively fetch the child group IDs
1343 while (count($tempChildGroupIDs)) {
1344 $tempChildGroupIDs = self
::getChildGroupIds($tempChildGroupIDs);
1345 if (count($tempChildGroupIDs)) {
1346 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1351 return $childGroupIDs;
1355 * Check parent groups and filter out the disabled ones.
1357 * @param array $parentArray
1358 * Array of group Ids.
1362 public static function filterActiveGroups($parentArray) {
1363 if (count($parentArray) > 1) {
1364 $result = civicrm_api3('Group', 'get', [
1365 'id' => ['IN' => $parentArray],
1366 'is_active' => TRUE,
1369 $activeParentGroupIDs = CRM_Utils_Array
::collect('id', $result['values']);
1370 foreach ($parentArray as $key => $groupID) {
1371 if (!array_key_exists($groupID, $activeParentGroupIDs)) {
1372 unset($parentArray[$key]);
1377 return reset($parentArray);