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
59 public static function retrieve(&$params, &$defaults) {
60 $group = new CRM_Contact_DAO_Group();
61 $group->copyValues($params);
62 if ($group->find(TRUE)) {
63 CRM_Core_DAO
::storeValues($group, $defaults);
71 * Delete the group and all the object that connect to
72 * this group. Incredibly destructive
80 public static function discard($id) {
81 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
83 $transaction = new CRM_Core_Transaction();
85 // added for CRM-1631 and CRM-1794
86 // delete all subscribed mails with the selected group id
87 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
88 $subscribe->group_id
= $id;
91 // delete all Subscription records with the selected group id
92 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
93 $subHistory->group_id
= $id;
94 $subHistory->delete();
96 // delete all crm_group_contact records with the selected group id
97 $groupContact = new CRM_Contact_DAO_GroupContact();
98 $groupContact->group_id
= $id;
99 $groupContact->delete();
101 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
102 $params = array(1 => array($id, 'Integer'));
103 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
104 CRM_Core_DAO
::executeQuery($query, $params);
106 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
107 CRM_Core_DAO
::executeQuery($query, $params);
109 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
111 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
112 CRM_Core_DAO
::executeQuery($query, $params);
114 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
115 CRM_Core_DAO
::executeQuery($query, $params);
117 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
118 CRM_Core_DAO
::executeQuery($query, $params);
120 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
124 // clear any descendant groups cache if exists
125 CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
128 // delete from group table
129 $group = new CRM_Contact_DAO_Group();
133 $transaction->commit();
135 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
137 // delete the recently created Group
138 $groupRecent = array(
142 CRM_Utils_Recent
::del($groupRecent);
146 * Returns an array of the contacts in the given group.
148 public static function getGroupContacts($id) {
149 $params = array(array('group', 'IN', array($id => 1), 0, 0));
150 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
155 * Get the count of a members in a group with the specific status
159 * @param string $status
160 * status of members in group
161 * @param bool $countChildGroups
164 * count of members in the group with above status
166 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
167 $groupContact = new CRM_Contact_DAO_GroupContact();
168 $groupIds = array($id);
169 if ($countChildGroups) {
170 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
174 $contacts = self
::getGroupContacts($id);
176 foreach ($groupIds as $groupId) {
178 $groupContacts = self
::getGroupContacts($groupId);
179 foreach ($groupContacts as $gcontact) {
180 if ($groupId != $id) {
181 // Loop through main group's contacts
182 // and subtract from the count for each contact which
183 // matches one in the present group, if it is not the
185 foreach ($contacts as $contact) {
186 if ($contact['contact_id'] == $gcontact['contact_id']) {
192 $groupContact->group_id
= $groupId;
193 if (isset($status)) {
194 $groupContact->status
= $status;
196 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
197 $count +
= $groupContact->count();
203 * Get the list of member for a group id
205 * @param int $groupID
206 * @param bool $useCache
209 * this array contains the list of members for this group id
212 public static function &getMember($groupID, $useCache = TRUE) {
213 $params = array(array('group', 'IN', array($groupID => 1), 0, 0));
214 $returnProperties = array('contact_id');
215 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, $useCache);
218 foreach ($contacts as $contact) {
219 $aMembers[$contact['contact_id']] = 1;
226 * Returns array of group object(s) matching a set of one or Group properties.
228 * @param array $params
229 * Limits the set of groups returned.
230 * @param array $returnProperties
231 * Which properties should be included in the returned group objects.
232 * (member_count should be last element.)
233 * @param string $sort
235 * @param int $rowCount
238 * Array of group objects.
241 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
242 * add in essential fields (e.g. id). This should follow a regular pattern like the others
244 static function getGroups(
246 $returnProperties = NULL,
251 $dao = new CRM_Contact_DAO_Group();
252 if (!isset($params['is_active'])) {
256 foreach ($params as $k => $v) {
257 if ($k == 'name' ||
$k == 'title') {
258 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
260 elseif ($k == 'group_type') {
261 foreach ((array) $v as $type) {
262 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
265 elseif (is_array($v)) {
266 foreach ($v as &$num) {
269 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
277 if ($offset ||
$rowCount) {
278 $offset = ($offset > 0) ?
$offset : 0;
279 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
280 $dao->limit($offset, $rowCount);
284 $dao->orderBy($sort);
287 // return only specific fields if returnproperties are sent
288 if (!empty($returnProperties)) {
290 $dao->selectAdd(implode(',', $returnProperties));
294 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
297 while ($dao->fetch()) {
298 $group = new CRM_Contact_DAO_Group();
300 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
302 $groups[] = clone($dao);
308 * Make sure that the user has permission to access this group
311 * The id of the object.
314 * the permission that the user has (or NULL)
317 public static function checkPermission($id) {
318 $allGroups = CRM_Core_PseudoConstant
::allGroup();
321 if (CRM_Core_Permission
::check('edit all contacts') ||
322 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
323 'civicrm_saved_search', $allGroups
326 $permissions[] = CRM_Core_Permission
::EDIT
;
329 if (CRM_Core_Permission
::check('view all contacts') ||
330 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
331 'civicrm_saved_search', $allGroups
334 $permissions[] = CRM_Core_Permission
::VIEW
;
337 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
338 // Note: using !empty() in if condition, restricts the scope of delete
339 // permission to groups/contacts that are editable/viewable.
340 // We can remove this !empty condition once we have ACL support for delete functionality.
341 $permissions[] = CRM_Core_Permission
::DELETE
;
350 * @param array $params
352 * @return CRM_Contact_BAO_Group|NULL
353 * The new group BAO (if created)
356 public static function &create(&$params) {
358 if (!empty($params['id'])) {
359 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
362 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
365 // form the name only if missing: CRM-627
366 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
367 if (!$nameParam && empty($params['id'])) {
368 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
371 // convert params if array type
372 if (isset($params['group_type'])) {
373 if (is_array($params['group_type'])) {
374 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
375 array_keys($params['group_type'])
376 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
380 $params['group_type'] = '';
383 $session = CRM_Core_Session
::singleton();
384 $cid = $session->get('userID');
385 // this action is add
386 if ($cid && empty($params['id'])) {
387 $params['created_id'] = $cid;
389 // this action is update
390 if ($cid && !empty($params['id'])) {
391 $params['modified_id'] = $cid;
394 $group = new CRM_Contact_BAO_Group();
395 $group->copyValues($params);
396 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
397 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
398 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
399 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
400 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
401 if (isset($group->parents
) && is_array($group->parents
)) {
402 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
403 array_keys($group->parents
)
404 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
406 if (empty($params['id']) &&
409 $group->name
.= "_tmp";
417 if (empty($params['id']) &&
420 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
423 $group->buildClause();
426 // add custom field values
427 if (!empty($params['custom'])) {
428 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
431 // make the group, child of domain/site group by default.
432 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
433 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
434 if (empty($params['parents']) &&
435 $domainGroupID != $group->id
&&
436 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
439 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
441 // if no parent present and the group doesn't already have any parents,
442 // make sure site group goes as parent
443 $params['parents'] = array($domainGroupID => 1);
445 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
446 $params['parents'] = array($params['parents'] => 1);
449 if (!empty($params['parents'])) {
450 foreach ($params['parents'] as $parentId => $dnc) {
451 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
452 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
457 // clear any descendant groups cache if exists
458 $finalGroups = CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
460 // this is always required, since we don't know when a
461 // parent group is removed
462 CRM_Contact_BAO_GroupNestingCache
::update();
464 // update group contact cache for all parent groups
465 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
466 foreach ($parentIds as $parentId) {
467 CRM_Contact_BAO_GroupContactCache
::add($parentId);
471 if (!empty($params['organization_id'])) {
474 $groupOrg['group_id'] = $group->id
;
475 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
478 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
480 if (!empty($params['id'])) {
481 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
484 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
487 $recentOther = array();
488 if (CRM_Core_Permission
::check('edit groups')) {
489 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
490 // currently same permission we are using for delete a group
491 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
494 // add the recently added group (unless hidden: CRM-6432)
495 if (!$group->is_hidden
) {
496 CRM_Utils_Recent
::add($group->title
,
497 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
509 * Given a saved search compute the clause and the tables
510 * and store it for future use
512 public function buildClause() {
513 $params = array(array('group', 'IN', array($this->id
=> 1), 0, 0));
515 if (!empty($params)) {
516 $tables = $whereTables = array();
517 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
518 if (!empty($tables)) {
519 $this->select_tables
= serialize($tables);
521 if (!empty($whereTables)) {
522 $this->where_tables
= serialize($whereTables);
530 * Defines a new smart group
532 * @param array $params
533 * Associative array of parameters.
535 * @return CRM_Contact_BAO_Group|NULL
536 * The new group BAO (if created)
539 public static function createSmartGroup(&$params) {
540 if (!empty($params['formValues'])) {
542 unset($ssParams['id']);
543 if (isset($ssParams['saved_search_id'])) {
544 $ssParams['id'] = $ssParams['saved_search_id'];
547 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
549 $params['saved_search_id'] = $savedSearch->id
;
555 return self
::create($params);
559 * Update the is_active flag in the db
562 * Id of the database record.
563 * @param bool $isActive
564 * Value we want to set the is_active field.
566 * @return CRM_Core_DAO|null
567 * DAO object on success, NULL otherwise
570 public static function setIsActive($id, $isActive) {
571 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
575 * Build the condition to retrieve groups.
577 * @param string $groupType
578 * Type of group(Access/Mailing) OR the key of the group.
579 * @param bool $excludeHidden exclude hidden groups.
584 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
586 if ($groupType == 'Mailing') {
587 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
589 elseif ($groupType == 'Access') {
590 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
592 elseif (!empty($groupType)) {
593 // ie we have been given the group key
594 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
598 if ($excludeHidden) {
599 $condition = "is_hidden = 0";
604 $condition .= " AND group_type LIKE '%$value%'";
607 $condition = "group_type LIKE '%$value%'";
615 * Get permission relevant clauses
622 public static function getPermissionClause($force = FALSE) {
624 static $retrieved = FALSE;
625 if ((!$retrieved ||
$force) && !CRM_Core_Permission
::check('view all contacts') && !CRM_Core_Permission
::check('edit all contacts')) {
626 //get the allowed groups for the current user
627 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
628 if (!empty($groups)) {
629 $groupList = implode(', ', array_values($groups));
630 $clause = "groups.id IN ( $groupList ) ";
643 public function __toString() {
648 * This function create the hidden smart group when user perform
649 * contact seach and want to send mailing to search contacts.
651 * @param array $params
652 * ( reference ) an assoc array of name/value pairs.
655 * ( smartGroupId, ssId ) smart group id and saved search id
658 public static function createHiddenSmartGroup($params) {
659 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
661 //add mapping record only for search builder saved search
663 if ($params['search_context'] == 'builder') {
664 //save the mapping for search builder
666 //save record in mapping table
668 $mappingParams = array('mapping_type' => 'Search Builder');
669 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams, $temp);
670 $mappingId = $mapping->id
;
673 //get the mapping id from saved search
674 $savedSearch = new CRM_Contact_BAO_SavedSearch();
675 $savedSearch->id
= $ssId;
676 $savedSearch->find(TRUE);
677 $mappingId = $savedSearch->mapping_id
;
680 //save mapping fields
681 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
684 //create/update saved search record.
685 $savedSearch = new CRM_Contact_BAO_SavedSearch();
686 $savedSearch->id
= $ssId;
687 $savedSearch->form_values
= serialize($params['form_values']);
688 $savedSearch->mapping_id
= $mappingId;
689 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
690 $savedSearch->save();
692 $ssId = $savedSearch->id
;
697 $smartGroupId = NULL;
698 if (!empty($params['saved_search_id'])) {
699 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
702 //create group only when new saved search.
703 $groupParams = array(
704 'title' => "Hidden Smart Group {$ssId}",
705 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
706 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
707 'group_type' => CRM_Utils_Array
::value('group_type', $params),
708 'visibility' => CRM_Utils_Array
::value('visibility', $params),
709 'saved_search_id' => $ssId,
712 $smartGroup = self
::create($groupParams);
713 $smartGroupId = $smartGroup->id
;
716 return array($smartGroupId, $ssId);
720 * wrapper for ajax group selector
722 * @param array $params
723 * Associated array for params record id.
726 * associated array of group list
729 * @todo there seems little reason for the small number of functions that call this to pass in
730 * params that then need to be translated in this function since they are coding them when calling
732 static public function getGroupListSelector(&$params) {
734 $params['offset'] = ($params['page'] - 1) * $params['rp'];
735 $params['rowCount'] = $params['rp'];
736 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
739 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
741 //skip total if we are making call to show only children
742 if (empty($params['parent_id'])) {
744 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
746 // get all the groups
747 $allGroups = CRM_Core_PseudoConstant
::allGroup();
750 // format params and add links
751 $groupList = array();
752 if (!empty($groups)) {
753 foreach ($groups as $id => $value) {
754 $groupList[$id]['group_id'] = $value['id'];
755 $groupList[$id]['count'] = $value['count'];
756 $groupList[$id]['group_name'] = $value['title'];
758 // append parent names if in search mode
759 if (empty($params['parent_id']) && !empty($value['parents'])) {
760 $groupIds = explode(',', $value['parents']);
762 foreach ($groupIds as $gId) {
763 $title[] = $allGroups[$gId];
765 $groupList[$id]['group_name'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
766 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
768 $value['class'][] = 'crm-entity';
769 $groupList[$id]['class'] = $value['id'] . ',' . implode(' ', $value['class']);
771 $groupList[$id]['group_description'] = CRM_Utils_Array
::value('description', $value);
772 if (!empty($value['group_type'])) {
773 $groupList[$id]['group_type'] = $value['group_type'];
776 $groupList[$id]['group_type'] = '';
778 $groupList[$id]['visibility'] = $value['visibility'];
779 $groupList[$id]['links'] = $value['action'];
780 $groupList[$id]['org_info'] = CRM_Utils_Array
::value('org_info', $value);
781 $groupList[$id]['created_by'] = CRM_Utils_Array
::value('created_by', $value);
783 $groupList[$id]['is_parent'] = $value['is_parent'];
790 * This function to get list of groups
792 * @param array $params
793 * Associated array for params.
797 public static function getGroupList(&$params) {
798 $config = CRM_Core_Config
::singleton();
800 $whereClause = self
::whereClause($params, FALSE);
802 //$this->pagerAToZ( $whereClause, $params );
804 if (!empty($params['rowCount']) &&
805 $params['rowCount'] > 0
807 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
810 $orderBy = ' ORDER BY groups.title asc';
811 if (!empty($params['sort'])) {
812 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
815 $select = $from = $where = "";
817 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
818 CRM_Core_Permission
::isMultisiteEnabled()
820 $select = ", contact.display_name as org_name, contact.id as org_id";
821 $from = " LEFT JOIN civicrm_group_organization gOrg
822 ON gOrg.group_id = groups.id
823 LEFT JOIN civicrm_contact contact
824 ON contact.id = gOrg.organization_id ";
826 //get the Organization ID
827 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
829 $where = " AND gOrg.organization_id = {$orgID}";
836 SELECT groups.*, createdBy.sort_name as created_by {$select}
837 FROM civicrm_group groups
838 LEFT JOIN civicrm_contact createdBy
839 ON createdBy.id = groups.created_id
841 WHERE $whereClause {$where}
846 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
848 //FIXME CRM-4418, now we are handling delete separately
849 //if we introduce 'delete for group' make sure to handle here.
850 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
851 if (CRM_Core_Permission
::check('edit groups')) {
852 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
853 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
857 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
859 $links = self
::actionLinks();
861 $allTypes = CRM_Core_OptionGroup
::values('group_type');
862 $values = $groupsToCount = array();
864 $visibility = CRM_Core_SelectValues
::ufVisibility();
866 while ($object->fetch()) {
867 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
868 //@todo CRM-12209 introduced an ACL check in the whereClause function
869 // it may be that this checking is now obsolete - or that what remains
870 // should be removed to the whereClause (which is also accessed by getCount)
874 $values[$object->id
] = array(
878 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
879 if ($object->saved_search_id
) {
880 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
881 // check if custom search, if so fix view link
882 $customSearchID = CRM_Core_DAO
::getFieldValue(
883 'CRM_Contact_DAO_SavedSearch',
884 $object->saved_search_id
,
888 if ($customSearchID) {
889 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
890 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
894 $action = array_sum(array_keys($newLinks));
897 if (array_key_exists('is_reserved', $object)) {
898 //if group is reserved and I don't have reserved permission, suppress delete/edit
899 if ($object->is_reserved
&& !$reservedPermission) {
900 $action -= CRM_Core_Action
::DELETE
;
901 $action -= CRM_Core_Action
::UPDATE
;
902 $action -= CRM_Core_Action
::DISABLE
;
906 if (array_key_exists('is_active', $object)) {
907 if ($object->is_active
) {
908 $action -= CRM_Core_Action
::ENABLE
;
911 $values[$object->id
]['class'][] = 'disabled';
912 $action -= CRM_Core_Action
::VIEW
;
913 $action -= CRM_Core_Action
::DISABLE
;
917 $action = $action & CRM_Core_Action
::mask($groupPermissions);
919 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
921 $groupsToCount[$object->saved_search_id ?
'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id
;
923 if (isset($values[$object->id
]['group_type'])) {
924 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
925 substr($values[$object->id
]['group_type'], 1, -1)
928 foreach ($groupTypes as $type) {
929 $types[] = CRM_Utils_Array
::value($type, $allTypes);
931 $values[$object->id
]['group_type'] = implode(', ', $types);
933 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
937 'ssid' => $object->saved_search_id
,
941 'group.selector.row',
946 // If group has children, add class for link to view children
947 $values[$object->id
]['is_parent'] = FALSE;
948 if (array_key_exists('children', $values[$object->id
])) {
949 $values[$object->id
]['class'][] = "crm-group-parent";
950 $values[$object->id
]['is_parent'] = TRUE;
953 // If group is a child, add child class
954 if (array_key_exists('parents', $values[$object->id
])) {
955 $values[$object->id
]['class'][] = "crm-group-child";
959 if ($object->org_id
) {
960 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
961 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
964 $values[$object->id
]['org_info'] = ''; // Empty cell
968 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
970 if ($object->created_id
) {
971 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
972 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
978 foreach ($groupsToCount as $table => $groups) {
979 $where = "group_id IN (" . implode(',', $groups) . ")";
980 if ($table == 'civicrm_group_contact') {
981 $where .= " AND status = 'Added'";
983 $dao = CRM_Core_DAO
::executeQuery("SELECT group_id, COUNT(id) as `count` FROM $table WHERE $where GROUP BY group_id");
984 while ($dao->fetch()) {
985 $values[$dao->group_id
]['count'] = $dao->count
;
993 * This function to get hierarchical list of groups (parent followed by children)
995 * @param array $groupIDs
996 * Array of group ids.
998 * @param NULL $parents
999 * @param string $spacer
1000 * @param bool $titleOnly
1004 static function getGroupsHierarchy(
1007 $spacer = '<span class="child-indent"></span>',
1010 if (empty($groupIDs)) {
1014 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1015 // <span class="child-icon"></span>
1016 // need to return id, title (w/ spacer), description, visibility
1018 // We need to build a list of tags ordered by hierarchy and sorted by
1019 // name. The heirarchy will be communicated by an accumulation of
1020 // separators in front of the name to give it a visual offset.
1021 // Instead of recursively making mysql queries, we'll make one big
1022 // query and build the heirarchy with the algorithm below.
1024 $args = array(1 => array($groupIdString, 'String'));
1026 SELECT id, title, description, visibility, parents
1028 WHERE id IN $groupIdString
1031 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1032 $parentArray = explode(',', $parents);
1033 $parent = $parentArray[0];
1034 $args[2] = array($parent, 'Integer');
1035 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1037 $query .= " ORDER BY title";
1038 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1040 // Sort the groups into the correct storage by the parent
1041 // $roots represent the current leaf nodes that need to be checked for
1042 // children. $rows represent the unplaced nodes
1043 $roots = $rows = $allGroups = array();
1044 while ($dao->fetch()) {
1045 $allGroups[$dao->id
] = array(
1046 'title' => $dao->title
,
1047 'visibility' => $dao->visibility
,
1048 'description' => $dao->description
,
1051 if ($dao->parents
== $parents) {
1055 'title' => $dao->title
,
1059 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1060 $parentArray = explode(',', $dao->parents
);
1061 $parent = $parentArray[0];
1065 'title' => $dao->title
,
1066 'parents' => $parent,
1071 // While we have nodes left to build, shift the first (alphabetically)
1072 // node of the list, place it in our groups list and loop through the
1073 // list of unplaced nodes to find its children. We make a copy to
1074 // iterate through because we must modify the unplaced nodes list
1076 while (count($roots)) {
1077 $new_roots = array();
1078 $current_rows = $rows;
1079 $root = array_shift($roots);
1080 $groups[$root['id']] = array($root['prefix'], $root['title']);
1082 // As you find the children, append them to the end of the new set
1083 // of roots (maintain alphabetical ordering). Also remove the node
1084 // from the set of unplaced nodes.
1085 if (is_array($current_rows)) {
1086 foreach ($current_rows as $key => $row) {
1087 if ($row['parents'] == $root['id']) {
1088 $new_roots[] = array(
1090 'prefix' => $groups[$root['id']][0] . $spacer,
1091 'title' => $row['title'],
1098 //As a group, insert the new roots into the beginning of the roots
1099 //list. This maintains the hierarchical ordering of the tags.
1100 $roots = array_merge($new_roots, $roots);
1103 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1104 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1105 foreach ($rows as $value) {
1106 $groups[$value['id']] = array($value['prefix'], $value['title']);
1108 // Prefix titles with the calcuated spacing to give the visual
1109 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1110 $groupsReturn = array();
1111 foreach ($groups as $key => $value) {
1113 $groupsReturn[$key] = $value[0] . $value[1];
1116 $groupsReturn[$key] = array(
1117 'title' => $value[0] . $value[1],
1118 'description' => $allGroups[$key]['description'],
1119 'visibility' => $allGroups[$key]['visibility'],
1124 return $groupsReturn;
1128 * @param array $params
1130 * @return NULL|string
1132 public static function getGroupCount(&$params) {
1133 $whereClause = self
::whereClause($params, FALSE);
1134 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1136 if (!empty($params['created_by'])) {
1138 INNER JOIN civicrm_contact createdBy
1139 ON createdBy.id = groups.created_id";
1142 WHERE {$whereClause}";
1143 return CRM_Core_DAO
::singleValueQuery($query, $params);
1147 * Generate permissioned where clause for group search
1148 * @param array $params
1149 * @param bool $sortBy
1150 * @param bool $excludeHidden
1154 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1156 $title = CRM_Utils_Array
::value('title', $params);
1158 $clauses[] = "groups.title LIKE %1";
1159 if (strpos($title, '%') !== FALSE) {
1160 $params[1] = array($title, 'String', FALSE);
1163 $params[1] = array($title, 'String', TRUE);
1167 $groupType = CRM_Utils_Array
::value('group_type', $params);
1169 $types = explode(',', $groupType);
1170 if (!empty($types)) {
1171 $clauses[] = 'groups.group_type LIKE %2';
1172 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1173 $params[2] = array($typeString, 'String', TRUE);
1177 $visibility = CRM_Utils_Array
::value('visibility', $params);
1179 $clauses[] = 'groups.visibility = %3';
1180 $params[3] = array($visibility, 'String');
1183 $groupStatus = CRM_Utils_Array
::value('status', $params);
1185 switch ($groupStatus) {
1187 $clauses[] = 'groups.is_active = 1';
1188 $params[4] = array($groupStatus, 'Integer');
1192 $clauses[] = 'groups.is_active = 0';
1193 $params[4] = array($groupStatus, 'Integer');
1197 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1202 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1204 $clauses[] = 'groups.parents IS NULL';
1207 // only show child groups of a specific parent group
1208 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1210 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1211 $params[5] = array($parent_id, 'Integer');
1214 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1215 $clauses[] = "createdBy.sort_name LIKE %6";
1216 if (strpos($createdBy, '%') !== FALSE) {
1217 $params[6] = array($createdBy, 'String', FALSE);
1220 $params[6] = array($createdBy, 'String', TRUE);
1224 if (empty($clauses)) {
1225 $clauses[] = 'groups.is_active = 1';
1228 if ($excludeHidden) {
1229 $clauses[] = 'groups.is_hidden = 0';
1232 $clauses[] = self
::getPermissionClause();
1235 return implode(' AND ', $clauses);
1239 * Define action links
1242 * array of action links
1244 public static function actionLinks() {
1246 CRM_Core_Action
::VIEW
=> array(
1247 'name' => ts('Contacts'),
1248 'url' => 'civicrm/group/search',
1249 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1250 'title' => ts('Group Contacts'),
1252 CRM_Core_Action
::UPDATE
=> array(
1253 'name' => ts('Settings'),
1254 'url' => 'civicrm/group',
1255 'qs' => 'reset=1&action=update&id=%%id%%',
1256 'title' => ts('Edit Group'),
1258 CRM_Core_Action
::DISABLE
=> array(
1259 'name' => ts('Disable'),
1260 'ref' => 'crm-enable-disable',
1261 'title' => ts('Disable Group'),
1263 CRM_Core_Action
::ENABLE
=> array(
1264 'name' => ts('Enable'),
1265 'ref' => 'crm-enable-disable',
1266 'title' => ts('Enable Group'),
1268 CRM_Core_Action
::DELETE
=> array(
1269 'name' => ts('Delete'),
1270 'url' => 'civicrm/group',
1271 'qs' => 'reset=1&action=delete&id=%%id%%',
1272 'title' => ts('Delete Group'),
1280 * @param $whereClause
1281 * @param array $whereParams
1285 public function pagerAtoZ($whereClause, $whereParams) {
1287 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1288 FROM civicrm_group groups
1290 ORDER BY LEFT(groups.title, 1)
1292 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1294 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);