3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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);
64 * Delete the group and all the object that connect to this group.
66 * Incredibly destructive.
68 * @param int $id Group id.
70 public static function discard($id) {
71 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
73 $transaction = new CRM_Core_Transaction();
75 // added for CRM-1631 and CRM-1794
76 // delete all subscribed mails with the selected group id
77 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
78 $subscribe->group_id
= $id;
81 // delete all Subscription records with the selected group id
82 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
83 $subHistory->group_id
= $id;
84 $subHistory->delete();
86 // delete all crm_group_contact records with the selected group id
87 $groupContact = new CRM_Contact_DAO_GroupContact();
88 $groupContact->group_id
= $id;
89 $groupContact->delete();
91 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
92 $params = array(1 => array($id, 'Integer'));
93 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
94 CRM_Core_DAO
::executeQuery($query, $params);
96 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
97 CRM_Core_DAO
::executeQuery($query, $params);
99 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
101 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
102 CRM_Core_DAO
::executeQuery($query, $params);
104 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
105 CRM_Core_DAO
::executeQuery($query, $params);
107 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
108 CRM_Core_DAO
::executeQuery($query, $params);
110 if (Civi
::settings()->get('is_enabled')) {
111 // clear any descendant groups cache if exists
112 CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
115 // delete from group table
116 $group = new CRM_Contact_DAO_Group();
120 $transaction->commit();
122 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
124 // delete the recently created Group
125 $groupRecent = array(
129 CRM_Utils_Recent
::del($groupRecent);
133 * Returns an array of the contacts in the given group.
137 public static function getGroupContacts($id) {
138 $params = array(array('group', 'IN', array($id => 1), 0, 0));
139 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
144 * Get the count of a members in a group with the specific status.
148 * @param string $status
149 * status of members in group
150 * @param bool $countChildGroups
153 * count of members in the group with above status
155 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
156 $groupContact = new CRM_Contact_DAO_GroupContact();
157 $groupIds = array($id);
158 if ($countChildGroups) {
159 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
163 $contacts = self
::getGroupContacts($id);
165 foreach ($groupIds as $groupId) {
167 $groupContacts = self
::getGroupContacts($groupId);
168 foreach ($groupContacts as $gcontact) {
169 if ($groupId != $id) {
170 // Loop through main group's contacts
171 // and subtract from the count for each contact which
172 // matches one in the present group, if it is not the
174 foreach ($contacts as $contact) {
175 if ($contact['contact_id'] == $gcontact['contact_id']) {
181 $groupContact->group_id
= $groupId;
182 if (isset($status)) {
183 $groupContact->status
= $status;
185 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
186 $count +
= $groupContact->count();
192 * Get the list of member for a group id.
194 * @param int $groupID
195 * @param bool $useCache
198 * this array contains the list of members for this group id
200 public static function &getMember($groupID, $useCache = TRUE) {
201 $params = array(array('group', '=', $groupID, 0, 0));
202 $returnProperties = array('contact_id');
203 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, $useCache);
206 foreach ($contacts as $contact) {
207 $aMembers[$contact['contact_id']] = 1;
214 * Returns array of group object(s) matching a set of one or Group properties.
216 * @param array $params
217 * Limits the set of groups returned.
218 * @param array $returnProperties
219 * Which properties should be included in the returned group objects.
220 * (member_count should be last element.)
221 * @param string $sort
223 * @param int $rowCount
226 * Array of group objects.
229 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
230 * add in essential fields (e.g. id). This should follow a regular pattern like the others
232 public static function getGroups(
234 $returnProperties = NULL,
239 $dao = new CRM_Contact_DAO_Group();
240 if (!isset($params['is_active'])) {
244 foreach ($params as $k => $v) {
245 if ($k == 'name' ||
$k == 'title') {
246 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
248 elseif ($k == 'group_type') {
249 foreach ((array) $v as $type) {
250 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
253 elseif (is_array($v)) {
254 foreach ($v as &$num) {
257 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
265 if ($offset ||
$rowCount) {
266 $offset = ($offset > 0) ?
$offset : 0;
267 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
268 $dao->limit($offset, $rowCount);
272 $dao->orderBy($sort);
275 // return only specific fields if returnproperties are sent
276 if (!empty($returnProperties)) {
278 $dao->selectAdd(implode(',', $returnProperties));
282 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
285 while ($dao->fetch()) {
286 $group = new CRM_Contact_DAO_Group();
288 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
290 $groups[] = clone($dao);
296 * Make sure that the user has permission to access this group.
299 * The id of the object.
300 * @param bool $excludeHidden
301 * Should hidden groups be excluded.
302 * Logically this is the wrong place to filter hidden groups out as that is
303 * not a permission issue. However, as other functions may rely on that defaulting to
304 * FALSE for now & only the api call is calling with true.
307 * The permission that the user has (or NULL)
309 public static function checkPermission($id, $excludeHidden = FALSE) {
310 $allGroups = CRM_Core_PseudoConstant
::allGroup(NULL, $excludeHidden);
313 if (CRM_Core_Permission
::check('edit all contacts') ||
314 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
315 'civicrm_saved_search', $allGroups
318 $permissions[] = CRM_Core_Permission
::EDIT
;
321 if (CRM_Core_Permission
::check('view all contacts') ||
322 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
323 'civicrm_saved_search', $allGroups
326 $permissions[] = CRM_Core_Permission
::VIEW
;
329 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
330 // Note: using !empty() in if condition, restricts the scope of delete
331 // permission to groups/contacts that are editable/viewable.
332 // We can remove this !empty condition once we have ACL support for delete functionality.
333 $permissions[] = CRM_Core_Permission
::DELETE
;
340 * Create a new group.
342 * @param array $params
344 * @return CRM_Contact_BAO_Group|NULL
345 * The new group BAO (if created)
347 public static function &create(&$params) {
349 if (!empty($params['id'])) {
350 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
353 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
356 // form the name only if missing: CRM-627
357 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
358 if (!$nameParam && empty($params['id'])) {
359 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
362 // convert params if array type
363 if (isset($params['group_type'])) {
364 if (is_array($params['group_type'])) {
365 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
366 array_keys($params['group_type'])
367 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
371 $params['group_type'] = NULL;
374 $session = CRM_Core_Session
::singleton();
375 $cid = $session->get('userID');
376 // this action is add
377 if ($cid && empty($params['id'])) {
378 $params['created_id'] = $cid;
380 // this action is update
381 if ($cid && !empty($params['id'])) {
382 $params['modified_id'] = $cid;
385 $group = new CRM_Contact_BAO_Group();
386 $group->copyValues($params);
387 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
388 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
389 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
390 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
391 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
392 if (isset($group->parents
) && is_array($group->parents
)) {
393 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
394 array_keys($group->parents
)
395 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
397 if (empty($params['id']) &&
400 $group->name
.= "_tmp";
408 if (empty($params['id']) &&
411 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
414 $group->buildClause();
417 // add custom field values
418 if (!empty($params['custom'])) {
419 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
422 // make the group, child of domain/site group by default.
423 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
424 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
425 if (empty($params['parents']) &&
426 $domainGroupID != $group->id
&&
427 Civi
::settings()->get('is_enabled') &&
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 foreach ($groups as $id => $value) {
737 $group['group_id'] = $value['id'];
738 $group['count'] = $value['count'];
739 $group['title'] = $value['title'];
741 // append parent names if in search mode
742 if (empty($params['parent_id']) && !empty($value['parents'])) {
743 $group['parent_id'] = $value['parents'];
744 $groupIds = explode(',', $value['parents']);
746 foreach ($groupIds as $gId) {
747 $title[] = $allGroups[$gId];
749 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
750 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
752 $group['DT_RowId'] = 'row_' . $value['id'];
753 if (!$params['parentsOnly']) {
754 foreach ($value['class'] as $id => $class) {
755 if ($class == 'crm-group-parent') {
756 unset($value['class'][$id]);
760 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
761 $group['DT_RowAttr'] = array();
762 $group['DT_RowAttr']['data-id'] = $value['id'];
763 $group['DT_RowAttr']['data-entity'] = 'group';
765 $group['description'] = CRM_Utils_Array
::value('description', $value);
767 if (!empty($value['group_type'])) {
768 $group['group_type'] = $value['group_type'];
771 $group['group_type'] = '';
774 $group['visibility'] = $value['visibility'];
775 $group['links'] = $value['action'];
776 $group['org_info'] = CRM_Utils_Array
::value('org_info', $value);
777 $group['created_by'] = CRM_Utils_Array
::value('created_by', $value);
779 $group['is_parent'] = $value['is_parent'];
781 array_push($groupList, $group);
785 $groupsDT['data'] = $groupList;
786 $groupsDT['recordsTotal'] = $params['total'];
787 $groupsDT['recordsFiltered'] = $params['total'];
793 * This function to get list of groups.
795 * @param array $params
796 * Associated array for params.
800 public static function getGroupList(&$params) {
801 $config = CRM_Core_Config
::singleton();
803 $whereClause = self
::whereClause($params, FALSE);
805 //$this->pagerAToZ( $whereClause, $params );
807 if (!empty($params['rowCount']) &&
808 $params['rowCount'] > 0
810 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
813 $orderBy = ' ORDER BY groups.title asc';
814 if (!empty($params['sort'])) {
815 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
817 // CRM-16905 - Sort by count cannot be done with sql
818 if (strpos($params['sort'], 'count') === 0) {
819 $orderBy = $limit = '';
823 $select = $from = $where = "";
825 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
826 CRM_Core_Permission
::isMultisiteEnabled()
828 $select = ", contact.display_name as org_name, contact.id as org_id";
829 $from = " LEFT JOIN civicrm_group_organization gOrg
830 ON gOrg.group_id = groups.id
831 LEFT JOIN civicrm_contact contact
832 ON contact.id = gOrg.organization_id ";
834 //get the Organization ID
835 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
837 $where = " AND gOrg.organization_id = {$orgID}";
844 SELECT groups.*, createdBy.sort_name as created_by {$select}
845 FROM civicrm_group groups
846 LEFT JOIN civicrm_contact createdBy
847 ON createdBy.id = groups.created_id
849 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 = array(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();
869 $allTypes = CRM_Core_OptionGroup
::values('group_type');
870 $values = $groupsToCount = array();
872 $visibility = CRM_Core_SelectValues
::ufVisibility();
874 while ($object->fetch()) {
875 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
876 //@todo CRM-12209 introduced an ACL check in the whereClause function
877 // it may be that this checking is now obsolete - or that what remains
878 // should be removed to the whereClause (which is also accessed by getCount)
882 $values[$object->id
] = array(
886 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
888 if ($object->saved_search_id
) {
889 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
890 // check if custom search, if so fix view link
891 $customSearchID = CRM_Core_DAO
::getFieldValue(
892 'CRM_Contact_DAO_SavedSearch',
893 $object->saved_search_id
,
897 if ($customSearchID) {
898 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
899 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
903 $action = array_sum(array_keys($newLinks));
906 if (array_key_exists('is_reserved', $object)) {
907 //if group is reserved and I don't have reserved permission, suppress delete/edit
908 if ($object->is_reserved
&& !$reservedPermission) {
909 $action -= CRM_Core_Action
::DELETE
;
910 $action -= CRM_Core_Action
::UPDATE
;
911 $action -= CRM_Core_Action
::DISABLE
;
915 if (array_key_exists('is_active', $object)) {
916 if ($object->is_active
) {
917 $action -= CRM_Core_Action
::ENABLE
;
920 $values[$object->id
]['class'][] = 'disabled';
921 $action -= CRM_Core_Action
::VIEW
;
922 $action -= CRM_Core_Action
::DISABLE
;
926 $action = $action & CRM_Core_Action
::mask($groupPermissions);
928 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
930 $groupsToCount[$object->saved_search_id ?
'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id
;
932 if (isset($values[$object->id
]['group_type'])) {
933 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
934 substr($values[$object->id
]['group_type'], 1, -1)
937 foreach ($groupTypes as $type) {
938 $types[] = CRM_Utils_Array
::value($type, $allTypes);
940 $values[$object->id
]['group_type'] = implode(', ', $types);
942 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
946 'ssid' => $object->saved_search_id
,
950 'group.selector.row',
955 // If group has children, add class for link to view children
956 $values[$object->id
]['is_parent'] = FALSE;
957 if (array_key_exists('children', $values[$object->id
])) {
958 $values[$object->id
]['class'][] = "crm-group-parent";
959 $values[$object->id
]['is_parent'] = TRUE;
962 // If group is a child, add child class
963 if (array_key_exists('parents', $values[$object->id
])) {
964 $values[$object->id
]['class'][] = "crm-group-child";
968 if ($object->org_id
) {
969 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
970 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
973 $values[$object->id
]['org_info'] = ''; // Empty cell
977 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
979 if ($object->created_id
) {
980 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
981 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
986 // Get group counts - executes one query for regular groups and another for smart groups
987 foreach ($groupsToCount as $table => $groups) {
988 $where = "g.group_id IN (" . implode(',', $groups) . ")";
989 if ($table == 'civicrm_group_contact') {
990 $where .= " AND g.status = 'Added'";
992 // Exclude deleted contacts
993 $where .= " and c.id = g.contact_id AND c.is_deleted = 0";
994 $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");
995 while ($dao->fetch()) {
996 $values[$dao->group_id
]['count'] = $dao->count
;
1000 // CRM-16905 - Sort by count cannot be done with sql
1001 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1002 usort($values, function($a, $b) {
1003 return $a['count'] - $b['count'];
1005 if (strpos($params['sort'], 'desc')) {
1006 $values = array_reverse($values, TRUE);
1008 return array_slice($values, $params['offset'], $params['rowCount']);
1015 * This function to get hierarchical list of groups (parent followed by children)
1017 * @param array $groupIDs
1018 * Array of group ids.
1020 * @param NULL $parents
1021 * @param string $spacer
1022 * @param bool $titleOnly
1026 public static function getGroupsHierarchy(
1029 $spacer = '<span class="child-indent"></span>',
1032 if (empty($groupIDs)) {
1036 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1037 // <span class="child-icon"></span>
1038 // need to return id, title (w/ spacer), description, visibility
1040 // We need to build a list of tags ordered by hierarchy and sorted by
1041 // name. The hierarchy will be communicated by an accumulation of
1042 // separators in front of the name to give it a visual offset.
1043 // Instead of recursively making mysql queries, we'll make one big
1044 // query and build the hierarchy with the algorithm below.
1046 $args = array(1 => array($groupIdString, 'String'));
1048 SELECT id, title, description, visibility, parents
1050 WHERE id IN $groupIdString
1053 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1054 $parentArray = explode(',', $parents);
1055 $parent = $parentArray[0];
1056 $args[2] = array($parent, 'Integer');
1057 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1059 $query .= " ORDER BY title";
1060 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1062 // Sort the groups into the correct storage by the parent
1063 // $roots represent the current leaf nodes that need to be checked for
1064 // children. $rows represent the unplaced nodes
1065 $roots = $rows = $allGroups = array();
1066 while ($dao->fetch()) {
1067 $allGroups[$dao->id
] = array(
1068 'title' => $dao->title
,
1069 'visibility' => $dao->visibility
,
1070 'description' => $dao->description
,
1073 if ($dao->parents
== $parents) {
1077 'title' => $dao->title
,
1081 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1082 $parentArray = explode(',', $dao->parents
);
1083 $parent = $parentArray[0];
1087 'title' => $dao->title
,
1088 'parents' => $parent,
1093 // While we have nodes left to build, shift the first (alphabetically)
1094 // node of the list, place it in our groups list and loop through the
1095 // list of unplaced nodes to find its children. We make a copy to
1096 // iterate through because we must modify the unplaced nodes list
1098 while (count($roots)) {
1099 $new_roots = array();
1100 $current_rows = $rows;
1101 $root = array_shift($roots);
1102 $groups[$root['id']] = array($root['prefix'], $root['title']);
1104 // As you find the children, append them to the end of the new set
1105 // of roots (maintain alphabetical ordering). Also remove the node
1106 // from the set of unplaced nodes.
1107 if (is_array($current_rows)) {
1108 foreach ($current_rows as $key => $row) {
1109 if ($row['parents'] == $root['id']) {
1110 $new_roots[] = array(
1112 'prefix' => $groups[$root['id']][0] . $spacer,
1113 'title' => $row['title'],
1120 //As a group, insert the new roots into the beginning of the roots
1121 //list. This maintains the hierarchical ordering of the tags.
1122 $roots = array_merge($new_roots, $roots);
1125 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1126 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1127 foreach ($rows as $value) {
1128 $groups[$value['id']] = array($value['prefix'], $value['title']);
1130 // Prefix titles with the calcuated spacing to give the visual
1131 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1132 $groupsReturn = array();
1133 foreach ($groups as $key => $value) {
1135 $groupsReturn[$key] = $value[0] . $value[1];
1138 $groupsReturn[$key] = array(
1139 'title' => $value[0] . $value[1],
1140 'description' => $allGroups[$key]['description'],
1141 'visibility' => $allGroups[$key]['visibility'],
1146 return $groupsReturn;
1150 * @param array $params
1152 * @return NULL|string
1154 public static function getGroupCount(&$params) {
1155 $whereClause = self
::whereClause($params, FALSE);
1156 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1158 if (!empty($params['created_by'])) {
1160 INNER JOIN civicrm_contact createdBy
1161 ON createdBy.id = groups.created_id";
1164 WHERE {$whereClause}";
1165 return CRM_Core_DAO
::singleValueQuery($query, $params);
1169 * Generate permissioned where clause for group search.
1170 * @param array $params
1171 * @param bool $sortBy
1172 * @param bool $excludeHidden
1176 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1178 $title = CRM_Utils_Array
::value('title', $params);
1180 $clauses[] = "groups.title LIKE %1";
1181 if (strpos($title, '%') !== FALSE) {
1182 $params[1] = array($title, 'String', FALSE);
1185 $params[1] = array($title, 'String', TRUE);
1189 $groupType = CRM_Utils_Array
::value('group_type', $params);
1191 $types = explode(',', $groupType);
1192 if (!empty($types)) {
1193 $clauses[] = 'groups.group_type LIKE %2';
1194 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1195 $params[2] = array($typeString, 'String', TRUE);
1199 $visibility = CRM_Utils_Array
::value('visibility', $params);
1201 $clauses[] = 'groups.visibility = %3';
1202 $params[3] = array($visibility, 'String');
1205 $groupStatus = CRM_Utils_Array
::value('status', $params);
1207 switch ($groupStatus) {
1209 $clauses[] = 'groups.is_active = 1';
1210 $params[4] = array($groupStatus, 'Integer');
1214 $clauses[] = 'groups.is_active = 0';
1215 $params[4] = array($groupStatus, 'Integer');
1219 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1224 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1226 $clauses[] = 'groups.parents IS NULL';
1229 // only show child groups of a specific parent group
1230 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1232 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1233 $params[5] = array($parent_id, 'Integer');
1236 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1237 $clauses[] = "createdBy.sort_name LIKE %6";
1238 if (strpos($createdBy, '%') !== FALSE) {
1239 $params[6] = array($createdBy, 'String', FALSE);
1242 $params[6] = array($createdBy, 'String', TRUE);
1246 if (empty($clauses)) {
1247 $clauses[] = 'groups.is_active = 1';
1250 if ($excludeHidden) {
1251 $clauses[] = 'groups.is_hidden = 0';
1254 $clauses[] = self
::getPermissionClause();
1256 return implode(' AND ', $clauses);
1260 * Define action links.
1263 * array of action links
1265 public static function actionLinks() {
1267 CRM_Core_Action
::VIEW
=> array(
1268 'name' => ts('Contacts'),
1269 'url' => 'civicrm/group/search',
1270 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1271 'title' => ts('Group Contacts'),
1273 CRM_Core_Action
::UPDATE
=> array(
1274 'name' => ts('Settings'),
1275 'url' => 'civicrm/group',
1276 'qs' => 'reset=1&action=update&id=%%id%%',
1277 'title' => ts('Edit Group'),
1279 CRM_Core_Action
::DISABLE
=> array(
1280 'name' => ts('Disable'),
1281 'ref' => 'crm-enable-disable',
1282 'title' => ts('Disable Group'),
1284 CRM_Core_Action
::ENABLE
=> array(
1285 'name' => ts('Enable'),
1286 'ref' => 'crm-enable-disable',
1287 'title' => ts('Enable Group'),
1289 CRM_Core_Action
::DELETE
=> array(
1290 'name' => ts('Delete'),
1291 'url' => 'civicrm/group',
1292 'qs' => 'reset=1&action=delete&id=%%id%%',
1293 'title' => ts('Delete Group'),
1301 * @param $whereClause
1302 * @param array $whereParams
1306 public function pagerAtoZ($whereClause, $whereParams) {
1308 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1309 FROM civicrm_group groups
1311 ORDER BY LEFT(groups.title, 1)
1313 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1315 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);