3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 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 (reference ) an assoc array of name/value pairs
52 * @param array $defaults (reference ) an assoc array to hold the flattened values
54 * @return object CRM_Contact_BAO_Group object
58 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 * Function to delete the group and all the object that connect to
71 * this group. Incredibly destructive
73 * @param int $id group id
80 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
,
123 // clear any descendant groups cache if exists
124 CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
127 // delete from group table
128 $group = new CRM_Contact_DAO_Group();
132 $transaction->commit();
134 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
136 // delete the recently created Group
137 $groupRecent = array(
141 CRM_Utils_Recent
::del($groupRecent);
145 * Returns an array of the contacts in the given group.
148 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
157 * @param int $id group id
158 * @param enum|string $status status of members in group
160 * @param bool $countChildGroups
162 * @return int count of members in the group with above status
165 static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
166 $groupContact = new CRM_Contact_DAO_GroupContact();
167 $groupIds = array($id);
168 if ($countChildGroups) {
169 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
173 $contacts = self
::getGroupContacts($id);
175 foreach ($groupIds as $groupId) {
177 $groupContacts = self
::getGroupContacts($groupId);
178 foreach ($groupContacts as $gcontact) {
179 if ($groupId != $id) {
180 // Loop through main group's contacts
181 // and subtract from the count for each contact which
182 // matches one in the present group, if it is not the
184 foreach ($contacts as $contact) {
185 if ($contact['contact_id'] == $gcontact['contact_id']) {
191 $groupContact->group_id
= $groupId;
192 if (isset($status)) {
193 $groupContact->status
= $status;
195 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
196 $count +
= $groupContact->count();
202 * Get the list of member for a group id
205 * @param bool $useCache
207 * @internal param int $lngGroupId this is group id
209 * @return array $aMembers this arrray contains the list of members for this group id
213 static function &getMember($groupID, $useCache = TRUE) {
214 $params = array(array('group', 'IN', array($groupID => 1), 0, 0));
215 $returnProperties = array('contact_id');
216 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, $useCache);
219 foreach ($contacts as $contact) {
220 $aMembers[$contact['contact_id']] = 1;
227 * Returns array of group object(s) matching a set of one or Group properties.
229 * @param null $params
230 * @param array $returnProperties 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 * @internal param array $param Array of one or more valid property_name=>value pairs.
238 * Limits the set of groups returned.
239 * @return An array of group objects.
243 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
244 * add in essential fields (e.g. id). This should follow a regular pattern like the others
246 static function getGroups(
248 $returnProperties = NULL,
253 $dao = new CRM_Contact_DAO_Group();
254 if (!isset($params['is_active'])) {
258 foreach ($params as $k => $v) {
259 if ($k == 'name' ||
$k == 'title') {
260 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
262 elseif ($k == 'group_type') {
263 foreach ((array) $v as $type) {
264 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
267 elseif (is_array($v)) {
268 foreach ($v as &$num) {
271 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
279 if ($offset ||
$rowCount) {
280 $offset = ($offset > 0) ?
$offset : 0;
281 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
282 $dao->limit($offset, $rowCount);
286 $dao->orderBy($sort);
289 // return only specific fields if returnproperties are sent
290 if (!empty($returnProperties)) {
292 $dao->selectAdd(implode(',', $returnProperties));
296 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
299 while ($dao->fetch()) {
300 $group = new CRM_Contact_DAO_Group();
302 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
304 $groups[] = clone($dao);
310 * make sure that the user has permission to access this group
312 * @param int $id the id of the object
314 * @return string the permission that the user has (or null)
318 static function checkPermission($id) {
319 $allGroups = CRM_Core_PseudoConstant
::allGroup();
322 if (CRM_Core_Permission
::check('edit all contacts') ||
323 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
324 'civicrm_saved_search', $allGroups
327 $permissions[] = CRM_Core_Permission
::EDIT
;
330 if (CRM_Core_Permission
::check('view all contacts') ||
331 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
332 'civicrm_saved_search', $allGroups
335 $permissions[] = CRM_Core_Permission
::VIEW
;
338 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
339 // Note: using !empty() in if condition, restricts the scope of delete
340 // permission to groups/contacts that are editable/viewable.
341 // We can remove this !empty condition once we have ACL support for delete functionality.
342 $permissions[] = CRM_Core_Permission
::DELETE
;
351 * @param array $params Associative array of parameters
353 * @return object|null The new group BAO (if created)
357 public static function &create(&$params) {
359 if (!empty($params['id'])) {
360 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
363 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
366 // form the name only if missing: CRM-627
367 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
368 if (!$nameParam && empty($params['id'])) {
369 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
372 // convert params if array type
373 if (isset($params['group_type'])) {
374 if (is_array($params['group_type'])) {
375 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
376 array_keys($params['group_type'])
377 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
381 $params['group_type'] = '';
384 $session = CRM_Core_Session
::singleton( );
385 $cid = $session->get('userID');
386 // this action is add
387 if ($cid && empty($params['id'])) {
388 $params['created_id'] = $cid;
390 // this action is update
391 if ($cid && !empty($params['id'])) {
392 $params['modified_id'] = $cid;
395 $group = new CRM_Contact_BAO_Group();
396 $group->copyValues($params);
397 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
398 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
399 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
400 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
401 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
402 if(isset($group->parents
) && is_array($group->parents
)) {
403 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
404 array_keys($group->parents
)
405 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
407 if (empty($params['id']) &&
410 $group->name
.= "_tmp";
418 if (empty($params['id']) &&
421 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
424 $group->buildClause();
427 // add custom field values
428 if (!empty($params['custom'])) {
429 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
432 // make the group, child of domain/site group by default.
433 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
434 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
435 if (empty($params['parents']) &&
436 $domainGroupID != $group->id
&&
437 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
440 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
442 // if no parent present and the group doesn't already have any parents,
443 // make sure site group goes as parent
444 $params['parents'] = array($domainGroupID => 1);
446 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
447 $params['parents'] = array($params['parents'] => 1);
450 if (!empty($params['parents'])) {
451 foreach ($params['parents'] as $parentId => $dnc) {
452 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
453 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
458 // clear any descendant groups cache if exists
459 $finalGroups = CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
461 // this is always required, since we don't know when a
462 // parent group is removed
463 CRM_Contact_BAO_GroupNestingCache
::update();
465 // update group contact cache for all parent groups
466 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
467 foreach ($parentIds as $parentId) {
468 CRM_Contact_BAO_GroupContactCache
::add($parentId);
472 if (!empty($params['organization_id'])) {
475 $groupOrg['group_id'] = $group->id
;
476 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
479 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
481 if (!empty($params['id'])) {
482 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
485 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
488 $recentOther = array();
489 if (CRM_Core_Permission
::check('edit groups')) {
490 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
491 // currently same permission we are using for delete a group
492 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
495 // add the recently added group (unless hidden: CRM-6432)
496 if (!$group->is_hidden
) {
497 CRM_Utils_Recent
::add($group->title
,
498 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
510 * given a saved search compute the clause and the tables
511 * and store it for future use
513 function buildClause() {
514 $params = array(array('group', 'IN', array($this->id
=> 1), 0, 0));
516 if (!empty($params)) {
517 $tables = $whereTables = array();
518 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
519 if (!empty($tables)) {
520 $this->select_tables
= serialize($tables);
522 if (!empty($whereTables)) {
523 $this->where_tables
= serialize($whereTables);
531 * Defines a new smart group
533 * @param array $params Associative array of parameters
535 * @return object|null 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
561 * @param int $id id of the database record
562 * @param boolean $isActive value we want to set the is_active field
564 * @return Object DAO object on sucess, null otherwise
567 static function setIsActive($id, $isActive) {
568 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
572 * build the condition to retrieve groups.
574 * @param string $groupType type of group(Access/Mailing) OR the key of the group
575 * @param bool|\boolen $excludeHidden exclude hidden groups.
577 * @return string $condition
580 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
614 * @internal param $existingClauses
616 * @internal param $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 ( reference ) an assoc array of name/value pairs
653 * @return array ( smartGroupId, ssId ) smart group id and saved search id
657 static function createHiddenSmartGroup($params) {
658 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
660 //add mapping record only for search builder saved search
662 if ($params['search_context'] == 'builder') {
663 //save the mapping for search builder
665 //save record in mapping table
667 $mappingParams = array('mapping_type' => 'Search Builder');
668 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams, $temp);
669 $mappingId = $mapping->id
;
672 //get the mapping id from saved search
673 $savedSearch = new CRM_Contact_BAO_SavedSearch();
674 $savedSearch->id
= $ssId;
675 $savedSearch->find(TRUE);
676 $mappingId = $savedSearch->mapping_id
;
679 //save mapping fields
680 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
683 //create/update saved search record.
684 $savedSearch = new CRM_Contact_BAO_SavedSearch();
685 $savedSearch->id
= $ssId;
686 $savedSearch->form_values
= serialize($params['form_values']);
687 $savedSearch->mapping_id
= $mappingId;
688 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
689 $savedSearch->save();
691 $ssId = $savedSearch->id
;
696 $smartGroupId = NULL;
697 if (!empty($params['saved_search_id'])) {
698 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
701 //create group only when new saved search.
702 $groupParams = array(
703 'title' => "Hidden Smart Group {$ssId}",
704 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
705 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
706 'group_type' => CRM_Utils_Array
::value('group_type', $params),
707 'visibility' => CRM_Utils_Array
::value('visibility', $params),
708 'saved_search_id' => $ssId,
711 $smartGroup = self
::create($groupParams);
712 $smartGroupId = $smartGroup->id
;
715 return array($smartGroupId, $ssId);
719 * This function is a wrapper for ajax group selector
721 * @param array $params associated array for params record id.
723 * @return array $groupList associated array of group list
726 * @todo there seems little reason for the small number of functions that call this to pass in
727 * params that then need to be translated in this function since they are coding them when calling
730 static public function getGroupListSelector(&$params) {
732 $params['offset'] = ($params['page'] - 1) * $params['rp'];
733 $params['rowCount'] = $params['rp'];
734 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
737 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
739 //skip total if we are making call to show only children
740 if (empty($params['parent_id'])) {
742 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
744 // get all the groups
745 $allGroups = CRM_Core_PseudoConstant
::allGroup();
748 // format params and add links
749 $groupList = array();
750 if (!empty($groups)) {
751 foreach ($groups as $id => $value) {
752 $groupList[$id]['group_id'] = $value['id'];
753 $groupList[$id]['group_name'] = $value['title'];
754 $groupList[$id]['class'] = implode(' ', $value['class']);
756 // append parent names if in search mode
757 if (empty($params['parent_id']) && !empty($value['parents'])) {
758 $groupIds = explode(',', $value['parents']);
760 foreach($groupIds as $gId) {
761 $title[] = $allGroups[$gId];
763 $groupList[$id]['group_name'] .= '<div class="crm-row-parent-name"><em>'.ts('Child of').'</em>: ' . implode(', ', $title) . '</div>';
764 $groupList[$id]['class'] = in_array('disabled', $value['class']) ?
'disabled' : '';
767 $groupList[$id]['group_description'] = CRM_Utils_Array
::value('description', $value);
768 if (!empty($value['group_type'])) {
769 $groupList[$id]['group_type'] = $value['group_type'];
772 $groupList[$id]['group_type'] = '';
774 $groupList[$id]['visibility'] = $value['visibility'];
775 $groupList[$id]['links'] = $value['action'];
776 $groupList[$id]['org_info'] = CRM_Utils_Array
::value('org_info', $value);
777 $groupList[$id]['created_by'] = CRM_Utils_Array
::value('created_by', $value);
779 $groupList[$id]['is_parent'] = $value['is_parent'];
786 * This function to get list of groups
788 * @param array $params associated array for params
793 static function getGroupList(&$params) {
794 $config = CRM_Core_Config
::singleton();
796 $whereClause = self
::whereClause($params, FALSE);
798 //$this->pagerAToZ( $whereClause, $params );
800 if (!empty($params['rowCount']) &&
801 $params['rowCount'] > 0
803 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
806 $orderBy = ' ORDER BY groups.title asc';
807 if (!empty($params['sort'])) {
808 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
811 $select = $from = $where = "";
813 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
814 CRM_Core_Permission
::isMultisiteEnabled()
816 $select = ", contact.display_name as org_name, contact.id as org_id";
817 $from = " LEFT JOIN civicrm_group_organization gOrg
818 ON gOrg.group_id = groups.id
819 LEFT JOIN civicrm_contact contact
820 ON contact.id = gOrg.organization_id ";
822 //get the Organization ID
823 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
825 $where = " AND gOrg.organization_id = {$orgID}";
832 SELECT groups.*, createdBy.sort_name as created_by {$select}
833 FROM civicrm_group groups
834 LEFT JOIN civicrm_contact createdBy
835 ON createdBy.id = groups.created_id
837 WHERE $whereClause {$where}
841 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
843 //FIXME CRM-4418, now we are handling delete separately
844 //if we introduce 'delete for group' make sure to handle here.
845 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
846 if (CRM_Core_Permission
::check('edit groups')) {
847 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
848 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
852 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
854 $links = self
::actionLinks();
856 $allTypes = CRM_Core_OptionGroup
::values('group_type');
859 $visibility = CRM_Core_SelectValues
::ufVisibility();
861 while ($object->fetch()) {
862 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
863 //@todo CRM-12209 introduced an ACL check in the whereClause function
864 // it may be that this checking is now obsolete - or that what remains
865 // should be removed to the whereClause (which is also accessed by getCount)
869 $values[$object->id
] = array('class' => array());
870 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
871 if ($object->saved_search_id
) {
872 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
873 // check if custom search, if so fix view link
874 $customSearchID = CRM_Core_DAO
::getFieldValue(
875 'CRM_Contact_DAO_SavedSearch',
876 $object->saved_search_id
,
880 if ($customSearchID) {
881 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
882 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
886 $action = array_sum(array_keys($newLinks));
889 if (array_key_exists('is_reserved', $object)) {
890 //if group is reserved and I don't have reserved permission, suppress delete/edit
891 if ($object->is_reserved
&& !$reservedPermission) {
892 $action -= CRM_Core_Action
::DELETE
;
893 $action -= CRM_Core_Action
::UPDATE
;
894 $action -= CRM_Core_Action
::DISABLE
;
898 if (array_key_exists('is_active', $object)) {
899 if ($object->is_active
) {
900 $action -= CRM_Core_Action
::ENABLE
;
903 $values[$object->id
]['class'][] = 'disabled';
904 $action -= CRM_Core_Action
::VIEW
;
905 $action -= CRM_Core_Action
::DISABLE
;
909 $action = $action & CRM_Core_Action
::mask($groupPermissions);
911 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
913 if (isset($values[$object->id
]['group_type'])) {
914 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
915 substr($values[$object->id
]['group_type'], 1, -1)
918 foreach ($groupTypes as $type) {
919 $types[] = CRM_Utils_Array
::value($type, $allTypes);
921 $values[$object->id
]['group_type'] = implode(', ', $types);
923 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
927 'ssid' => $object->saved_search_id
,
931 'group.selector.row',
936 // If group has children, add class for link to view children
937 $values[$object->id
]['is_parent'] = false;
938 if (array_key_exists('children', $values[$object->id
])) {
939 $values[$object->id
]['class'][] = "crm-group-parent";
940 $values[$object->id
]['is_parent'] = true;
943 // If group is a child, add child class
944 if (array_key_exists('parents', $values[$object->id
])) {
945 $values[$object->id
]['class'][] = "crm-group-child";
949 if ($object->org_id
) {
950 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
951 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
954 $values[$object->id
]['org_info'] = ''; // Empty cell
958 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
960 if ($object->created_id
) {
961 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
962 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
971 * This function to get hierarchical list of groups (parent followed by children)
973 * @param array $groupIDs array of group ids
975 * @param null $parents
976 * @param string $spacer
977 * @param bool $titleOnly
982 static function getGroupsHierarchy(
985 $spacer = '<span class="child-indent"></span>',
988 if (empty($groupIDs)) {
992 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
993 // <span class="child-icon"></span>
994 // need to return id, title (w/ spacer), description, visibility
996 // We need to build a list of tags ordered by hierarchy and sorted by
997 // name. The heirarchy will be communicated by an accumulation of
998 // separators in front of the name to give it a visual offset.
999 // Instead of recursively making mysql queries, we'll make one big
1000 // query and build the heirarchy with the algorithm below.
1002 $args = array(1 => array($groupIdString, 'String'));
1004 SELECT id, title, description, visibility, parents
1006 WHERE id IN $groupIdString
1009 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1010 $parentArray = explode(',', $parents);
1011 $parent = $parentArray[0];
1012 $args[2] = array($parent, 'Integer');
1013 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1015 $query .= " ORDER BY title";
1016 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1018 // Sort the groups into the correct storage by the parent
1019 // $roots represent the current leaf nodes that need to be checked for
1020 // children. $rows represent the unplaced nodes
1021 $roots = $rows = $allGroups = array();
1022 while ($dao->fetch()) {
1023 $allGroups[$dao->id
] = array(
1024 'title' => $dao->title
,
1025 'visibility' => $dao->visibility
,
1026 'description' => $dao->description
1029 if ($dao->parents
== $parents) {
1033 'title' => $dao->title
1037 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1038 $parentArray = explode(',', $dao->parents
);
1039 $parent = $parentArray[0];
1043 'title' => $dao->title
,
1044 'parents' => $parent
1049 // While we have nodes left to build, shift the first (alphabetically)
1050 // node of the list, place it in our groups list and loop through the
1051 // list of unplaced nodes to find its children. We make a copy to
1052 // iterate through because we must modify the unplaced nodes list
1054 while (count($roots)) {
1055 $new_roots = array();
1056 $current_rows = $rows;
1057 $root = array_shift($roots);
1058 $groups[$root['id']] = array($root['prefix'], $root['title']);
1060 // As you find the children, append them to the end of the new set
1061 // of roots (maintain alphabetical ordering). Also remove the node
1062 // from the set of unplaced nodes.
1063 if (is_array($current_rows)) {
1064 foreach ($current_rows as $key => $row) {
1065 if ($row['parents'] == $root['id']) {
1066 $new_roots[] = array(
1068 'prefix' => $groups[$root['id']][0] . $spacer,
1069 'title' => $row['title']
1076 //As a group, insert the new roots into the beginning of the roots
1077 //list. This maintains the hierarchical ordering of the tags.
1078 $roots = array_merge($new_roots, $roots);
1081 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1082 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1083 foreach ($rows as $value) {
1084 $groups[$value['id']] = array($value['prefix'], $value['title']);
1086 // Prefix titles with the calcuated spacing to give the visual
1087 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1088 $groupsReturn = array();
1089 foreach ($groups as $key => $value) {
1091 $groupsReturn[$key] = $value[0] . $value[1];
1094 $groupsReturn[$key] = array(
1095 'title' => $value[0] . $value[1],
1096 'description' => $allGroups[$key]['description'],
1097 'visibility' => $allGroups[$key]['visibility'],
1102 return $groupsReturn;
1108 * @return null|string
1110 static function getGroupCount(&$params) {
1111 $whereClause = self
::whereClause($params, FALSE);
1112 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1114 if (!empty($params['created_by'])) {
1116 INNER JOIN civicrm_contact createdBy
1117 ON createdBy.id = groups.created_id";
1120 WHERE {$whereClause}";
1121 return CRM_Core_DAO
::singleValueQuery($query, $params);
1125 * Generate permissioned where clause for group search
1127 * @param bool $sortBy
1128 * @param bool $excludeHidden
1132 static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1134 $title = CRM_Utils_Array
::value('title', $params);
1136 $clauses[] = "groups.title LIKE %1";
1137 if (strpos($title, '%') !== FALSE) {
1138 $params[1] = array($title, 'String', FALSE);
1141 $params[1] = array($title, 'String', TRUE);
1145 $groupType = CRM_Utils_Array
::value('group_type', $params);
1147 $types = explode(',', $groupType);
1148 if (!empty($types)) {
1149 $clauses[] = 'groups.group_type LIKE %2';
1150 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1151 $params[2] = array($typeString, 'String', TRUE);
1155 $visibility = CRM_Utils_Array
::value('visibility', $params);
1157 $clauses[] = 'groups.visibility = %3';
1158 $params[3] = array($visibility, 'String');
1161 $groupStatus = CRM_Utils_Array
::value('status', $params);
1163 switch ($groupStatus) {
1165 $clauses[] = 'groups.is_active = 1';
1166 $params[4] = array($groupStatus, 'Integer');
1170 $clauses[] = 'groups.is_active = 0';
1171 $params[4] = array($groupStatus, 'Integer');
1175 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1180 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1182 $clauses[] = 'groups.parents IS NULL';
1185 // only show child groups of a specific parent group
1186 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1188 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1189 $params[5] = array($parent_id, 'Integer');
1192 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1193 $clauses[] = "createdBy.sort_name LIKE %6";
1194 if (strpos($createdBy, '%') !== FALSE) {
1195 $params[6] = array($createdBy, 'String', FALSE);
1198 $params[6] = array($createdBy, 'String', TRUE);
1202 if (empty($clauses)) {
1203 $clauses[] = 'groups.is_active = 1';
1206 if ($excludeHidden) {
1207 $clauses[] = 'groups.is_hidden = 0';
1210 $clauses[] = self
::getPermissionClause();
1213 return implode(' AND ', $clauses);
1217 * Function to define action links
1219 * @return array $links array of action links
1222 static function actionLinks() {
1224 CRM_Core_Action
::VIEW
=> array(
1225 'name' => ts('Contacts'),
1226 'url' => 'civicrm/group/search',
1227 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1228 'title' => ts('Group Contacts'),
1230 CRM_Core_Action
::UPDATE
=> array(
1231 'name' => ts('Settings'),
1232 'url' => 'civicrm/group',
1233 'qs' => 'reset=1&action=update&id=%%id%%',
1234 'title' => ts('Edit Group'),
1236 CRM_Core_Action
::DISABLE
=> array(
1237 'name' => ts('Disable'),
1238 'ref' => 'crm-enable-disable',
1239 'title' => ts('Disable Group'),
1241 CRM_Core_Action
::ENABLE
=> array(
1242 'name' => ts('Enable'),
1243 'ref' => 'crm-enable-disable',
1244 'title' => ts('Enable Group'),
1246 CRM_Core_Action
::DELETE
=> array(
1247 'name' => ts('Delete'),
1248 'url' => 'civicrm/group',
1249 'qs' => 'reset=1&action=delete&id=%%id%%',
1250 'title' => ts('Delete Group'),
1258 * @param $whereClause
1259 * @param $whereParams
1263 function pagerAtoZ($whereClause, $whereParams) {
1265 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1266 FROM civicrm_group groups
1268 ORDER BY LEFT(groups.title, 1)
1270 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1272 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);