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 object
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
81 public static function discard($id) {
82 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
84 $transaction = new CRM_Core_Transaction();
86 // added for CRM-1631 and CRM-1794
87 // delete all subscribed mails with the selected group id
88 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
89 $subscribe->group_id
= $id;
92 // delete all Subscription records with the selected group id
93 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
94 $subHistory->group_id
= $id;
95 $subHistory->delete();
97 // delete all crm_group_contact records with the selected group id
98 $groupContact = new CRM_Contact_DAO_GroupContact();
99 $groupContact->group_id
= $id;
100 $groupContact->delete();
102 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
103 $params = array(1 => array($id, 'Integer'));
104 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
105 CRM_Core_DAO
::executeQuery($query, $params);
107 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
108 CRM_Core_DAO
::executeQuery($query, $params);
110 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
112 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
113 CRM_Core_DAO
::executeQuery($query, $params);
115 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
116 CRM_Core_DAO
::executeQuery($query, $params);
118 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
119 CRM_Core_DAO
::executeQuery($query, $params);
121 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.
149 public static function getGroupContacts($id) {
150 $params = array(array('group', 'IN', array($id => 1), 0, 0));
151 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
156 * Get the count of a members in a group with the specific status
160 * @param enum|string $status status of members in group
162 * @param bool $countChildGroups
164 * @return int 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
208 * @return array $aMembers this array contains the list of members for this group id
211 public static function &getMember($groupID, $useCache = TRUE) {
212 $params = array(array('group', 'IN', array($groupID => 1), 0, 0));
213 $returnProperties = array('contact_id');
214 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, $useCache);
217 foreach ($contacts as $contact) {
218 $aMembers[$contact['contact_id']] = 1;
225 * Returns array of group object(s) matching a set of one or Group properties.
227 * @param array $params
228 * Limits the set of groups returned.
229 * @param array $returnProperties
230 * Which properties should be included in the returned group objects.
231 * (member_count should be last element.)
234 * @param null $offset
235 * @param null $rowCount
237 * @return array of group objects.
240 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
241 * add in essential fields (e.g. id). This should follow a regular pattern like the others
243 static function getGroups(
245 $returnProperties = NULL,
250 $dao = new CRM_Contact_DAO_Group();
251 if (!isset($params['is_active'])) {
255 foreach ($params as $k => $v) {
256 if ($k == 'name' ||
$k == 'title') {
257 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
259 elseif ($k == 'group_type') {
260 foreach ((array) $v as $type) {
261 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
264 elseif (is_array($v)) {
265 foreach ($v as &$num) {
268 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
276 if ($offset ||
$rowCount) {
277 $offset = ($offset > 0) ?
$offset : 0;
278 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
279 $dao->limit($offset, $rowCount);
283 $dao->orderBy($sort);
286 // return only specific fields if returnproperties are sent
287 if (!empty($returnProperties)) {
289 $dao->selectAdd(implode(',', $returnProperties));
293 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
296 while ($dao->fetch()) {
297 $group = new CRM_Contact_DAO_Group();
299 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
301 $groups[] = clone($dao);
307 * Make sure that the user has permission to access this group
310 * The id of the object.
312 * @return string the permission that the user has (or null)
315 public static function checkPermission($id) {
316 $allGroups = CRM_Core_PseudoConstant
::allGroup();
319 if (CRM_Core_Permission
::check('edit all contacts') ||
320 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
321 'civicrm_saved_search', $allGroups
324 $permissions[] = CRM_Core_Permission
::EDIT
;
327 if (CRM_Core_Permission
::check('view all contacts') ||
328 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
329 'civicrm_saved_search', $allGroups
332 $permissions[] = CRM_Core_Permission
::VIEW
;
335 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
336 // Note: using !empty() in if condition, restricts the scope of delete
337 // permission to groups/contacts that are editable/viewable.
338 // We can remove this !empty condition once we have ACL support for delete functionality.
339 $permissions[] = CRM_Core_Permission
::DELETE
;
348 * @param array $params
349 * Associative array of parameters.
351 * @return object|null The new group BAO (if created)
354 public static function &create(&$params) {
356 if (!empty($params['id'])) {
357 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
360 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
363 // form the name only if missing: CRM-627
364 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
365 if (!$nameParam && empty($params['id'])) {
366 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
369 // convert params if array type
370 if (isset($params['group_type'])) {
371 if (is_array($params['group_type'])) {
372 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
373 array_keys($params['group_type'])
374 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
378 $params['group_type'] = '';
381 $session = CRM_Core_Session
::singleton( );
382 $cid = $session->get('userID');
383 // this action is add
384 if ($cid && empty($params['id'])) {
385 $params['created_id'] = $cid;
387 // this action is update
388 if ($cid && !empty($params['id'])) {
389 $params['modified_id'] = $cid;
392 $group = new CRM_Contact_BAO_Group();
393 $group->copyValues($params);
394 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
395 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
396 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
397 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
398 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
399 if (isset($group->parents
) && is_array($group->parents
)) {
400 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
401 array_keys($group->parents
)
402 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
404 if (empty($params['id']) &&
407 $group->name
.= "_tmp";
415 if (empty($params['id']) &&
418 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
421 $group->buildClause();
424 // add custom field values
425 if (!empty($params['custom'])) {
426 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
429 // make the group, child of domain/site group by default.
430 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
431 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
432 if (empty($params['parents']) &&
433 $domainGroupID != $group->id
&&
434 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
437 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
439 // if no parent present and the group doesn't already have any parents,
440 // make sure site group goes as parent
441 $params['parents'] = array($domainGroupID => 1);
443 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
444 $params['parents'] = array($params['parents'] => 1);
447 if (!empty($params['parents'])) {
448 foreach ($params['parents'] as $parentId => $dnc) {
449 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
450 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
455 // clear any descendant groups cache if exists
456 $finalGroups = CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
458 // this is always required, since we don't know when a
459 // parent group is removed
460 CRM_Contact_BAO_GroupNestingCache
::update();
462 // update group contact cache for all parent groups
463 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
464 foreach ($parentIds as $parentId) {
465 CRM_Contact_BAO_GroupContactCache
::add($parentId);
469 if (!empty($params['organization_id'])) {
472 $groupOrg['group_id'] = $group->id
;
473 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
476 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
478 if (!empty($params['id'])) {
479 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
482 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
485 $recentOther = array();
486 if (CRM_Core_Permission
::check('edit groups')) {
487 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
488 // currently same permission we are using for delete a group
489 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
492 // add the recently added group (unless hidden: CRM-6432)
493 if (!$group->is_hidden
) {
494 CRM_Utils_Recent
::add($group->title
,
495 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
507 * Given a saved search compute the clause and the tables
508 * and store it for future use
510 public function buildClause() {
511 $params = array(array('group', 'IN', array($this->id
=> 1), 0, 0));
513 if (!empty($params)) {
514 $tables = $whereTables = array();
515 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
516 if (!empty($tables)) {
517 $this->select_tables
= serialize($tables);
519 if (!empty($whereTables)) {
520 $this->where_tables
= serialize($whereTables);
528 * Defines a new smart group
530 * @param array $params
531 * Associative array of parameters.
533 * @return object|null The new group BAO (if created)
536 public static function createSmartGroup(&$params) {
537 if (!empty($params['formValues'])) {
539 unset($ssParams['id']);
540 if (isset($ssParams['saved_search_id'])) {
541 $ssParams['id'] = $ssParams['saved_search_id'];
544 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
546 $params['saved_search_id'] = $savedSearch->id
;
552 return self
::create($params);
556 * Update the is_active flag in the db
559 * Id of the database record.
560 * @param bool $isActive
561 * Value we want to set the is_active field.
563 * @return Object DAO object on sucess, null otherwise
566 public static function setIsActive($id, $isActive) {
567 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
571 * Build the condition to retrieve groups.
573 * @param string $groupType
574 * Type of group(Access/Mailing) OR the key of the group.
575 * @param bool|\boolen $excludeHidden exclude hidden groups.
577 * @return string $condition
580 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
582 if ($groupType == 'Mailing') {
583 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
585 elseif ($groupType == 'Access') {
586 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
588 elseif (!empty($groupType)){
589 // ie we have been given the group key
590 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
594 if ($excludeHidden) {
595 $condition = "is_hidden = 0";
600 $condition .= " AND group_type LIKE '%$value%'";
603 $condition = "group_type LIKE '%$value%'";
611 * Get permission relevant clauses
618 public static function getPermissionClause($force = FALSE) {
620 static $retrieved = FALSE;
621 if ((!$retrieved ||
$force ) && !CRM_Core_Permission
::check('view all contacts') && !CRM_Core_Permission
::check('edit all contacts')) {
622 //get the allowed groups for the current user
623 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
624 if (!empty($groups)) {
625 $groupList = implode(', ', array_values($groups));
626 $clause = "groups.id IN ( $groupList ) ";
639 public function __toString() {
644 * This function create the hidden smart group when user perform
645 * contact seach and want to send mailing to search contacts.
647 * @param array $params
648 * ( reference ) an assoc array of name/value pairs.
650 * @return array ( smartGroupId, ssId ) smart group id and saved search id
653 public static function createHiddenSmartGroup($params) {
654 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
656 //add mapping record only for search builder saved search
658 if ($params['search_context'] == 'builder') {
659 //save the mapping for search builder
661 //save record in mapping table
663 $mappingParams = array('mapping_type' => 'Search Builder');
664 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams, $temp);
665 $mappingId = $mapping->id
;
668 //get the mapping id from saved search
669 $savedSearch = new CRM_Contact_BAO_SavedSearch();
670 $savedSearch->id
= $ssId;
671 $savedSearch->find(TRUE);
672 $mappingId = $savedSearch->mapping_id
;
675 //save mapping fields
676 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
679 //create/update saved search record.
680 $savedSearch = new CRM_Contact_BAO_SavedSearch();
681 $savedSearch->id
= $ssId;
682 $savedSearch->form_values
= serialize($params['form_values']);
683 $savedSearch->mapping_id
= $mappingId;
684 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
685 $savedSearch->save();
687 $ssId = $savedSearch->id
;
692 $smartGroupId = NULL;
693 if (!empty($params['saved_search_id'])) {
694 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
697 //create group only when new saved search.
698 $groupParams = array(
699 'title' => "Hidden Smart Group {$ssId}",
700 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
701 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
702 'group_type' => CRM_Utils_Array
::value('group_type', $params),
703 'visibility' => CRM_Utils_Array
::value('visibility', $params),
704 'saved_search_id' => $ssId,
707 $smartGroup = self
::create($groupParams);
708 $smartGroupId = $smartGroup->id
;
711 return array($smartGroupId, $ssId);
715 * This function is a wrapper for ajax group selector
717 * @param array $params
718 * Associated array for params record id.
720 * @return array $groupList associated array of group list
723 * @todo there seems little reason for the small number of functions that call this to pass in
724 * params that then need to be translated in this function since they are coding them when calling
726 static public function getGroupListSelector(&$params) {
728 $params['offset'] = ($params['page'] - 1) * $params['rp'];
729 $params['rowCount'] = $params['rp'];
730 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
733 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
735 //skip total if we are making call to show only children
736 if (empty($params['parent_id'])) {
738 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
740 // get all the groups
741 $allGroups = CRM_Core_PseudoConstant
::allGroup();
744 // format params and add links
745 $groupList = array();
746 if (!empty($groups)) {
747 foreach ($groups as $id => $value) {
748 $groupList[$id]['group_id'] = $value['id'];
749 $groupList[$id]['count'] = $value['count'];
750 $groupList[$id]['group_name'] = $value['title'];
752 // append parent names if in search mode
753 if (empty($params['parent_id']) && !empty($value['parents'])) {
754 $groupIds = explode(',', $value['parents']);
756 foreach ($groupIds as $gId) {
757 $title[] = $allGroups[$gId];
759 $groupList[$id]['group_name'] .= '<div class="crm-row-parent-name"><em>'.ts('Child of').'</em>: ' . implode(', ', $title) . '</div>';
760 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
762 $value['class'][] = 'crm-entity';
763 $groupList[$id]['class'] = $value['id'] . ',' . implode(' ', $value['class']);
765 $groupList[$id]['group_description'] = CRM_Utils_Array
::value('description', $value);
766 if (!empty($value['group_type'])) {
767 $groupList[$id]['group_type'] = $value['group_type'];
770 $groupList[$id]['group_type'] = '';
772 $groupList[$id]['visibility'] = $value['visibility'];
773 $groupList[$id]['links'] = $value['action'];
774 $groupList[$id]['org_info'] = CRM_Utils_Array
::value('org_info', $value);
775 $groupList[$id]['created_by'] = CRM_Utils_Array
::value('created_by', $value);
777 $groupList[$id]['is_parent'] = $value['is_parent'];
784 * This function to get list of groups
786 * @param array $params
787 * Associated array for params.
791 public static function getGroupList(&$params) {
792 $config = CRM_Core_Config
::singleton();
794 $whereClause = self
::whereClause($params, FALSE);
796 //$this->pagerAToZ( $whereClause, $params );
798 if (!empty($params['rowCount']) &&
799 $params['rowCount'] > 0
801 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
804 $orderBy = ' ORDER BY groups.title asc';
805 if (!empty($params['sort'])) {
806 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
809 $select = $from = $where = "";
811 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
812 CRM_Core_Permission
::isMultisiteEnabled()
814 $select = ", contact.display_name as org_name, contact.id as org_id";
815 $from = " LEFT JOIN civicrm_group_organization gOrg
816 ON gOrg.group_id = groups.id
817 LEFT JOIN civicrm_contact contact
818 ON contact.id = gOrg.organization_id ";
820 //get the Organization ID
821 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
823 $where = " AND gOrg.organization_id = {$orgID}";
830 SELECT groups.*, createdBy.sort_name as created_by {$select}
831 FROM civicrm_group groups
832 LEFT JOIN civicrm_contact createdBy
833 ON createdBy.id = groups.created_id
835 WHERE $whereClause {$where}
840 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
842 //FIXME CRM-4418, now we are handling delete separately
843 //if we introduce 'delete for group' make sure to handle here.
844 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
845 if (CRM_Core_Permission
::check('edit groups')) {
846 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
847 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
851 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
853 $links = self
::actionLinks();
855 $allTypes = CRM_Core_OptionGroup
::values('group_type');
856 $values = $groupsToCount = array();
858 $visibility = CRM_Core_SelectValues
::ufVisibility();
860 while ($object->fetch()) {
861 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
862 //@todo CRM-12209 introduced an ACL check in the whereClause function
863 // it may be that this checking is now obsolete - or that what remains
864 // should be removed to the whereClause (which is also accessed by getCount)
868 $values[$object->id
] = array(
872 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
873 if ($object->saved_search_id
) {
874 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
875 // check if custom search, if so fix view link
876 $customSearchID = CRM_Core_DAO
::getFieldValue(
877 'CRM_Contact_DAO_SavedSearch',
878 $object->saved_search_id
,
882 if ($customSearchID) {
883 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
884 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
888 $action = array_sum(array_keys($newLinks));
891 if (array_key_exists('is_reserved', $object)) {
892 //if group is reserved and I don't have reserved permission, suppress delete/edit
893 if ($object->is_reserved
&& !$reservedPermission) {
894 $action -= CRM_Core_Action
::DELETE
;
895 $action -= CRM_Core_Action
::UPDATE
;
896 $action -= CRM_Core_Action
::DISABLE
;
900 if (array_key_exists('is_active', $object)) {
901 if ($object->is_active
) {
902 $action -= CRM_Core_Action
::ENABLE
;
905 $values[$object->id
]['class'][] = 'disabled';
906 $action -= CRM_Core_Action
::VIEW
;
907 $action -= CRM_Core_Action
::DISABLE
;
911 $action = $action & CRM_Core_Action
::mask($groupPermissions);
913 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
915 $groupsToCount[$object->saved_search_id ?
'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id
;
917 if (isset($values[$object->id
]['group_type'])) {
918 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
919 substr($values[$object->id
]['group_type'], 1, -1)
922 foreach ($groupTypes as $type) {
923 $types[] = CRM_Utils_Array
::value($type, $allTypes);
925 $values[$object->id
]['group_type'] = implode(', ', $types);
927 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
931 'ssid' => $object->saved_search_id
,
935 'group.selector.row',
940 // If group has children, add class for link to view children
941 $values[$object->id
]['is_parent'] = false;
942 if (array_key_exists('children', $values[$object->id
])) {
943 $values[$object->id
]['class'][] = "crm-group-parent";
944 $values[$object->id
]['is_parent'] = true;
947 // If group is a child, add child class
948 if (array_key_exists('parents', $values[$object->id
])) {
949 $values[$object->id
]['class'][] = "crm-group-child";
953 if ($object->org_id
) {
954 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
955 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
958 $values[$object->id
]['org_info'] = ''; // Empty cell
962 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
964 if ($object->created_id
) {
965 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
966 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
972 foreach ($groupsToCount as $table => $groups) {
973 $where = "group_id IN (" . implode(',', $groups) . ")";
974 if ($table == 'civicrm_group_contact') {
975 $where .= " AND status = 'Added'";
977 $dao = CRM_Core_DAO
::executeQuery("SELECT group_id, COUNT(id) as `count` FROM $table WHERE $where GROUP BY group_id");
978 while ($dao->fetch()) {
979 $values[$dao->group_id
]['count'] = $dao->count
;
987 * This function to get hierarchical list of groups (parent followed by children)
989 * @param array $groupIDs
990 * Array of group ids.
992 * @param null $parents
993 * @param string $spacer
994 * @param bool $titleOnly
998 static function getGroupsHierarchy(
1001 $spacer = '<span class="child-indent"></span>',
1004 if (empty($groupIDs)) {
1008 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1009 // <span class="child-icon"></span>
1010 // need to return id, title (w/ spacer), description, visibility
1012 // We need to build a list of tags ordered by hierarchy and sorted by
1013 // name. The heirarchy will be communicated by an accumulation of
1014 // separators in front of the name to give it a visual offset.
1015 // Instead of recursively making mysql queries, we'll make one big
1016 // query and build the heirarchy with the algorithm below.
1018 $args = array(1 => array($groupIdString, 'String'));
1020 SELECT id, title, description, visibility, parents
1022 WHERE id IN $groupIdString
1025 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1026 $parentArray = explode(',', $parents);
1027 $parent = $parentArray[0];
1028 $args[2] = array($parent, 'Integer');
1029 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1031 $query .= " ORDER BY title";
1032 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1034 // Sort the groups into the correct storage by the parent
1035 // $roots represent the current leaf nodes that need to be checked for
1036 // children. $rows represent the unplaced nodes
1037 $roots = $rows = $allGroups = array();
1038 while ($dao->fetch()) {
1039 $allGroups[$dao->id
] = array(
1040 'title' => $dao->title
,
1041 'visibility' => $dao->visibility
,
1042 'description' => $dao->description
1045 if ($dao->parents
== $parents) {
1049 'title' => $dao->title
1053 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1054 $parentArray = explode(',', $dao->parents
);
1055 $parent = $parentArray[0];
1059 'title' => $dao->title
,
1060 'parents' => $parent
1065 // While we have nodes left to build, shift the first (alphabetically)
1066 // node of the list, place it in our groups list and loop through the
1067 // list of unplaced nodes to find its children. We make a copy to
1068 // iterate through because we must modify the unplaced nodes list
1070 while (count($roots)) {
1071 $new_roots = array();
1072 $current_rows = $rows;
1073 $root = array_shift($roots);
1074 $groups[$root['id']] = array($root['prefix'], $root['title']);
1076 // As you find the children, append them to the end of the new set
1077 // of roots (maintain alphabetical ordering). Also remove the node
1078 // from the set of unplaced nodes.
1079 if (is_array($current_rows)) {
1080 foreach ($current_rows as $key => $row) {
1081 if ($row['parents'] == $root['id']) {
1082 $new_roots[] = array(
1084 'prefix' => $groups[$root['id']][0] . $spacer,
1085 'title' => $row['title']
1092 //As a group, insert the new roots into the beginning of the roots
1093 //list. This maintains the hierarchical ordering of the tags.
1094 $roots = array_merge($new_roots, $roots);
1097 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1098 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1099 foreach ($rows as $value) {
1100 $groups[$value['id']] = array($value['prefix'], $value['title']);
1102 // Prefix titles with the calcuated spacing to give the visual
1103 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1104 $groupsReturn = array();
1105 foreach ($groups as $key => $value) {
1107 $groupsReturn[$key] = $value[0] . $value[1];
1110 $groupsReturn[$key] = array(
1111 'title' => $value[0] . $value[1],
1112 'description' => $allGroups[$key]['description'],
1113 'visibility' => $allGroups[$key]['visibility'],
1118 return $groupsReturn;
1122 * @param array $params
1124 * @return null|string
1126 public static function getGroupCount(&$params) {
1127 $whereClause = self
::whereClause($params, FALSE);
1128 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1130 if (!empty($params['created_by'])) {
1132 INNER JOIN civicrm_contact createdBy
1133 ON createdBy.id = groups.created_id";
1136 WHERE {$whereClause}";
1137 return CRM_Core_DAO
::singleValueQuery($query, $params);
1141 * Generate permissioned where clause for group search
1142 * @param array $params
1143 * @param bool $sortBy
1144 * @param bool $excludeHidden
1148 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1150 $title = CRM_Utils_Array
::value('title', $params);
1152 $clauses[] = "groups.title LIKE %1";
1153 if (strpos($title, '%') !== FALSE) {
1154 $params[1] = array($title, 'String', FALSE);
1157 $params[1] = array($title, 'String', TRUE);
1161 $groupType = CRM_Utils_Array
::value('group_type', $params);
1163 $types = explode(',', $groupType);
1164 if (!empty($types)) {
1165 $clauses[] = 'groups.group_type LIKE %2';
1166 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1167 $params[2] = array($typeString, 'String', TRUE);
1171 $visibility = CRM_Utils_Array
::value('visibility', $params);
1173 $clauses[] = 'groups.visibility = %3';
1174 $params[3] = array($visibility, 'String');
1177 $groupStatus = CRM_Utils_Array
::value('status', $params);
1179 switch ($groupStatus) {
1181 $clauses[] = 'groups.is_active = 1';
1182 $params[4] = array($groupStatus, 'Integer');
1186 $clauses[] = 'groups.is_active = 0';
1187 $params[4] = array($groupStatus, 'Integer');
1191 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1196 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1198 $clauses[] = 'groups.parents IS NULL';
1201 // only show child groups of a specific parent group
1202 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1204 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1205 $params[5] = array($parent_id, 'Integer');
1208 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1209 $clauses[] = "createdBy.sort_name LIKE %6";
1210 if (strpos($createdBy, '%') !== FALSE) {
1211 $params[6] = array($createdBy, 'String', FALSE);
1214 $params[6] = array($createdBy, 'String', TRUE);
1218 if (empty($clauses)) {
1219 $clauses[] = 'groups.is_active = 1';
1222 if ($excludeHidden) {
1223 $clauses[] = 'groups.is_hidden = 0';
1226 $clauses[] = self
::getPermissionClause();
1229 return implode(' AND ', $clauses);
1233 * Define action links
1235 * @return array $links array of action links
1237 public static function actionLinks() {
1239 CRM_Core_Action
::VIEW
=> array(
1240 'name' => ts('Contacts'),
1241 'url' => 'civicrm/group/search',
1242 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1243 'title' => ts('Group Contacts'),
1245 CRM_Core_Action
::UPDATE
=> array(
1246 'name' => ts('Settings'),
1247 'url' => 'civicrm/group',
1248 'qs' => 'reset=1&action=update&id=%%id%%',
1249 'title' => ts('Edit Group'),
1251 CRM_Core_Action
::DISABLE
=> array(
1252 'name' => ts('Disable'),
1253 'ref' => 'crm-enable-disable',
1254 'title' => ts('Disable Group'),
1256 CRM_Core_Action
::ENABLE
=> array(
1257 'name' => ts('Enable'),
1258 'ref' => 'crm-enable-disable',
1259 'title' => ts('Enable Group'),
1261 CRM_Core_Action
::DELETE
=> array(
1262 'name' => ts('Delete'),
1263 'url' => 'civicrm/group',
1264 'qs' => 'reset=1&action=delete&id=%%id%%',
1265 'title' => ts('Delete Group'),
1273 * @param $whereClause
1274 * @param array $whereParams
1278 public function pagerAtoZ($whereClause, $whereParams) {
1280 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1281 FROM civicrm_group groups
1283 ORDER BY LEFT(groups.title, 1)
1285 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1287 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);