3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 class CRM_Contact_BAO_Group
extends CRM_Contact_DAO_Group
{
40 public function __construct() {
41 parent
::__construct();
45 * Takes a bunch of params that are needed to match certain criteria and
46 * retrieves the relevant objects. Typically the valid params are only
47 * group_id. We'll tweak this function to be more full featured over a period
48 * of time. This is the inverse function of create. It also stores all the retrieved
49 * values in the default array
51 * @param array $params
52 * (reference ) an assoc array of name/value pairs.
53 * @param array $defaults
54 * (reference ) an assoc array to hold the flattened values.
56 * @return CRM_Contact_BAO_Group
58 public static function retrieve(&$params, &$defaults) {
59 $group = new CRM_Contact_DAO_Group();
60 $group->copyValues($params);
61 if ($group->find(TRUE)) {
62 CRM_Core_DAO
::storeValues($group, $defaults);
70 * Delete the group and all the object that connect to
71 * this group. Incredibly destructive
76 public static function discard($id) {
77 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
79 $transaction = new CRM_Core_Transaction();
81 // added for CRM-1631 and CRM-1794
82 // delete all subscribed mails with the selected group id
83 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
84 $subscribe->group_id
= $id;
87 // delete all Subscription records with the selected group id
88 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
89 $subHistory->group_id
= $id;
90 $subHistory->delete();
92 // delete all crm_group_contact records with the selected group id
93 $groupContact = new CRM_Contact_DAO_GroupContact();
94 $groupContact->group_id
= $id;
95 $groupContact->delete();
97 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
98 $params = array(1 => array($id, 'Integer'));
99 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
100 CRM_Core_DAO
::executeQuery($query, $params);
102 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
103 CRM_Core_DAO
::executeQuery($query, $params);
105 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
107 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
108 CRM_Core_DAO
::executeQuery($query, $params);
110 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
111 CRM_Core_DAO
::executeQuery($query, $params);
113 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
114 CRM_Core_DAO
::executeQuery($query, $params);
116 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
120 // clear any descendant groups cache if exists
121 CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
124 // delete from group table
125 $group = new CRM_Contact_DAO_Group();
129 $transaction->commit();
131 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
133 // delete the recently created Group
134 $groupRecent = array(
138 CRM_Utils_Recent
::del($groupRecent);
142 * Returns an array of the contacts in the given group.
144 public static function getGroupContacts($id) {
145 $params = array(array('group', 'IN', array($id => 1), 0, 0));
146 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
151 * Get the count of a members in a group with the specific status
155 * @param string $status
156 * status of members in group
157 * @param bool $countChildGroups
160 * count of members in the group with above status
162 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
163 $groupContact = new CRM_Contact_DAO_GroupContact();
164 $groupIds = array($id);
165 if ($countChildGroups) {
166 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
170 $contacts = self
::getGroupContacts($id);
172 foreach ($groupIds as $groupId) {
174 $groupContacts = self
::getGroupContacts($groupId);
175 foreach ($groupContacts as $gcontact) {
176 if ($groupId != $id) {
177 // Loop through main group's contacts
178 // and subtract from the count for each contact which
179 // matches one in the present group, if it is not the
181 foreach ($contacts as $contact) {
182 if ($contact['contact_id'] == $gcontact['contact_id']) {
188 $groupContact->group_id
= $groupId;
189 if (isset($status)) {
190 $groupContact->status
= $status;
192 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
193 $count +
= $groupContact->count();
199 * Get the list of member for a group id
201 * @param int $groupID
202 * @param bool $useCache
205 * this array contains the list of members for this group id
207 public static function &getMember($groupID, $useCache = TRUE) {
208 $params = array(array('group', 'IN', array($groupID => 1), 0, 0));
209 $returnProperties = array('contact_id');
210 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, $useCache);
213 foreach ($contacts as $contact) {
214 $aMembers[$contact['contact_id']] = 1;
221 * Returns array of group object(s) matching a set of one or Group properties.
223 * @param array $params
224 * Limits the set of groups returned.
225 * @param array $returnProperties
226 * Which properties should be included in the returned group objects.
227 * (member_count should be last element.)
228 * @param string $sort
230 * @param int $rowCount
233 * Array of group objects.
236 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
237 * add in essential fields (e.g. id). This should follow a regular pattern like the others
239 public static function getGroups(
241 $returnProperties = NULL,
246 $dao = new CRM_Contact_DAO_Group();
247 if (!isset($params['is_active'])) {
251 foreach ($params as $k => $v) {
252 if ($k == 'name' ||
$k == 'title') {
253 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
255 elseif ($k == 'group_type') {
256 foreach ((array) $v as $type) {
257 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
260 elseif (is_array($v)) {
261 foreach ($v as &$num) {
264 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
272 if ($offset ||
$rowCount) {
273 $offset = ($offset > 0) ?
$offset : 0;
274 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
275 $dao->limit($offset, $rowCount);
279 $dao->orderBy($sort);
282 // return only specific fields if returnproperties are sent
283 if (!empty($returnProperties)) {
285 $dao->selectAdd(implode(',', $returnProperties));
289 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
292 while ($dao->fetch()) {
293 $group = new CRM_Contact_DAO_Group();
295 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
297 $groups[] = clone($dao);
303 * Make sure that the user has permission to access this group
306 * The id of the object.
309 * the permission that the user has (or NULL)
311 public static function checkPermission($id) {
312 $allGroups = CRM_Core_PseudoConstant
::allGroup();
315 if (CRM_Core_Permission
::check('edit all contacts') ||
316 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
317 'civicrm_saved_search', $allGroups
320 $permissions[] = CRM_Core_Permission
::EDIT
;
323 if (CRM_Core_Permission
::check('view all contacts') ||
324 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
325 'civicrm_saved_search', $allGroups
328 $permissions[] = CRM_Core_Permission
::VIEW
;
331 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
332 // Note: using !empty() in if condition, restricts the scope of delete
333 // permission to groups/contacts that are editable/viewable.
334 // We can remove this !empty condition once we have ACL support for delete functionality.
335 $permissions[] = CRM_Core_Permission
::DELETE
;
344 * @param array $params
346 * @return CRM_Contact_BAO_Group|NULL
347 * The new group BAO (if created)
349 public static function &create(&$params) {
351 if (!empty($params['id'])) {
352 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
355 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
358 // form the name only if missing: CRM-627
359 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
360 if (!$nameParam && empty($params['id'])) {
361 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
364 // convert params if array type
365 if (isset($params['group_type'])) {
366 if (is_array($params['group_type'])) {
367 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
368 array_keys($params['group_type'])
369 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
373 $params['group_type'] = '';
376 $session = CRM_Core_Session
::singleton();
377 $cid = $session->get('userID');
378 // this action is add
379 if ($cid && empty($params['id'])) {
380 $params['created_id'] = $cid;
382 // this action is update
383 if ($cid && !empty($params['id'])) {
384 $params['modified_id'] = $cid;
387 $group = new CRM_Contact_BAO_Group();
388 $group->copyValues($params);
389 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
390 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
391 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
392 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
393 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
394 if (isset($group->parents
) && is_array($group->parents
)) {
395 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
396 array_keys($group->parents
)
397 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
399 if (empty($params['id']) &&
402 $group->name
.= "_tmp";
410 if (empty($params['id']) &&
413 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
416 $group->buildClause();
419 // add custom field values
420 if (!empty($params['custom'])) {
421 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
424 // make the group, child of domain/site group by default.
425 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
426 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
427 if (empty($params['parents']) &&
428 $domainGroupID != $group->id
&&
429 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
432 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
434 // if no parent present and the group doesn't already have any parents,
435 // make sure site group goes as parent
436 $params['parents'] = array($domainGroupID => 1);
438 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
439 $params['parents'] = array($params['parents'] => 1);
442 if (!empty($params['parents'])) {
443 foreach ($params['parents'] as $parentId => $dnc) {
444 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
445 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
450 // clear any descendant groups cache if exists
451 $finalGroups = CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
453 // this is always required, since we don't know when a
454 // parent group is removed
455 CRM_Contact_BAO_GroupNestingCache
::update();
457 // update group contact cache for all parent groups
458 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
459 foreach ($parentIds as $parentId) {
460 CRM_Contact_BAO_GroupContactCache
::add($parentId);
464 if (!empty($params['organization_id'])) {
467 $groupOrg['group_id'] = $group->id
;
468 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
471 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
473 if (!empty($params['id'])) {
474 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
477 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
480 $recentOther = array();
481 if (CRM_Core_Permission
::check('edit groups')) {
482 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
483 // currently same permission we are using for delete a group
484 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
487 // add the recently added group (unless hidden: CRM-6432)
488 if (!$group->is_hidden
) {
489 CRM_Utils_Recent
::add($group->title
,
490 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
502 * Given a saved search compute the clause and the tables
503 * and store it for future use
505 public function buildClause() {
506 $params = array(array('group', 'IN', array($this->id
=> 1), 0, 0));
508 if (!empty($params)) {
509 $tables = $whereTables = array();
510 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
511 if (!empty($tables)) {
512 $this->select_tables
= serialize($tables);
514 if (!empty($whereTables)) {
515 $this->where_tables
= serialize($whereTables);
521 * Defines a new smart group
523 * @param array $params
524 * Associative array of parameters.
526 * @return CRM_Contact_BAO_Group|NULL
527 * The new group BAO (if created)
529 public static function createSmartGroup(&$params) {
530 if (!empty($params['formValues'])) {
532 unset($ssParams['id']);
533 if (isset($ssParams['saved_search_id'])) {
534 $ssParams['id'] = $ssParams['saved_search_id'];
537 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
539 $params['saved_search_id'] = $savedSearch->id
;
545 return self
::create($params);
549 * Update the is_active flag in the db
552 * Id of the database record.
553 * @param bool $isActive
554 * Value we want to set the is_active field.
556 * @return CRM_Core_DAO|null
557 * DAO object on success, NULL otherwise
559 public static function setIsActive($id, $isActive) {
560 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
564 * Build the condition to retrieve groups.
566 * @param string $groupType
567 * Type of group(Access/Mailing) OR the key of the group.
568 * @param bool $excludeHidden exclude hidden groups.
572 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
574 if ($groupType == 'Mailing') {
575 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
577 elseif ($groupType == 'Access') {
578 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
580 elseif (!empty($groupType)) {
581 // ie we have been given the group key
582 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
586 if ($excludeHidden) {
587 $condition = "is_hidden = 0";
592 $condition .= " AND group_type LIKE '%$value%'";
595 $condition = "group_type LIKE '%$value%'";
603 * Get permission relevant clauses
610 public static function getPermissionClause($force = FALSE) {
612 static $retrieved = FALSE;
613 if ((!$retrieved ||
$force) && !CRM_Core_Permission
::check('view all contacts') && !CRM_Core_Permission
::check('edit all contacts')) {
614 //get the allowed groups for the current user
615 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
616 if (!empty($groups)) {
617 $groupList = implode(', ', array_values($groups));
618 $clause = "groups.id IN ( $groupList ) ";
631 public function __toString() {
636 * This function create the hidden smart group when user perform
637 * contact seach and want to send mailing to search contacts.
639 * @param array $params
640 * ( reference ) an assoc array of name/value pairs.
643 * ( smartGroupId, ssId ) smart group id and saved search id
645 public static function createHiddenSmartGroup($params) {
646 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
648 //add mapping record only for search builder saved search
650 if ($params['search_context'] == 'builder') {
651 //save the mapping for search builder
653 //save record in mapping table
655 $mappingParams = array('mapping_type' => 'Search Builder');
656 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams, $temp);
657 $mappingId = $mapping->id
;
660 //get the mapping id from saved search
661 $savedSearch = new CRM_Contact_BAO_SavedSearch();
662 $savedSearch->id
= $ssId;
663 $savedSearch->find(TRUE);
664 $mappingId = $savedSearch->mapping_id
;
667 //save mapping fields
668 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
671 //create/update saved search record.
672 $savedSearch = new CRM_Contact_BAO_SavedSearch();
673 $savedSearch->id
= $ssId;
674 $savedSearch->form_values
= serialize($params['form_values']);
675 $savedSearch->mapping_id
= $mappingId;
676 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
677 $savedSearch->save();
679 $ssId = $savedSearch->id
;
684 $smartGroupId = NULL;
685 if (!empty($params['saved_search_id'])) {
686 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
689 //create group only when new saved search.
690 $groupParams = array(
691 'title' => "Hidden Smart Group {$ssId}",
692 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
693 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
694 'group_type' => CRM_Utils_Array
::value('group_type', $params),
695 'visibility' => CRM_Utils_Array
::value('visibility', $params),
696 'saved_search_id' => $ssId,
699 $smartGroup = self
::create($groupParams);
700 $smartGroupId = $smartGroup->id
;
703 return array($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 static public 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
738 $groupList = array();
739 if (!empty($groups)) {
740 foreach ($groups as $id => $value) {
741 $groupList[$id]['group_id'] = $value['id'];
742 $groupList[$id]['count'] = $value['count'];
743 $groupList[$id]['group_name'] = $value['title'];
745 // append parent names if in search mode
746 if (empty($params['parent_id']) && !empty($value['parents'])) {
747 $groupIds = explode(',', $value['parents']);
749 foreach ($groupIds as $gId) {
750 $title[] = $allGroups[$gId];
752 $groupList[$id]['group_name'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
753 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
755 $value['class'][] = 'crm-entity';
756 $groupList[$id]['class'] = $value['id'] . ',' . implode(' ', $value['class']);
758 $groupList[$id]['group_description'] = CRM_Utils_Array
::value('description', $value);
759 if (!empty($value['group_type'])) {
760 $groupList[$id]['group_type'] = $value['group_type'];
763 $groupList[$id]['group_type'] = '';
765 $groupList[$id]['visibility'] = $value['visibility'];
766 $groupList[$id]['links'] = $value['action'];
767 $groupList[$id]['org_info'] = CRM_Utils_Array
::value('org_info', $value);
768 $groupList[$id]['created_by'] = CRM_Utils_Array
::value('created_by', $value);
770 $groupList[$id]['is_parent'] = $value['is_parent'];
777 * This function to get list of groups
779 * @param array $params
780 * Associated array for params.
784 public static function getGroupList(&$params) {
785 $config = CRM_Core_Config
::singleton();
787 $whereClause = self
::whereClause($params, FALSE);
789 //$this->pagerAToZ( $whereClause, $params );
791 if (!empty($params['rowCount']) &&
792 $params['rowCount'] > 0
794 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
797 $orderBy = ' ORDER BY groups.title asc';
798 if (!empty($params['sort'])) {
799 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
802 $select = $from = $where = "";
804 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
805 CRM_Core_Permission
::isMultisiteEnabled()
807 $select = ", contact.display_name as org_name, contact.id as org_id";
808 $from = " LEFT JOIN civicrm_group_organization gOrg
809 ON gOrg.group_id = groups.id
810 LEFT JOIN civicrm_contact contact
811 ON contact.id = gOrg.organization_id ";
813 //get the Organization ID
814 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
816 $where = " AND gOrg.organization_id = {$orgID}";
823 SELECT groups.*, createdBy.sort_name as created_by {$select}
824 FROM civicrm_group groups
825 LEFT JOIN civicrm_contact createdBy
826 ON createdBy.id = groups.created_id
828 WHERE $whereClause {$where}
833 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
835 //FIXME CRM-4418, now we are handling delete separately
836 //if we introduce 'delete for group' make sure to handle here.
837 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
838 if (CRM_Core_Permission
::check('edit groups')) {
839 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
840 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
844 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
846 $links = self
::actionLinks();
848 $allTypes = CRM_Core_OptionGroup
::values('group_type');
849 $values = $groupsToCount = array();
851 $visibility = CRM_Core_SelectValues
::ufVisibility();
853 while ($object->fetch()) {
854 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
855 //@todo CRM-12209 introduced an ACL check in the whereClause function
856 // it may be that this checking is now obsolete - or that what remains
857 // should be removed to the whereClause (which is also accessed by getCount)
861 $values[$object->id
] = array(
865 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
866 if ($object->saved_search_id
) {
867 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
868 // check if custom search, if so fix view link
869 $customSearchID = CRM_Core_DAO
::getFieldValue(
870 'CRM_Contact_DAO_SavedSearch',
871 $object->saved_search_id
,
875 if ($customSearchID) {
876 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
877 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
881 $action = array_sum(array_keys($newLinks));
884 if (array_key_exists('is_reserved', $object)) {
885 //if group is reserved and I don't have reserved permission, suppress delete/edit
886 if ($object->is_reserved
&& !$reservedPermission) {
887 $action -= CRM_Core_Action
::DELETE
;
888 $action -= CRM_Core_Action
::UPDATE
;
889 $action -= CRM_Core_Action
::DISABLE
;
893 if (array_key_exists('is_active', $object)) {
894 if ($object->is_active
) {
895 $action -= CRM_Core_Action
::ENABLE
;
898 $values[$object->id
]['class'][] = 'disabled';
899 $action -= CRM_Core_Action
::VIEW
;
900 $action -= CRM_Core_Action
::DISABLE
;
904 $action = $action & CRM_Core_Action
::mask($groupPermissions);
906 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
908 $groupsToCount[$object->saved_search_id ?
'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id
;
910 if (isset($values[$object->id
]['group_type'])) {
911 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
912 substr($values[$object->id
]['group_type'], 1, -1)
915 foreach ($groupTypes as $type) {
916 $types[] = CRM_Utils_Array
::value($type, $allTypes);
918 $values[$object->id
]['group_type'] = implode(', ', $types);
920 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
924 'ssid' => $object->saved_search_id
,
928 'group.selector.row',
933 // If group has children, add class for link to view children
934 $values[$object->id
]['is_parent'] = FALSE;
935 if (array_key_exists('children', $values[$object->id
])) {
936 $values[$object->id
]['class'][] = "crm-group-parent";
937 $values[$object->id
]['is_parent'] = TRUE;
940 // If group is a child, add child class
941 if (array_key_exists('parents', $values[$object->id
])) {
942 $values[$object->id
]['class'][] = "crm-group-child";
946 if ($object->org_id
) {
947 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
948 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
951 $values[$object->id
]['org_info'] = ''; // Empty cell
955 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
957 if ($object->created_id
) {
958 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
959 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
964 // Get group counts - executes one query for regular groups and another for smart groups
965 foreach ($groupsToCount as $table => $groups) {
966 $where = "g.group_id IN (" . implode(',', $groups) . ")";
967 if ($table == 'civicrm_group_contact') {
968 $where .= " AND g.status = 'Added'";
970 // Exclude deleted contacts
971 $where .= " and c.id = g.contact_id AND c.is_deleted = 0";
972 $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");
973 while ($dao->fetch()) {
974 $values[$dao->group_id
]['count'] = $dao->count
;
982 * This function to get hierarchical list of groups (parent followed by children)
984 * @param array $groupIDs
985 * Array of group ids.
987 * @param NULL $parents
988 * @param string $spacer
989 * @param bool $titleOnly
993 public static function getGroupsHierarchy(
996 $spacer = '<span class="child-indent"></span>',
999 if (empty($groupIDs)) {
1003 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1004 // <span class="child-icon"></span>
1005 // need to return id, title (w/ spacer), description, visibility
1007 // We need to build a list of tags ordered by hierarchy and sorted by
1008 // name. The heirarchy will be communicated by an accumulation of
1009 // separators in front of the name to give it a visual offset.
1010 // Instead of recursively making mysql queries, we'll make one big
1011 // query and build the heirarchy with the algorithm below.
1013 $args = array(1 => array($groupIdString, 'String'));
1015 SELECT id, title, description, visibility, parents
1017 WHERE id IN $groupIdString
1020 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1021 $parentArray = explode(',', $parents);
1022 $parent = $parentArray[0];
1023 $args[2] = array($parent, 'Integer');
1024 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1026 $query .= " ORDER BY title";
1027 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1029 // Sort the groups into the correct storage by the parent
1030 // $roots represent the current leaf nodes that need to be checked for
1031 // children. $rows represent the unplaced nodes
1032 $roots = $rows = $allGroups = array();
1033 while ($dao->fetch()) {
1034 $allGroups[$dao->id
] = array(
1035 'title' => $dao->title
,
1036 'visibility' => $dao->visibility
,
1037 'description' => $dao->description
,
1040 if ($dao->parents
== $parents) {
1044 'title' => $dao->title
,
1048 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1049 $parentArray = explode(',', $dao->parents
);
1050 $parent = $parentArray[0];
1054 'title' => $dao->title
,
1055 'parents' => $parent,
1060 // While we have nodes left to build, shift the first (alphabetically)
1061 // node of the list, place it in our groups list and loop through the
1062 // list of unplaced nodes to find its children. We make a copy to
1063 // iterate through because we must modify the unplaced nodes list
1065 while (count($roots)) {
1066 $new_roots = array();
1067 $current_rows = $rows;
1068 $root = array_shift($roots);
1069 $groups[$root['id']] = array($root['prefix'], $root['title']);
1071 // As you find the children, append them to the end of the new set
1072 // of roots (maintain alphabetical ordering). Also remove the node
1073 // from the set of unplaced nodes.
1074 if (is_array($current_rows)) {
1075 foreach ($current_rows as $key => $row) {
1076 if ($row['parents'] == $root['id']) {
1077 $new_roots[] = array(
1079 'prefix' => $groups[$root['id']][0] . $spacer,
1080 'title' => $row['title'],
1087 //As a group, insert the new roots into the beginning of the roots
1088 //list. This maintains the hierarchical ordering of the tags.
1089 $roots = array_merge($new_roots, $roots);
1092 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1093 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1094 foreach ($rows as $value) {
1095 $groups[$value['id']] = array($value['prefix'], $value['title']);
1097 // Prefix titles with the calcuated spacing to give the visual
1098 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1099 $groupsReturn = array();
1100 foreach ($groups as $key => $value) {
1102 $groupsReturn[$key] = $value[0] . $value[1];
1105 $groupsReturn[$key] = array(
1106 'title' => $value[0] . $value[1],
1107 'description' => $allGroups[$key]['description'],
1108 'visibility' => $allGroups[$key]['visibility'],
1113 return $groupsReturn;
1117 * @param array $params
1119 * @return NULL|string
1121 public static function getGroupCount(&$params) {
1122 $whereClause = self
::whereClause($params, FALSE);
1123 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1125 if (!empty($params['created_by'])) {
1127 INNER JOIN civicrm_contact createdBy
1128 ON createdBy.id = groups.created_id";
1131 WHERE {$whereClause}";
1132 return CRM_Core_DAO
::singleValueQuery($query, $params);
1136 * Generate permissioned where clause for group search
1137 * @param array $params
1138 * @param bool $sortBy
1139 * @param bool $excludeHidden
1143 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1145 $title = CRM_Utils_Array
::value('title', $params);
1147 $clauses[] = "groups.title LIKE %1";
1148 if (strpos($title, '%') !== FALSE) {
1149 $params[1] = array($title, 'String', FALSE);
1152 $params[1] = array($title, 'String', TRUE);
1156 $groupType = CRM_Utils_Array
::value('group_type', $params);
1158 $types = explode(',', $groupType);
1159 if (!empty($types)) {
1160 $clauses[] = 'groups.group_type LIKE %2';
1161 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1162 $params[2] = array($typeString, 'String', TRUE);
1166 $visibility = CRM_Utils_Array
::value('visibility', $params);
1168 $clauses[] = 'groups.visibility = %3';
1169 $params[3] = array($visibility, 'String');
1172 $groupStatus = CRM_Utils_Array
::value('status', $params);
1174 switch ($groupStatus) {
1176 $clauses[] = 'groups.is_active = 1';
1177 $params[4] = array($groupStatus, 'Integer');
1181 $clauses[] = 'groups.is_active = 0';
1182 $params[4] = array($groupStatus, 'Integer');
1186 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1191 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1193 $clauses[] = 'groups.parents IS NULL';
1196 // only show child groups of a specific parent group
1197 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1199 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1200 $params[5] = array($parent_id, 'Integer');
1203 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1204 $clauses[] = "createdBy.sort_name LIKE %6";
1205 if (strpos($createdBy, '%') !== FALSE) {
1206 $params[6] = array($createdBy, 'String', FALSE);
1209 $params[6] = array($createdBy, 'String', TRUE);
1213 if (empty($clauses)) {
1214 $clauses[] = 'groups.is_active = 1';
1217 if ($excludeHidden) {
1218 $clauses[] = 'groups.is_hidden = 0';
1221 $clauses[] = self
::getPermissionClause();
1223 return implode(' AND ', $clauses);
1227 * Define action links
1230 * array of action links
1232 public static function actionLinks() {
1234 CRM_Core_Action
::VIEW
=> array(
1235 'name' => ts('Contacts'),
1236 'url' => 'civicrm/group/search',
1237 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1238 'title' => ts('Group Contacts'),
1240 CRM_Core_Action
::UPDATE
=> array(
1241 'name' => ts('Settings'),
1242 'url' => 'civicrm/group',
1243 'qs' => 'reset=1&action=update&id=%%id%%',
1244 'title' => ts('Edit Group'),
1246 CRM_Core_Action
::DISABLE
=> array(
1247 'name' => ts('Disable'),
1248 'ref' => 'crm-enable-disable',
1249 'title' => ts('Disable Group'),
1251 CRM_Core_Action
::ENABLE
=> array(
1252 'name' => ts('Enable'),
1253 'ref' => 'crm-enable-disable',
1254 'title' => ts('Enable Group'),
1256 CRM_Core_Action
::DELETE
=> array(
1257 'name' => ts('Delete'),
1258 'url' => 'civicrm/group',
1259 'qs' => 'reset=1&action=delete&id=%%id%%',
1260 'title' => ts('Delete Group'),
1268 * @param $whereClause
1269 * @param array $whereParams
1273 public function pagerAtoZ($whereClause, $whereParams) {
1275 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1276 FROM civicrm_group groups
1278 ORDER BY LEFT(groups.title, 1)
1280 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1282 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);