3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2016
33 class CRM_Contact_BAO_Group
extends CRM_Contact_DAO_Group
{
38 public function __construct() {
39 parent
::__construct();
43 * Retrieve DB object based on input parameters.
45 * It also stores all the retrieved values in the default array.
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
49 * @param array $defaults
50 * (reference ) an assoc array to hold the flattened values.
52 * @return CRM_Contact_BAO_Group
54 public static function retrieve(&$params, &$defaults) {
55 $group = new CRM_Contact_DAO_Group();
56 $group->copyValues($params);
57 if ($group->find(TRUE)) {
58 CRM_Core_DAO
::storeValues($group, $defaults);
64 * Delete the group and all the object that connect to this group.
66 * Incredibly destructive.
68 * @param int $id Group id.
70 public static function discard($id) {
71 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
73 $transaction = new CRM_Core_Transaction();
75 // added for CRM-1631 and CRM-1794
76 // delete all subscribed mails with the selected group id
77 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
78 $subscribe->group_id
= $id;
81 // delete all Subscription records with the selected group id
82 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
83 $subHistory->group_id
= $id;
84 $subHistory->delete();
86 // delete all crm_group_contact records with the selected group id
87 $groupContact = new CRM_Contact_DAO_GroupContact();
88 $groupContact->group_id
= $id;
89 $groupContact->delete();
91 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
92 $params = array(1 => array($id, 'Integer'));
93 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
94 CRM_Core_DAO
::executeQuery($query, $params);
96 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
97 CRM_Core_DAO
::executeQuery($query, $params);
99 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
101 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
102 CRM_Core_DAO
::executeQuery($query, $params);
104 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
105 CRM_Core_DAO
::executeQuery($query, $params);
107 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
108 CRM_Core_DAO
::executeQuery($query, $params);
110 // delete from group table
111 $group = new CRM_Contact_DAO_Group();
115 $transaction->commit();
117 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
119 // delete the recently created Group
120 $groupRecent = array(
124 CRM_Utils_Recent
::del($groupRecent);
128 * Returns an array of the contacts in the given group.
132 public static function getGroupContacts($id) {
133 $params = array(array('group', 'IN', array($id => 1), 0, 0));
134 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
139 * Get the count of a members in a group with the specific status.
143 * @param string $status
144 * status of members in group
145 * @param bool $countChildGroups
148 * count of members in the group with above status
150 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
151 $groupContact = new CRM_Contact_DAO_GroupContact();
152 $groupIds = array($id);
153 if ($countChildGroups) {
154 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
158 $contacts = self
::getGroupContacts($id);
160 foreach ($groupIds as $groupId) {
162 $groupContacts = self
::getGroupContacts($groupId);
163 foreach ($groupContacts as $gcontact) {
164 if ($groupId != $id) {
165 // Loop through main group's contacts
166 // and subtract from the count for each contact which
167 // matches one in the present group, if it is not the
169 foreach ($contacts as $contact) {
170 if ($contact['contact_id'] == $gcontact['contact_id']) {
176 $groupContact->group_id
= $groupId;
177 if (isset($status)) {
178 $groupContact->status
= $status;
180 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
181 $count +
= $groupContact->count();
187 * Get the list of member for a group id.
189 * @param int $groupID
190 * @param bool $useCache
192 * Number to limit to (or 0 for unlimited).
195 * this array contains the list of members for this group id
197 public static function getMember($groupID, $useCache = TRUE, $limit = 0) {
198 $params = array(array('group', '=', $groupID, 0, 0));
199 $returnProperties = array('contact_id');
200 list($contacts) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache);
203 foreach ($contacts as $contact) {
204 $aMembers[$contact['contact_id']] = 1;
211 * Returns array of group object(s) matching a set of one or Group properties.
213 * @param array $params
214 * Limits the set of groups returned.
215 * @param array $returnProperties
216 * Which properties should be included in the returned group objects.
217 * (member_count should be last element.)
218 * @param string $sort
220 * @param int $rowCount
223 * Array of group objects.
226 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
227 * add in essential fields (e.g. id). This should follow a regular pattern like the others
229 public static function getGroups(
231 $returnProperties = NULL,
236 $dao = new CRM_Contact_DAO_Group();
237 if (!isset($params['is_active'])) {
241 foreach ($params as $k => $v) {
242 if ($k == 'name' ||
$k == 'title') {
243 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
245 elseif ($k == 'group_type') {
246 foreach ((array) $v as $type) {
247 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
250 elseif (is_array($v)) {
251 foreach ($v as &$num) {
254 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
262 if ($offset ||
$rowCount) {
263 $offset = ($offset > 0) ?
$offset : 0;
264 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
265 $dao->limit($offset, $rowCount);
269 $dao->orderBy($sort);
272 // return only specific fields if returnproperties are sent
273 if (!empty($returnProperties)) {
275 $dao->selectAdd(implode(',', $returnProperties));
279 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
282 while ($dao->fetch()) {
283 $group = new CRM_Contact_DAO_Group();
285 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
287 $groups[] = clone($dao);
293 * Make sure that the user has permission to access this group.
296 * The id of the object.
297 * @param bool $excludeHidden
298 * Should hidden groups be excluded.
299 * Logically this is the wrong place to filter hidden groups out as that is
300 * not a permission issue. However, as other functions may rely on that defaulting to
301 * FALSE for now & only the api call is calling with true.
304 * The permission that the user has (or NULL)
306 public static function checkPermission($id, $excludeHidden = FALSE) {
307 $allGroups = CRM_Core_PseudoConstant
::allGroup(NULL, $excludeHidden);
310 if (CRM_Core_Permission
::check('edit all contacts') ||
311 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
312 'civicrm_saved_search', $allGroups
315 $permissions[] = CRM_Core_Permission
::EDIT
;
318 if (CRM_Core_Permission
::check('view all contacts') ||
319 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
320 'civicrm_saved_search', $allGroups
323 $permissions[] = CRM_Core_Permission
::VIEW
;
326 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
327 // Note: using !empty() in if condition, restricts the scope of delete
328 // permission to groups/contacts that are editable/viewable.
329 // We can remove this !empty condition once we have ACL support for delete functionality.
330 $permissions[] = CRM_Core_Permission
::DELETE
;
337 * Create a new group.
339 * @param array $params
341 * @return CRM_Contact_BAO_Group|NULL
342 * The new group BAO (if created)
344 public static function create(&$params) {
346 if (!empty($params['id'])) {
347 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
350 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
353 // form the name only if missing: CRM-627
354 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
355 if (!$nameParam && empty($params['id'])) {
356 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
359 // convert params if array type
360 if (isset($params['group_type'])) {
361 if (is_array($params['group_type'])) {
362 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
363 $params['group_type']
364 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
367 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $params['group_type'] . CRM_Core_DAO
::VALUE_SEPARATOR
;
371 $params['group_type'] = NULL;
374 $session = CRM_Core_Session
::singleton();
375 $cid = $session->get('userID');
376 // this action is add
377 if ($cid && empty($params['id'])) {
378 $params['created_id'] = $cid;
380 // this action is update
381 if ($cid && !empty($params['id'])) {
382 $params['modified_id'] = $cid;
386 // Validate parents parameter when creating group.
387 if (isset($params['parents'])) {
388 if (is_array($params['parents'])) {
389 foreach ($params['parents'] as $parent => $dc) {
390 if (!CRM_Utils_Type
::validate($parent, 'Integer', FALSE)) {
391 unset($params['parents'][$parent]);
396 if (!CRM_Utils_Type
::validate($params['parents'], 'Integer', FALSE)) {
397 unset($params['parents']);
401 $group = new CRM_Contact_BAO_Group();
402 $group->copyValues($params);
403 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
404 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
405 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
406 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
407 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
408 if (isset($group->parents
) && is_array($group->parents
)) {
409 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
410 array_keys($group->parents
)
411 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
413 if (empty($params['id']) &&
416 $group->name
.= "_tmp";
424 if (empty($params['id']) &&
427 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
430 $group->buildClause();
433 // add custom field values
434 if (!empty($params['custom'])) {
435 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
438 // make the group, child of domain/site group by default.
439 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
440 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
441 if (empty($params['parents']) &&
442 $domainGroupID != $group->id
&&
443 Civi
::settings()->get('is_enabled') &&
444 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
446 // if no parent present and the group doesn't already have any parents,
447 // make sure site group goes as parent
448 $params['parents'] = array($domainGroupID => 1);
450 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
451 $params['parents'] = array($params['parents'] => 1);
454 if (!empty($params['parents'])) {
455 foreach ($params['parents'] as $parentId => $dnc) {
456 if (CRM_Utils_Type
::validate($parentId, 'Integer', FALSE)) {
457 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
458 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
464 // this is always required, since we don't know when a
465 // parent group is removed
466 CRM_Contact_BAO_GroupNestingCache
::update();
468 // update group contact cache for all parent groups
469 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
470 foreach ($parentIds as $parentId) {
471 CRM_Contact_BAO_GroupContactCache
::add($parentId);
475 if (!empty($params['organization_id'])) {
477 $groupOrg['group_id'] = $group->id
;
478 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
481 CRM_Utils_System
::flushCache();
482 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
484 if (!empty($params['id'])) {
485 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
488 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
491 $recentOther = array();
492 if (CRM_Core_Permission
::check('edit groups')) {
493 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
494 // currently same permission we are using for delete a group
495 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
498 // add the recently added group (unless hidden: CRM-6432)
499 if (!$group->is_hidden
) {
500 CRM_Utils_Recent
::add($group->title
,
501 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
513 * Given a saved search compute the clause and the tables
514 * and store it for future use
516 public function buildClause() {
517 $params = array(array('group', 'IN', array($this->id
), 0, 0));
519 if (!empty($params)) {
520 $tables = $whereTables = array();
521 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
522 if (!empty($tables)) {
523 $this->select_tables
= serialize($tables);
525 if (!empty($whereTables)) {
526 $this->where_tables
= serialize($whereTables);
532 * Defines a new smart group.
534 * @param array $params
535 * Associative array of parameters.
537 * @return CRM_Contact_BAO_Group|NULL
538 * The new group BAO (if created)
540 public static function createSmartGroup(&$params) {
541 if (!empty($params['formValues'])) {
543 unset($ssParams['id']);
544 if (isset($ssParams['saved_search_id'])) {
545 $ssParams['id'] = $ssParams['saved_search_id'];
548 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
550 $params['saved_search_id'] = $savedSearch->id
;
556 return self
::create($params);
560 * Update the is_active flag in the db.
563 * Id of the database record.
564 * @param bool $isActive
565 * Value we want to set the is_active field.
567 * @return CRM_Core_DAO|null
568 * 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.
583 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
585 if ($groupType == 'Mailing') {
586 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
588 elseif ($groupType == 'Access') {
589 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
591 elseif (!empty($groupType)) {
592 // ie we have been given the group key
593 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
597 if ($excludeHidden) {
598 $condition = "is_hidden = 0";
603 $condition .= " AND group_type LIKE '%$value%'";
606 $condition = "group_type LIKE '%$value%'";
614 * Get permission relevant clauses.
621 public static function getPermissionClause($force = FALSE) {
623 static $retrieved = FALSE;
624 if (!$retrieved ||
$force) {
625 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
629 //get the allowed groups for the current user
630 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
631 if (!empty($groups)) {
632 $groupList = implode(', ', array_values($groups));
633 $clause = "groups.id IN ( $groupList ) ";
647 public function __toString() {
652 * This function create the hidden smart group when user perform
653 * contact search and want to send mailing to search contacts.
655 * @param array $params
656 * ( reference ) an assoc array of name/value pairs.
659 * ( smartGroupId, ssId ) smart group id and saved search id
661 public static function createHiddenSmartGroup($params) {
662 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
664 //add mapping record only for search builder saved search
666 if ($params['search_context'] == 'builder') {
667 //save the mapping for search builder
669 //save record in mapping table
671 $mappingParams = array('mapping_type' => 'Search Builder');
672 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams, $temp);
673 $mappingId = $mapping->id
;
676 //get the mapping id from saved search
677 $savedSearch = new CRM_Contact_BAO_SavedSearch();
678 $savedSearch->id
= $ssId;
679 $savedSearch->find(TRUE);
680 $mappingId = $savedSearch->mapping_id
;
683 //save mapping fields
684 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
687 //create/update saved search record.
688 $savedSearch = new CRM_Contact_BAO_SavedSearch();
689 $savedSearch->id
= $ssId;
690 $savedSearch->form_values
= serialize($params['form_values']);
691 $savedSearch->mapping_id
= $mappingId;
692 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
693 $savedSearch->save();
695 $ssId = $savedSearch->id
;
700 $smartGroupId = NULL;
701 if (!empty($params['saved_search_id'])) {
702 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
705 //create group only when new saved search.
706 $groupParams = array(
707 'title' => "Hidden Smart Group {$ssId}",
708 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
709 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
710 'group_type' => CRM_Utils_Array
::value('group_type', $params),
711 'visibility' => CRM_Utils_Array
::value('visibility', $params),
712 'saved_search_id' => $ssId,
715 $smartGroup = self
::create($groupParams);
716 $smartGroupId = $smartGroup->id
;
719 return array($smartGroupId, $ssId);
723 * wrapper for ajax group selector.
725 * @param array $params
726 * Associated array for params record id.
729 * associated array of group list
732 * @todo there seems little reason for the small number of functions that call this to pass in
733 * params that then need to be translated in this function since they are coding them when calling
735 static public function getGroupListSelector(&$params) {
737 $params['offset'] = ($params['page'] - 1) * $params['rp'];
738 $params['rowCount'] = $params['rp'];
739 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
742 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
744 //skip total if we are making call to show only children
745 if (empty($params['parent_id'])) {
747 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
749 // get all the groups
750 $allGroups = CRM_Core_PseudoConstant
::allGroup();
753 // format params and add links
754 $groupList = array();
755 foreach ($groups as $id => $value) {
757 $group['group_id'] = $value['id'];
758 $group['count'] = $value['count'];
759 $group['title'] = $value['title'];
761 // append parent names if in search mode
762 if (empty($params['parent_id']) && !empty($value['parents'])) {
763 $group['parent_id'] = $value['parents'];
764 $groupIds = explode(',', $value['parents']);
766 foreach ($groupIds as $gId) {
767 $title[] = $allGroups[$gId];
769 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
770 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
772 $group['DT_RowId'] = 'row_' . $value['id'];
773 if (empty($params['parentsOnly'])) {
774 foreach ($value['class'] as $id => $class) {
775 if ($class == 'crm-group-parent') {
776 unset($value['class'][$id]);
780 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
781 $group['DT_RowAttr'] = array();
782 $group['DT_RowAttr']['data-id'] = $value['id'];
783 $group['DT_RowAttr']['data-entity'] = 'group';
785 $group['description'] = CRM_Utils_Array
::value('description', $value);
787 if (!empty($value['group_type'])) {
788 $group['group_type'] = $value['group_type'];
791 $group['group_type'] = '';
794 $group['visibility'] = $value['visibility'];
795 $group['links'] = $value['action'];
796 $group['org_info'] = CRM_Utils_Array
::value('org_info', $value);
797 $group['created_by'] = CRM_Utils_Array
::value('created_by', $value);
799 $group['is_parent'] = $value['is_parent'];
801 array_push($groupList, $group);
805 $groupsDT['data'] = $groupList;
806 $groupsDT['recordsTotal'] = $params['total'];
807 $groupsDT['recordsFiltered'] = $params['total'];
813 * This function to get list of groups.
815 * @param array $params
816 * Associated array for params.
820 public static function getGroupList(&$params) {
821 $config = CRM_Core_Config
::singleton();
823 $whereClause = self
::whereClause($params, FALSE);
825 //$this->pagerAToZ( $whereClause, $params );
827 if (!empty($params['rowCount']) &&
828 $params['rowCount'] > 0
830 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
833 $orderBy = ' ORDER BY groups.title asc';
834 if (!empty($params['sort'])) {
835 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
837 // CRM-16905 - Sort by count cannot be done with sql
838 if (strpos($params['sort'], 'count') === 0) {
839 $orderBy = $limit = '';
843 $select = $from = $where = "";
845 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
846 CRM_Core_Permission
::isMultisiteEnabled()
848 $select = ", contact.display_name as org_name, contact.id as org_id";
849 $from = " LEFT JOIN civicrm_group_organization gOrg
850 ON gOrg.group_id = groups.id
851 LEFT JOIN civicrm_contact contact
852 ON contact.id = gOrg.organization_id ";
854 //get the Organization ID
855 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
857 $where = " AND gOrg.organization_id = {$orgID}";
864 SELECT groups.*, createdBy.sort_name as created_by {$select}
865 FROM civicrm_group groups
866 LEFT JOIN civicrm_contact createdBy
867 ON createdBy.id = groups.created_id
869 WHERE $whereClause {$where}
873 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
875 //FIXME CRM-4418, now we are handling delete separately
876 //if we introduce 'delete for group' make sure to handle here.
877 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
878 if (CRM_Core_Permission
::check('edit groups')) {
879 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
880 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
884 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
886 $links = self
::actionLinks();
888 $allTypes = CRM_Core_OptionGroup
::values('group_type');
889 $values = $groupsToCount = array();
891 $visibility = CRM_Core_SelectValues
::ufVisibility();
893 while ($object->fetch()) {
894 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
895 //@todo CRM-12209 introduced an ACL check in the whereClause function
896 // it may be that this checking is now obsolete - or that what remains
897 // should be removed to the whereClause (which is also accessed by getCount)
901 $values[$object->id
] = array(
905 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
907 if ($object->saved_search_id
) {
908 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
909 // check if custom search, if so fix view link
910 $customSearchID = CRM_Core_DAO
::getFieldValue(
911 'CRM_Contact_DAO_SavedSearch',
912 $object->saved_search_id
,
916 if ($customSearchID) {
917 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
918 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
922 $action = array_sum(array_keys($newLinks));
925 if (array_key_exists('is_reserved', $object)) {
926 //if group is reserved and I don't have reserved permission, suppress delete/edit
927 if ($object->is_reserved
&& !$reservedPermission) {
928 $action -= CRM_Core_Action
::DELETE
;
929 $action -= CRM_Core_Action
::UPDATE
;
930 $action -= CRM_Core_Action
::DISABLE
;
934 if (array_key_exists('is_active', $object)) {
935 if ($object->is_active
) {
936 $action -= CRM_Core_Action
::ENABLE
;
939 $values[$object->id
]['class'][] = 'disabled';
940 $action -= CRM_Core_Action
::VIEW
;
941 $action -= CRM_Core_Action
::DISABLE
;
945 $action = $action & CRM_Core_Action
::mask($groupPermissions);
947 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
949 $groupsToCount[$object->saved_search_id ?
'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id
;
951 if (isset($values[$object->id
]['group_type'])) {
952 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
953 substr($values[$object->id
]['group_type'], 1, -1)
956 foreach ($groupTypes as $type) {
957 $types[] = CRM_Utils_Array
::value($type, $allTypes);
959 $values[$object->id
]['group_type'] = implode(', ', $types);
961 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
965 'ssid' => $object->saved_search_id
,
969 'group.selector.row',
974 // If group has children, add class for link to view children
975 $values[$object->id
]['is_parent'] = FALSE;
976 if (array_key_exists('children', $values[$object->id
])) {
977 $values[$object->id
]['class'][] = "crm-group-parent";
978 $values[$object->id
]['is_parent'] = TRUE;
981 // If group is a child, add child class
982 if (array_key_exists('parents', $values[$object->id
])) {
983 $values[$object->id
]['class'][] = "crm-group-child";
987 if ($object->org_id
) {
988 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
989 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
992 $values[$object->id
]['org_info'] = ''; // Empty cell
996 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
998 if ($object->created_id
) {
999 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
1000 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
1005 // Get group counts - executes one query for regular groups and another for smart groups
1006 foreach ($groupsToCount as $table => $groups) {
1007 $where = "g.group_id IN (" . implode(',', $groups) . ")";
1008 if ($table == 'civicrm_group_contact') {
1009 $where .= " AND g.status = 'Added'";
1011 // Exclude deleted contacts
1012 $where .= " and c.id = g.contact_id AND c.is_deleted = 0";
1013 $dao = CRM_Core_DAO
::executeQuery("SELECT g.group_id, COUNT(g.id) as `count` FROM $table g, civicrm_contact c WHERE $where GROUP BY g.group_id");
1014 while ($dao->fetch()) {
1015 $values[$dao->group_id
]['count'] = $dao->count
;
1019 // CRM-16905 - Sort by count cannot be done with sql
1020 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1021 usort($values, function($a, $b) {
1022 return $a['count'] - $b['count'];
1024 if (strpos($params['sort'], 'desc')) {
1025 $values = array_reverse($values, TRUE);
1027 return array_slice($values, $params['offset'], $params['rowCount']);
1034 * This function to get hierarchical list of groups (parent followed by children)
1036 * @param array $groupIDs
1037 * Array of group ids.
1039 * @param NULL $parents
1040 * @param string $spacer
1041 * @param bool $titleOnly
1045 public static function getGroupsHierarchy(
1048 $spacer = '<span class="child-indent"></span>',
1051 if (empty($groupIDs)) {
1055 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1056 // <span class="child-icon"></span>
1057 // need to return id, title (w/ spacer), description, visibility
1059 // We need to build a list of tags ordered by hierarchy and sorted by
1060 // name. The hierarchy will be communicated by an accumulation of
1061 // separators in front of the name to give it a visual offset.
1062 // Instead of recursively making mysql queries, we'll make one big
1063 // query and build the hierarchy with the algorithm below.
1065 $args = array(1 => array($groupIdString, 'String'));
1067 SELECT id, title, description, visibility, parents
1069 WHERE id IN $groupIdString
1072 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1073 $parentArray = explode(',', $parents);
1074 $parent = $parentArray[0];
1075 $args[2] = array($parent, 'Integer');
1076 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1078 $query .= " ORDER BY title";
1079 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1081 // Sort the groups into the correct storage by the parent
1082 // $roots represent the current leaf nodes that need to be checked for
1083 // children. $rows represent the unplaced nodes
1084 $roots = $rows = $allGroups = array();
1085 while ($dao->fetch()) {
1086 $allGroups[$dao->id
] = array(
1087 'title' => $dao->title
,
1088 'visibility' => $dao->visibility
,
1089 'description' => $dao->description
,
1092 if ($dao->parents
== $parents) {
1096 'title' => $dao->title
,
1100 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1101 $parentArray = explode(',', $dao->parents
);
1102 $parent = $parentArray[0];
1106 'title' => $dao->title
,
1107 'parents' => $parent,
1112 // While we have nodes left to build, shift the first (alphabetically)
1113 // node of the list, place it in our groups list and loop through the
1114 // list of unplaced nodes to find its children. We make a copy to
1115 // iterate through because we must modify the unplaced nodes list
1117 while (count($roots)) {
1118 $new_roots = array();
1119 $current_rows = $rows;
1120 $root = array_shift($roots);
1121 $groups[$root['id']] = array($root['prefix'], $root['title']);
1123 // As you find the children, append them to the end of the new set
1124 // of roots (maintain alphabetical ordering). Also remove the node
1125 // from the set of unplaced nodes.
1126 if (is_array($current_rows)) {
1127 foreach ($current_rows as $key => $row) {
1128 if ($row['parents'] == $root['id']) {
1129 $new_roots[] = array(
1131 'prefix' => $groups[$root['id']][0] . $spacer,
1132 'title' => $row['title'],
1139 //As a group, insert the new roots into the beginning of the roots
1140 //list. This maintains the hierarchical ordering of the tags.
1141 $roots = array_merge($new_roots, $roots);
1144 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1145 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1146 foreach ($rows as $value) {
1147 $groups[$value['id']] = array($value['prefix'], $value['title']);
1149 // Prefix titles with the calcuated spacing to give the visual
1150 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1151 $groupsReturn = array();
1152 foreach ($groups as $key => $value) {
1154 $groupsReturn[$key] = $value[0] . $value[1];
1157 $groupsReturn[$key] = array(
1158 'title' => $value[0] . $value[1],
1159 'description' => $allGroups[$key]['description'],
1160 'visibility' => $allGroups[$key]['visibility'],
1165 return $groupsReturn;
1169 * @param array $params
1171 * @return NULL|string
1173 public static function getGroupCount(&$params) {
1174 $whereClause = self
::whereClause($params, FALSE);
1175 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1177 if (!empty($params['created_by'])) {
1179 INNER JOIN civicrm_contact createdBy
1180 ON createdBy.id = groups.created_id";
1183 WHERE {$whereClause}";
1184 return CRM_Core_DAO
::singleValueQuery($query, $params);
1188 * Generate permissioned where clause for group search.
1189 * @param array $params
1190 * @param bool $sortBy
1191 * @param bool $excludeHidden
1195 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1197 $title = CRM_Utils_Array
::value('title', $params);
1199 $clauses[] = "groups.title LIKE %1";
1200 if (strpos($title, '%') !== FALSE) {
1201 $params[1] = array($title, 'String', FALSE);
1204 $params[1] = array($title, 'String', TRUE);
1208 $groupType = CRM_Utils_Array
::value('group_type', $params);
1210 $types = explode(',', $groupType);
1211 if (!empty($types)) {
1212 $clauses[] = 'groups.group_type LIKE %2';
1213 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1214 $params[2] = array($typeString, 'String', TRUE);
1218 $visibility = CRM_Utils_Array
::value('visibility', $params);
1220 $clauses[] = 'groups.visibility = %3';
1221 $params[3] = array($visibility, 'String');
1224 $groupStatus = CRM_Utils_Array
::value('status', $params);
1226 switch ($groupStatus) {
1228 $clauses[] = 'groups.is_active = 1';
1229 $params[4] = array($groupStatus, 'Integer');
1233 $clauses[] = 'groups.is_active = 0';
1234 $params[4] = array($groupStatus, 'Integer');
1238 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1243 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1245 $clauses[] = 'groups.parents IS NULL';
1248 // only show child groups of a specific parent group
1249 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1251 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1252 $params[5] = array($parent_id, 'Integer');
1255 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1256 $clauses[] = "createdBy.sort_name LIKE %6";
1257 if (strpos($createdBy, '%') !== FALSE) {
1258 $params[6] = array($createdBy, 'String', FALSE);
1261 $params[6] = array($createdBy, 'String', TRUE);
1265 if (empty($clauses)) {
1266 $clauses[] = 'groups.is_active = 1';
1269 if ($excludeHidden) {
1270 $clauses[] = 'groups.is_hidden = 0';
1273 $clauses[] = self
::getPermissionClause();
1275 return implode(' AND ', $clauses);
1279 * Define action links.
1282 * array of action links
1284 public static function actionLinks() {
1286 CRM_Core_Action
::VIEW
=> array(
1287 'name' => ts('Contacts'),
1288 'url' => 'civicrm/group/search',
1289 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1290 'title' => ts('Group Contacts'),
1292 CRM_Core_Action
::UPDATE
=> array(
1293 'name' => ts('Settings'),
1294 'url' => 'civicrm/group',
1295 'qs' => 'reset=1&action=update&id=%%id%%',
1296 'title' => ts('Edit Group'),
1298 CRM_Core_Action
::DISABLE
=> array(
1299 'name' => ts('Disable'),
1300 'ref' => 'crm-enable-disable',
1301 'title' => ts('Disable Group'),
1303 CRM_Core_Action
::ENABLE
=> array(
1304 'name' => ts('Enable'),
1305 'ref' => 'crm-enable-disable',
1306 'title' => ts('Enable Group'),
1308 CRM_Core_Action
::DELETE
=> array(
1309 'name' => ts('Delete'),
1310 'url' => 'civicrm/group',
1311 'qs' => 'reset=1&action=delete&id=%%id%%',
1312 'title' => ts('Delete Group'),
1320 * @param $whereClause
1321 * @param array $whereParams
1325 public function pagerAtoZ($whereClause, $whereParams) {
1327 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1328 FROM civicrm_group groups
1330 ORDER BY LEFT(groups.title, 1)
1332 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1334 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1338 * Assign Test Value.
1340 * @param string $fieldName
1341 * @param array $fieldDef
1342 * @param int $counter
1344 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1345 if ($fieldName == 'children' ||
$fieldName = 'parents') {
1346 $this->{$fieldName} = "NULL";
1349 parent
::assignTestValues($fieldaName, $fieldDef, $counter);