3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
33 class CRM_Contact_BAO_Group
extends CRM_Contact_DAO_Group
{
38 public function __construct() {
39 parent
::__construct();
43 * Retrieve DB object based on input parameters.
45 * It also stores all the retrieved values in the default array.
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 * @param array $defaults
50 * (reference ) an assoc array to hold the flattened values.
52 * @return CRM_Contact_BAO_Group
54 public static function retrieve(&$params, &$defaults) {
55 $group = new CRM_Contact_DAO_Group();
56 $group->copyValues($params);
57 if ($group->find(TRUE)) {
58 CRM_Core_DAO
::storeValues($group, $defaults);
66 * Delete the group and all the object that connect to this group.
68 * Incredibly destructive.
70 * @param int $id Group id.
72 public static function discard($id) {
73 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
75 $transaction = new CRM_Core_Transaction();
77 // added for CRM-1631 and CRM-1794
78 // delete all subscribed mails with the selected group id
79 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
80 $subscribe->group_id
= $id;
83 // delete all Subscription records with the selected group id
84 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
85 $subHistory->group_id
= $id;
86 $subHistory->delete();
88 // delete all crm_group_contact records with the selected group id
89 $groupContact = new CRM_Contact_DAO_GroupContact();
90 $groupContact->group_id
= $id;
91 $groupContact->delete();
93 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
94 $params = array(1 => array($id, 'Integer'));
95 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
96 CRM_Core_DAO
::executeQuery($query, $params);
98 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
99 CRM_Core_DAO
::executeQuery($query, $params);
101 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
103 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
104 CRM_Core_DAO
::executeQuery($query, $params);
106 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
107 CRM_Core_DAO
::executeQuery($query, $params);
109 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
110 CRM_Core_DAO
::executeQuery($query, $params);
112 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
116 // clear any descendant groups cache if exists
117 CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
120 // delete from group table
121 $group = new CRM_Contact_DAO_Group();
125 $transaction->commit();
127 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
129 // delete the recently created Group
130 $groupRecent = array(
134 CRM_Utils_Recent
::del($groupRecent);
138 * Returns an array of the contacts in the given group.
140 public static function getGroupContacts($id) {
141 $params = array(array('group', 'IN', array($id => 1), 0, 0));
142 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
147 * Get the count of a members in a group with the specific status.
151 * @param string $status
152 * status of members in group
153 * @param bool $countChildGroups
156 * count of members in the group with above status
158 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
159 $groupContact = new CRM_Contact_DAO_GroupContact();
160 $groupIds = array($id);
161 if ($countChildGroups) {
162 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
166 $contacts = self
::getGroupContacts($id);
168 foreach ($groupIds as $groupId) {
170 $groupContacts = self
::getGroupContacts($groupId);
171 foreach ($groupContacts as $gcontact) {
172 if ($groupId != $id) {
173 // Loop through main group's contacts
174 // and subtract from the count for each contact which
175 // matches one in the present group, if it is not the
177 foreach ($contacts as $contact) {
178 if ($contact['contact_id'] == $gcontact['contact_id']) {
184 $groupContact->group_id
= $groupId;
185 if (isset($status)) {
186 $groupContact->status
= $status;
188 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
189 $count +
= $groupContact->count();
195 * Get the list of member for a group id.
197 * @param int $groupID
198 * @param bool $useCache
201 * this array contains the list of members for this group id
203 public static function &getMember($groupID, $useCache = TRUE) {
204 $params = array(array('group', 'IN', array($groupID => 1), 0, 0));
205 $returnProperties = array('contact_id');
206 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, $useCache);
209 foreach ($contacts as $contact) {
210 $aMembers[$contact['contact_id']] = 1;
217 * Returns array of group object(s) matching a set of one or Group properties.
219 * @param array $params
220 * Limits the set of groups returned.
221 * @param array $returnProperties
222 * Which properties should be included in the returned group objects.
223 * (member_count should be last element.)
224 * @param string $sort
226 * @param int $rowCount
229 * Array of group objects.
232 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
233 * add in essential fields (e.g. id). This should follow a regular pattern like the others
235 public static function getGroups(
237 $returnProperties = NULL,
242 $dao = new CRM_Contact_DAO_Group();
243 if (!isset($params['is_active'])) {
247 foreach ($params as $k => $v) {
248 if ($k == 'name' ||
$k == 'title') {
249 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
251 elseif ($k == 'group_type') {
252 foreach ((array) $v as $type) {
253 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
256 elseif (is_array($v)) {
257 foreach ($v as &$num) {
260 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
268 if ($offset ||
$rowCount) {
269 $offset = ($offset > 0) ?
$offset : 0;
270 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
271 $dao->limit($offset, $rowCount);
275 $dao->orderBy($sort);
278 // return only specific fields if returnproperties are sent
279 if (!empty($returnProperties)) {
281 $dao->selectAdd(implode(',', $returnProperties));
285 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
288 while ($dao->fetch()) {
289 $group = new CRM_Contact_DAO_Group();
291 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
293 $groups[] = clone($dao);
299 * Make sure that the user has permission to access this group.
302 * The id of the object.
305 * the permission that the user has (or NULL)
307 public static function checkPermission($id) {
308 $allGroups = CRM_Core_PseudoConstant
::allGroup();
311 if (CRM_Core_Permission
::check('edit all contacts') ||
312 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
313 'civicrm_saved_search', $allGroups
316 $permissions[] = CRM_Core_Permission
::EDIT
;
319 if (CRM_Core_Permission
::check('view all contacts') ||
320 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
321 'civicrm_saved_search', $allGroups
324 $permissions[] = CRM_Core_Permission
::VIEW
;
327 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
328 // Note: using !empty() in if condition, restricts the scope of delete
329 // permission to groups/contacts that are editable/viewable.
330 // We can remove this !empty condition once we have ACL support for delete functionality.
331 $permissions[] = CRM_Core_Permission
::DELETE
;
338 * Create a new group.
340 * @param array $params
342 * @return CRM_Contact_BAO_Group|NULL
343 * The new group BAO (if created)
345 public static function &create(&$params) {
347 if (!empty($params['id'])) {
348 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
351 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
354 // form the name only if missing: CRM-627
355 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
356 if (!$nameParam && empty($params['id'])) {
357 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
360 // convert params if array type
361 if (isset($params['group_type'])) {
362 if (is_array($params['group_type'])) {
363 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
364 array_keys($params['group_type'])
365 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
369 $params['group_type'] = '';
372 $session = CRM_Core_Session
::singleton();
373 $cid = $session->get('userID');
374 // this action is add
375 if ($cid && empty($params['id'])) {
376 $params['created_id'] = $cid;
378 // this action is update
379 if ($cid && !empty($params['id'])) {
380 $params['modified_id'] = $cid;
383 $group = new CRM_Contact_BAO_Group();
384 $group->copyValues($params);
385 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
386 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
387 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
388 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
389 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
390 if (isset($group->parents
) && is_array($group->parents
)) {
391 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
392 array_keys($group->parents
)
393 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
395 if (empty($params['id']) &&
398 $group->name
.= "_tmp";
406 if (empty($params['id']) &&
409 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
412 $group->buildClause();
415 // add custom field values
416 if (!empty($params['custom'])) {
417 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
420 // make the group, child of domain/site group by default.
421 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
422 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
423 if (empty($params['parents']) &&
424 $domainGroupID != $group->id
&&
425 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
428 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
430 // if no parent present and the group doesn't already have any parents,
431 // make sure site group goes as parent
432 $params['parents'] = array($domainGroupID => 1);
434 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
435 $params['parents'] = array($params['parents'] => 1);
438 if (!empty($params['parents'])) {
439 foreach ($params['parents'] as $parentId => $dnc) {
440 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
441 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
446 // clear any descendant groups cache if exists
447 $finalGroups = CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
449 // this is always required, since we don't know when a
450 // parent group is removed
451 CRM_Contact_BAO_GroupNestingCache
::update();
453 // update group contact cache for all parent groups
454 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
455 foreach ($parentIds as $parentId) {
456 CRM_Contact_BAO_GroupContactCache
::add($parentId);
460 if (!empty($params['organization_id'])) {
463 $groupOrg['group_id'] = $group->id
;
464 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
467 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
469 if (!empty($params['id'])) {
470 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
473 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
476 $recentOther = array();
477 if (CRM_Core_Permission
::check('edit groups')) {
478 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
479 // currently same permission we are using for delete a group
480 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
483 // add the recently added group (unless hidden: CRM-6432)
484 if (!$group->is_hidden
) {
485 CRM_Utils_Recent
::add($group->title
,
486 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
498 * Given a saved search compute the clause and the tables
499 * and store it for future use
501 public function buildClause() {
502 $params = array(array('group', 'IN', array($this->id
), 0, 0));
504 if (!empty($params)) {
505 $tables = $whereTables = array();
506 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
507 if (!empty($tables)) {
508 $this->select_tables
= serialize($tables);
510 if (!empty($whereTables)) {
511 $this->where_tables
= serialize($whereTables);
517 * Defines a new smart group.
519 * @param array $params
520 * Associative array of parameters.
522 * @return CRM_Contact_BAO_Group|NULL
523 * The new group BAO (if created)
525 public static function createSmartGroup(&$params) {
526 if (!empty($params['formValues'])) {
528 unset($ssParams['id']);
529 if (isset($ssParams['saved_search_id'])) {
530 $ssParams['id'] = $ssParams['saved_search_id'];
533 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
535 $params['saved_search_id'] = $savedSearch->id
;
541 return self
::create($params);
545 * Update the is_active flag in the db.
548 * Id of the database record.
549 * @param bool $isActive
550 * Value we want to set the is_active field.
552 * @return CRM_Core_DAO|null
553 * DAO object on success, NULL otherwise
555 public static function setIsActive($id, $isActive) {
556 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
560 * Build the condition to retrieve groups.
562 * @param string $groupType
563 * Type of group(Access/Mailing) OR the key of the group.
564 * @param bool $excludeHidden exclude hidden groups.
568 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
570 if ($groupType == 'Mailing') {
571 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
573 elseif ($groupType == 'Access') {
574 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
576 elseif (!empty($groupType)) {
577 // ie we have been given the group key
578 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
582 if ($excludeHidden) {
583 $condition = "is_hidden = 0";
588 $condition .= " AND group_type LIKE '%$value%'";
591 $condition = "group_type LIKE '%$value%'";
599 * Get permission relevant clauses.
606 public static function getPermissionClause($force = FALSE) {
608 static $retrieved = FALSE;
609 if ((!$retrieved ||
$force) && !CRM_Core_Permission
::check('view all contacts') && !CRM_Core_Permission
::check('edit all contacts')) {
610 //get the allowed groups for the current user
611 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
612 if (!empty($groups)) {
613 $groupList = implode(', ', array_values($groups));
614 $clause = "groups.id IN ( $groupList ) ";
627 public function __toString() {
632 * This function create the hidden smart group when user perform
633 * contact search and want to send mailing to search contacts.
635 * @param array $params
636 * ( reference ) an assoc array of name/value pairs.
639 * ( smartGroupId, ssId ) smart group id and saved search id
641 public static function createHiddenSmartGroup($params) {
642 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
644 //add mapping record only for search builder saved search
646 if ($params['search_context'] == 'builder') {
647 //save the mapping for search builder
649 //save record in mapping table
651 $mappingParams = array('mapping_type' => 'Search Builder');
652 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams, $temp);
653 $mappingId = $mapping->id
;
656 //get the mapping id from saved search
657 $savedSearch = new CRM_Contact_BAO_SavedSearch();
658 $savedSearch->id
= $ssId;
659 $savedSearch->find(TRUE);
660 $mappingId = $savedSearch->mapping_id
;
663 //save mapping fields
664 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
667 //create/update saved search record.
668 $savedSearch = new CRM_Contact_BAO_SavedSearch();
669 $savedSearch->id
= $ssId;
670 $savedSearch->form_values
= serialize($params['form_values']);
671 $savedSearch->mapping_id
= $mappingId;
672 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
673 $savedSearch->save();
675 $ssId = $savedSearch->id
;
680 $smartGroupId = NULL;
681 if (!empty($params['saved_search_id'])) {
682 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
685 //create group only when new saved search.
686 $groupParams = array(
687 'title' => "Hidden Smart Group {$ssId}",
688 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
689 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
690 'group_type' => CRM_Utils_Array
::value('group_type', $params),
691 'visibility' => CRM_Utils_Array
::value('visibility', $params),
692 'saved_search_id' => $ssId,
695 $smartGroup = self
::create($groupParams);
696 $smartGroupId = $smartGroup->id
;
699 return array($smartGroupId, $ssId);
703 * wrapper for ajax group selector.
705 * @param array $params
706 * Associated array for params record id.
709 * associated array of group list
712 * @todo there seems little reason for the small number of functions that call this to pass in
713 * params that then need to be translated in this function since they are coding them when calling
715 static public function getGroupListSelector(&$params) {
717 $params['offset'] = ($params['page'] - 1) * $params['rp'];
718 $params['rowCount'] = $params['rp'];
719 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
722 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
724 //skip total if we are making call to show only children
725 if (empty($params['parent_id'])) {
727 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
729 // get all the groups
730 $allGroups = CRM_Core_PseudoConstant
::allGroup();
733 // format params and add links
734 $groupList = array();
735 if (!empty($groups)) {
736 foreach ($groups as $id => $value) {
737 $groupList[$id]['group_id'] = $value['id'];
738 $groupList[$id]['count'] = $value['count'];
739 $groupList[$id]['group_name'] = $value['title'];
741 // append parent names if in search mode
742 if (empty($params['parent_id']) && !empty($value['parents'])) {
743 $groupIds = explode(',', $value['parents']);
745 foreach ($groupIds as $gId) {
746 $title[] = $allGroups[$gId];
748 $groupList[$id]['group_name'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
749 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
751 $value['class'][] = 'crm-entity';
752 $groupList[$id]['class'] = $value['id'] . ',' . implode(' ', $value['class']);
754 $groupList[$id]['group_description'] = CRM_Utils_Array
::value('description', $value);
755 if (!empty($value['group_type'])) {
756 $groupList[$id]['group_type'] = $value['group_type'];
759 $groupList[$id]['group_type'] = '';
761 $groupList[$id]['visibility'] = $value['visibility'];
762 $groupList[$id]['links'] = $value['action'];
763 $groupList[$id]['org_info'] = CRM_Utils_Array
::value('org_info', $value);
764 $groupList[$id]['created_by'] = CRM_Utils_Array
::value('created_by', $value);
766 $groupList[$id]['is_parent'] = $value['is_parent'];
773 * This function to get list of groups.
775 * @param array $params
776 * Associated array for params.
780 public static function getGroupList(&$params) {
781 $config = CRM_Core_Config
::singleton();
783 $whereClause = self
::whereClause($params, FALSE);
785 //$this->pagerAToZ( $whereClause, $params );
787 if (!empty($params['rowCount']) &&
788 $params['rowCount'] > 0
790 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
793 $orderBy = ' ORDER BY groups.title asc';
794 if (!empty($params['sort'])) {
795 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
797 // CRM-16905 - Sort by count cannot be done with sql
798 if (strpos($params['sort'], 'count') === 0) {
799 $orderBy = $limit = '';
803 $select = $from = $where = "";
805 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
806 CRM_Core_Permission
::isMultisiteEnabled()
808 $select = ", contact.display_name as org_name, contact.id as org_id";
809 $from = " LEFT JOIN civicrm_group_organization gOrg
810 ON gOrg.group_id = groups.id
811 LEFT JOIN civicrm_contact contact
812 ON contact.id = gOrg.organization_id ";
814 //get the Organization ID
815 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
817 $where = " AND gOrg.organization_id = {$orgID}";
824 SELECT groups.*, createdBy.sort_name as created_by {$select}
825 FROM civicrm_group groups
826 LEFT JOIN civicrm_contact createdBy
827 ON createdBy.id = groups.created_id
829 WHERE $whereClause {$where}
834 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
836 //FIXME CRM-4418, now we are handling delete separately
837 //if we introduce 'delete for group' make sure to handle here.
838 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
839 if (CRM_Core_Permission
::check('edit groups')) {
840 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
841 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
845 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
847 $links = self
::actionLinks();
849 $allTypes = CRM_Core_OptionGroup
::values('group_type');
850 $values = $groupsToCount = array();
852 $visibility = CRM_Core_SelectValues
::ufVisibility();
854 while ($object->fetch()) {
855 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
856 //@todo CRM-12209 introduced an ACL check in the whereClause function
857 // it may be that this checking is now obsolete - or that what remains
858 // should be removed to the whereClause (which is also accessed by getCount)
862 $values[$object->id
] = array(
866 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
867 // Wrap with crm-editable. Not an ideal solution.
868 $values[$object->id
]['title'] = '<span class="crm-editable crmf-title">' . $values[$object->id
]['title'] . '</span>';
870 if ($object->saved_search_id
) {
871 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
872 // check if custom search, if so fix view link
873 $customSearchID = CRM_Core_DAO
::getFieldValue(
874 'CRM_Contact_DAO_SavedSearch',
875 $object->saved_search_id
,
879 if ($customSearchID) {
880 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
881 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
885 $action = array_sum(array_keys($newLinks));
888 if (array_key_exists('is_reserved', $object)) {
889 //if group is reserved and I don't have reserved permission, suppress delete/edit
890 if ($object->is_reserved
&& !$reservedPermission) {
891 $action -= CRM_Core_Action
::DELETE
;
892 $action -= CRM_Core_Action
::UPDATE
;
893 $action -= CRM_Core_Action
::DISABLE
;
897 if (array_key_exists('is_active', $object)) {
898 if ($object->is_active
) {
899 $action -= CRM_Core_Action
::ENABLE
;
902 $values[$object->id
]['class'][] = 'disabled';
903 $action -= CRM_Core_Action
::VIEW
;
904 $action -= CRM_Core_Action
::DISABLE
;
908 $action = $action & CRM_Core_Action
::mask($groupPermissions);
910 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
912 $groupsToCount[$object->saved_search_id ?
'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id
;
914 if (isset($values[$object->id
]['group_type'])) {
915 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
916 substr($values[$object->id
]['group_type'], 1, -1)
919 foreach ($groupTypes as $type) {
920 $types[] = CRM_Utils_Array
::value($type, $allTypes);
922 $values[$object->id
]['group_type'] = implode(', ', $types);
924 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
928 'ssid' => $object->saved_search_id
,
932 'group.selector.row',
937 // If group has children, add class for link to view children
938 $values[$object->id
]['is_parent'] = FALSE;
939 if (array_key_exists('children', $values[$object->id
])) {
940 $values[$object->id
]['class'][] = "crm-group-parent";
941 $values[$object->id
]['is_parent'] = TRUE;
944 // If group is a child, add child class
945 if (array_key_exists('parents', $values[$object->id
])) {
946 $values[$object->id
]['class'][] = "crm-group-child";
950 if ($object->org_id
) {
951 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
952 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
955 $values[$object->id
]['org_info'] = ''; // Empty cell
959 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
961 if ($object->created_id
) {
962 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
963 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
968 // Get group counts - executes one query for regular groups and another for smart groups
969 foreach ($groupsToCount as $table => $groups) {
970 $where = "g.group_id IN (" . implode(',', $groups) . ")";
971 if ($table == 'civicrm_group_contact') {
972 $where .= " AND g.status = 'Added'";
974 // Exclude deleted contacts
975 $where .= " and c.id = g.contact_id AND c.is_deleted = 0";
976 $dao = CRM_Core_DAO
::executeQuery("SELECT g.group_id, COUNT(g.id) as `count` FROM $table g, civicrm_contact c WHERE $where GROUP BY g.group_id");
977 while ($dao->fetch()) {
978 $values[$dao->group_id
]['count'] = $dao->count
;
982 // CRM-16905 - Sort by count cannot be done with sql
983 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
984 usort($values, function($a, $b) {
985 return $a['count'] - $b['count'];
987 if (strpos($params['sort'], 'desc')) {
988 $values = array_reverse($values, TRUE);
990 return array_slice($values, $params['offset'], $params['rowCount']);
997 * This function to get hierarchical list of groups (parent followed by children)
999 * @param array $groupIDs
1000 * Array of group ids.
1002 * @param NULL $parents
1003 * @param string $spacer
1004 * @param bool $titleOnly
1008 public static function getGroupsHierarchy(
1011 $spacer = '<span class="child-indent"></span>',
1014 if (empty($groupIDs)) {
1018 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1019 // <span class="child-icon"></span>
1020 // need to return id, title (w/ spacer), description, visibility
1022 // We need to build a list of tags ordered by hierarchy and sorted by
1023 // name. The hierarchy will be communicated by an accumulation of
1024 // separators in front of the name to give it a visual offset.
1025 // Instead of recursively making mysql queries, we'll make one big
1026 // query and build the hierarchy with the algorithm below.
1028 $args = array(1 => array($groupIdString, 'String'));
1030 SELECT id, title, description, visibility, parents
1032 WHERE id IN $groupIdString
1035 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1036 $parentArray = explode(',', $parents);
1037 $parent = $parentArray[0];
1038 $args[2] = array($parent, 'Integer');
1039 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1041 $query .= " ORDER BY title";
1042 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1044 // Sort the groups into the correct storage by the parent
1045 // $roots represent the current leaf nodes that need to be checked for
1046 // children. $rows represent the unplaced nodes
1047 $roots = $rows = $allGroups = array();
1048 while ($dao->fetch()) {
1049 $allGroups[$dao->id
] = array(
1050 'title' => $dao->title
,
1051 'visibility' => $dao->visibility
,
1052 'description' => $dao->description
,
1055 if ($dao->parents
== $parents) {
1059 'title' => $dao->title
,
1063 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1064 $parentArray = explode(',', $dao->parents
);
1065 $parent = $parentArray[0];
1069 'title' => $dao->title
,
1070 'parents' => $parent,
1075 // While we have nodes left to build, shift the first (alphabetically)
1076 // node of the list, place it in our groups list and loop through the
1077 // list of unplaced nodes to find its children. We make a copy to
1078 // iterate through because we must modify the unplaced nodes list
1080 while (count($roots)) {
1081 $new_roots = array();
1082 $current_rows = $rows;
1083 $root = array_shift($roots);
1084 $groups[$root['id']] = array($root['prefix'], $root['title']);
1086 // As you find the children, append them to the end of the new set
1087 // of roots (maintain alphabetical ordering). Also remove the node
1088 // from the set of unplaced nodes.
1089 if (is_array($current_rows)) {
1090 foreach ($current_rows as $key => $row) {
1091 if ($row['parents'] == $root['id']) {
1092 $new_roots[] = array(
1094 'prefix' => $groups[$root['id']][0] . $spacer,
1095 'title' => $row['title'],
1102 //As a group, insert the new roots into the beginning of the roots
1103 //list. This maintains the hierarchical ordering of the tags.
1104 $roots = array_merge($new_roots, $roots);
1107 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1108 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1109 foreach ($rows as $value) {
1110 $groups[$value['id']] = array($value['prefix'], $value['title']);
1112 // Prefix titles with the calcuated spacing to give the visual
1113 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1114 $groupsReturn = array();
1115 foreach ($groups as $key => $value) {
1117 $groupsReturn[$key] = $value[0] . $value[1];
1120 $groupsReturn[$key] = array(
1121 'title' => $value[0] . $value[1],
1122 'description' => $allGroups[$key]['description'],
1123 'visibility' => $allGroups[$key]['visibility'],
1128 return $groupsReturn;
1132 * @param array $params
1134 * @return NULL|string
1136 public static function getGroupCount(&$params) {
1137 $whereClause = self
::whereClause($params, FALSE);
1138 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1140 if (!empty($params['created_by'])) {
1142 INNER JOIN civicrm_contact createdBy
1143 ON createdBy.id = groups.created_id";
1146 WHERE {$whereClause}";
1147 return CRM_Core_DAO
::singleValueQuery($query, $params);
1151 * Generate permissioned where clause for group search.
1152 * @param array $params
1153 * @param bool $sortBy
1154 * @param bool $excludeHidden
1158 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1160 $title = CRM_Utils_Array
::value('title', $params);
1162 $clauses[] = "groups.title LIKE %1";
1163 if (strpos($title, '%') !== FALSE) {
1164 $params[1] = array($title, 'String', FALSE);
1167 $params[1] = array($title, 'String', TRUE);
1171 $groupType = CRM_Utils_Array
::value('group_type', $params);
1173 $types = explode(',', $groupType);
1174 if (!empty($types)) {
1175 $clauses[] = 'groups.group_type LIKE %2';
1176 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1177 $params[2] = array($typeString, 'String', TRUE);
1181 $visibility = CRM_Utils_Array
::value('visibility', $params);
1183 $clauses[] = 'groups.visibility = %3';
1184 $params[3] = array($visibility, 'String');
1187 $groupStatus = CRM_Utils_Array
::value('status', $params);
1189 switch ($groupStatus) {
1191 $clauses[] = 'groups.is_active = 1';
1192 $params[4] = array($groupStatus, 'Integer');
1196 $clauses[] = 'groups.is_active = 0';
1197 $params[4] = array($groupStatus, 'Integer');
1201 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1206 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1208 $clauses[] = 'groups.parents IS NULL';
1211 // only show child groups of a specific parent group
1212 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1214 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1215 $params[5] = array($parent_id, 'Integer');
1218 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1219 $clauses[] = "createdBy.sort_name LIKE %6";
1220 if (strpos($createdBy, '%') !== FALSE) {
1221 $params[6] = array($createdBy, 'String', FALSE);
1224 $params[6] = array($createdBy, 'String', TRUE);
1228 if (empty($clauses)) {
1229 $clauses[] = 'groups.is_active = 1';
1232 if ($excludeHidden) {
1233 $clauses[] = 'groups.is_hidden = 0';
1236 $clauses[] = self
::getPermissionClause();
1238 return implode(' AND ', $clauses);
1242 * Define action links.
1245 * array of action links
1247 public static function actionLinks() {
1249 CRM_Core_Action
::VIEW
=> array(
1250 'name' => ts('Contacts'),
1251 'url' => 'civicrm/group/search',
1252 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1253 'title' => ts('Group Contacts'),
1255 CRM_Core_Action
::UPDATE
=> array(
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
=> array(
1262 'name' => ts('Disable'),
1263 'ref' => 'crm-enable-disable',
1264 'title' => ts('Disable Group'),
1266 CRM_Core_Action
::ENABLE
=> array(
1267 'name' => ts('Enable'),
1268 'ref' => 'crm-enable-disable',
1269 'title' => ts('Enable Group'),
1271 CRM_Core_Action
::DELETE
=> array(
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);