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 if (Civi
::settings()->get('is_enabled')) {
111 // clear any descendant groups cache if exists
112 CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
115 // delete from group table
116 $group = new CRM_Contact_DAO_Group();
120 $transaction->commit();
122 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
124 // delete the recently created Group
125 $groupRecent = array(
129 CRM_Utils_Recent
::del($groupRecent);
133 * Returns an array of the contacts in the given group.
137 public static function getGroupContacts($id) {
138 $params = array(array('group', 'IN', array($id => 1), 0, 0));
139 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
144 * Get the count of a members in a group with the specific status.
148 * @param string $status
149 * status of members in group
150 * @param bool $countChildGroups
153 * count of members in the group with above status
155 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
156 $groupContact = new CRM_Contact_DAO_GroupContact();
157 $groupIds = array($id);
158 if ($countChildGroups) {
159 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
163 $contacts = self
::getGroupContacts($id);
165 foreach ($groupIds as $groupId) {
167 $groupContacts = self
::getGroupContacts($groupId);
168 foreach ($groupContacts as $gcontact) {
169 if ($groupId != $id) {
170 // Loop through main group's contacts
171 // and subtract from the count for each contact which
172 // matches one in the present group, if it is not the
174 foreach ($contacts as $contact) {
175 if ($contact['contact_id'] == $gcontact['contact_id']) {
181 $groupContact->group_id
= $groupId;
182 if (isset($status)) {
183 $groupContact->status
= $status;
185 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
186 $count +
= $groupContact->count();
192 * Get the list of member for a group id.
194 * @param int $groupID
195 * @param bool $useCache
197 * Number to limit to (or 0 for unlimited).
200 * this array contains the list of members for this group id
202 public static function getMember($groupID, $useCache = TRUE, $limit = 0) {
203 $params = array(array('group', '=', $groupID, 0, 0));
204 $returnProperties = array('contact_id');
205 list($contacts) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache);
208 foreach ($contacts as $contact) {
209 $aMembers[$contact['contact_id']] = 1;
216 * Returns array of group object(s) matching a set of one or Group properties.
218 * @param array $params
219 * Limits the set of groups returned.
220 * @param array $returnProperties
221 * Which properties should be included in the returned group objects.
222 * (member_count should be last element.)
223 * @param string $sort
225 * @param int $rowCount
228 * Array of group objects.
231 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
232 * add in essential fields (e.g. id). This should follow a regular pattern like the others
234 public static function getGroups(
236 $returnProperties = NULL,
241 $dao = new CRM_Contact_DAO_Group();
242 if (!isset($params['is_active'])) {
246 foreach ($params as $k => $v) {
247 if ($k == 'name' ||
$k == 'title') {
248 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
250 elseif ($k == 'group_type') {
251 foreach ((array) $v as $type) {
252 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
255 elseif (is_array($v)) {
256 foreach ($v as &$num) {
259 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
267 if ($offset ||
$rowCount) {
268 $offset = ($offset > 0) ?
$offset : 0;
269 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
270 $dao->limit($offset, $rowCount);
274 $dao->orderBy($sort);
277 // return only specific fields if returnproperties are sent
278 if (!empty($returnProperties)) {
280 $dao->selectAdd(implode(',', $returnProperties));
284 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
287 while ($dao->fetch()) {
288 $group = new CRM_Contact_DAO_Group();
290 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
292 $groups[] = clone($dao);
298 * Make sure that the user has permission to access this group.
301 * The id of the object.
302 * @param bool $excludeHidden
303 * Should hidden groups be excluded.
304 * Logically this is the wrong place to filter hidden groups out as that is
305 * not a permission issue. However, as other functions may rely on that defaulting to
306 * FALSE for now & only the api call is calling with true.
309 * The permission that the user has (or NULL)
311 public static function checkPermission($id, $excludeHidden = FALSE) {
312 $allGroups = CRM_Core_PseudoConstant
::allGroup(NULL, $excludeHidden);
315 if (CRM_Core_Permission
::check('edit all contacts') ||
316 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
317 'civicrm_saved_search', $allGroups
320 $permissions[] = CRM_Core_Permission
::EDIT
;
323 if (CRM_Core_Permission
::check('view all contacts') ||
324 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
325 'civicrm_saved_search', $allGroups
328 $permissions[] = CRM_Core_Permission
::VIEW
;
331 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
332 // Note: using !empty() in if condition, restricts the scope of delete
333 // permission to groups/contacts that are editable/viewable.
334 // We can remove this !empty condition once we have ACL support for delete functionality.
335 $permissions[] = CRM_Core_Permission
::DELETE
;
342 * Create a new group.
344 * @param array $params
346 * @return CRM_Contact_BAO_Group|NULL
347 * The new group BAO (if created)
349 public static function create(&$params) {
351 if (!empty($params['id'])) {
352 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
355 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
358 // form the name only if missing: CRM-627
359 $nameParam = CRM_Utils_Array
::value('name', $params, NULL);
360 if (!$nameParam && empty($params['id'])) {
361 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
364 // convert params if array type
365 if (isset($params['group_type'])) {
366 if (is_array($params['group_type'])) {
367 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
368 $params['group_type']
369 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
372 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $params['group_type'] . CRM_Core_DAO
::VALUE_SEPARATOR
;
376 $params['group_type'] = NULL;
379 $session = CRM_Core_Session
::singleton();
380 $cid = $session->get('userID');
381 // this action is add
382 if ($cid && empty($params['id'])) {
383 $params['created_id'] = $cid;
385 // this action is update
386 if ($cid && !empty($params['id'])) {
387 $params['modified_id'] = $cid;
390 $group = new CRM_Contact_BAO_Group();
391 $group->copyValues($params);
392 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
393 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
394 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
395 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
396 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
397 if (isset($group->parents
) && is_array($group->parents
)) {
398 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
399 array_keys($group->parents
)
400 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
402 if (empty($params['id']) &&
405 $group->name
.= "_tmp";
413 if (empty($params['id']) &&
416 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
419 $group->buildClause();
422 // add custom field values
423 if (!empty($params['custom'])) {
424 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
427 // make the group, child of domain/site group by default.
428 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
429 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
430 if (empty($params['parents']) &&
431 $domainGroupID != $group->id
&&
432 Civi
::settings()->get('is_enabled') &&
433 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
435 // if no parent present and the group doesn't already have any parents,
436 // make sure site group goes as parent
437 $params['parents'] = array($domainGroupID => 1);
439 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
440 $params['parents'] = array($params['parents'] => 1);
443 if (!empty($params['parents'])) {
444 foreach ($params['parents'] as $parentId => $dnc) {
445 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
446 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
451 // clear any descendant groups cache if exists
452 $finalGroups = CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
454 // this is always required, since we don't know when a
455 // parent group is removed
456 CRM_Contact_BAO_GroupNestingCache
::update();
458 // update group contact cache for all parent groups
459 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
460 foreach ($parentIds as $parentId) {
461 CRM_Contact_BAO_GroupContactCache
::add($parentId);
465 if (!empty($params['organization_id'])) {
467 $groupOrg['group_id'] = $group->id
;
468 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
471 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
473 if (!empty($params['id'])) {
474 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
477 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
480 $recentOther = array();
481 if (CRM_Core_Permission
::check('edit groups')) {
482 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
483 // currently same permission we are using for delete a group
484 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
487 // add the recently added group (unless hidden: CRM-6432)
488 if (!$group->is_hidden
) {
489 CRM_Utils_Recent
::add($group->title
,
490 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
502 * Given a saved search compute the clause and the tables
503 * and store it for future use
505 public function buildClause() {
506 $params = array(array('group', 'IN', array($this->id
), 0, 0));
508 if (!empty($params)) {
509 $tables = $whereTables = array();
510 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
511 if (!empty($tables)) {
512 $this->select_tables
= serialize($tables);
514 if (!empty($whereTables)) {
515 $this->where_tables
= serialize($whereTables);
521 * Defines a new smart group.
523 * @param array $params
524 * Associative array of parameters.
526 * @return CRM_Contact_BAO_Group|NULL
527 * The new group BAO (if created)
529 public static function createSmartGroup(&$params) {
530 if (!empty($params['formValues'])) {
532 unset($ssParams['id']);
533 if (isset($ssParams['saved_search_id'])) {
534 $ssParams['id'] = $ssParams['saved_search_id'];
537 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
539 $params['saved_search_id'] = $savedSearch->id
;
545 return self
::create($params);
549 * Update the is_active flag in the db.
552 * Id of the database record.
553 * @param bool $isActive
554 * Value we want to set the is_active field.
556 * @return CRM_Core_DAO|null
557 * DAO object on success, NULL otherwise
559 public static function setIsActive($id, $isActive) {
560 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
564 * Build the condition to retrieve groups.
566 * @param string $groupType
567 * Type of group(Access/Mailing) OR the key of the group.
568 * @param bool $excludeHidden exclude hidden groups.
572 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
574 if ($groupType == 'Mailing') {
575 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
577 elseif ($groupType == 'Access') {
578 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
580 elseif (!empty($groupType)) {
581 // ie we have been given the group key
582 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
586 if ($excludeHidden) {
587 $condition = "is_hidden = 0";
592 $condition .= " AND group_type LIKE '%$value%'";
595 $condition = "group_type LIKE '%$value%'";
603 * Get permission relevant clauses.
610 public static function getPermissionClause($force = FALSE) {
612 static $retrieved = FALSE;
613 if (!$retrieved ||
$force) {
614 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
618 //get the allowed groups for the current user
619 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
620 if (!empty($groups)) {
621 $groupList = implode(', ', array_values($groups));
622 $clause = "groups.id IN ( $groupList ) ";
636 public function __toString() {
641 * This function create the hidden smart group when user perform
642 * contact search and want to send mailing to search contacts.
644 * @param array $params
645 * ( reference ) an assoc array of name/value pairs.
648 * ( smartGroupId, ssId ) smart group id and saved search id
650 public static function createHiddenSmartGroup($params) {
651 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
653 //add mapping record only for search builder saved search
655 if ($params['search_context'] == 'builder') {
656 //save the mapping for search builder
658 //save record in mapping table
660 $mappingParams = array('mapping_type' => 'Search Builder');
661 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams, $temp);
662 $mappingId = $mapping->id
;
665 //get the mapping id from saved search
666 $savedSearch = new CRM_Contact_BAO_SavedSearch();
667 $savedSearch->id
= $ssId;
668 $savedSearch->find(TRUE);
669 $mappingId = $savedSearch->mapping_id
;
672 //save mapping fields
673 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
676 //create/update saved search record.
677 $savedSearch = new CRM_Contact_BAO_SavedSearch();
678 $savedSearch->id
= $ssId;
679 $savedSearch->form_values
= serialize($params['form_values']);
680 $savedSearch->mapping_id
= $mappingId;
681 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
682 $savedSearch->save();
684 $ssId = $savedSearch->id
;
689 $smartGroupId = NULL;
690 if (!empty($params['saved_search_id'])) {
691 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
694 //create group only when new saved search.
695 $groupParams = array(
696 'title' => "Hidden Smart Group {$ssId}",
697 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
698 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
699 'group_type' => CRM_Utils_Array
::value('group_type', $params),
700 'visibility' => CRM_Utils_Array
::value('visibility', $params),
701 'saved_search_id' => $ssId,
704 $smartGroup = self
::create($groupParams);
705 $smartGroupId = $smartGroup->id
;
708 return array($smartGroupId, $ssId);
712 * wrapper for ajax group selector.
714 * @param array $params
715 * Associated array for params record id.
718 * associated array of group list
721 * @todo there seems little reason for the small number of functions that call this to pass in
722 * params that then need to be translated in this function since they are coding them when calling
724 static public function getGroupListSelector(&$params) {
726 $params['offset'] = ($params['page'] - 1) * $params['rp'];
727 $params['rowCount'] = $params['rp'];
728 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
731 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
733 //skip total if we are making call to show only children
734 if (empty($params['parent_id'])) {
736 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
738 // get all the groups
739 $allGroups = CRM_Core_PseudoConstant
::allGroup();
742 // format params and add links
743 $groupList = array();
744 foreach ($groups as $id => $value) {
746 $group['group_id'] = $value['id'];
747 $group['count'] = $value['count'];
748 $group['title'] = $value['title'];
750 // append parent names if in search mode
751 if (empty($params['parent_id']) && !empty($value['parents'])) {
752 $group['parent_id'] = $value['parents'];
753 $groupIds = explode(',', $value['parents']);
755 foreach ($groupIds as $gId) {
756 $title[] = $allGroups[$gId];
758 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
759 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
761 $group['DT_RowId'] = 'row_' . $value['id'];
762 if (empty($params['parentsOnly'])) {
763 foreach ($value['class'] as $id => $class) {
764 if ($class == 'crm-group-parent') {
765 unset($value['class'][$id]);
769 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
770 $group['DT_RowAttr'] = array();
771 $group['DT_RowAttr']['data-id'] = $value['id'];
772 $group['DT_RowAttr']['data-entity'] = 'group';
774 $group['description'] = CRM_Utils_Array
::value('description', $value);
776 if (!empty($value['group_type'])) {
777 $group['group_type'] = $value['group_type'];
780 $group['group_type'] = '';
783 $group['visibility'] = $value['visibility'];
784 $group['links'] = $value['action'];
785 $group['org_info'] = CRM_Utils_Array
::value('org_info', $value);
786 $group['created_by'] = CRM_Utils_Array
::value('created_by', $value);
788 $group['is_parent'] = $value['is_parent'];
790 array_push($groupList, $group);
794 $groupsDT['data'] = $groupList;
795 $groupsDT['recordsTotal'] = $params['total'];
796 $groupsDT['recordsFiltered'] = $params['total'];
802 * This function to get list of groups.
804 * @param array $params
805 * Associated array for params.
809 public static function getGroupList(&$params) {
810 $config = CRM_Core_Config
::singleton();
812 $whereClause = self
::whereClause($params, FALSE);
814 //$this->pagerAToZ( $whereClause, $params );
816 if (!empty($params['rowCount']) &&
817 $params['rowCount'] > 0
819 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
822 $orderBy = ' ORDER BY groups.title asc';
823 if (!empty($params['sort'])) {
824 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
826 // CRM-16905 - Sort by count cannot be done with sql
827 if (strpos($params['sort'], 'count') === 0) {
828 $orderBy = $limit = '';
832 $select = $from = $where = "";
834 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
835 CRM_Core_Permission
::isMultisiteEnabled()
837 $select = ", contact.display_name as org_name, contact.id as org_id";
838 $from = " LEFT JOIN civicrm_group_organization gOrg
839 ON gOrg.group_id = groups.id
840 LEFT JOIN civicrm_contact contact
841 ON contact.id = gOrg.organization_id ";
843 //get the Organization ID
844 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
846 $where = " AND gOrg.organization_id = {$orgID}";
853 SELECT groups.*, createdBy.sort_name as created_by {$select}
854 FROM civicrm_group groups
855 LEFT JOIN civicrm_contact createdBy
856 ON createdBy.id = groups.created_id
858 WHERE $whereClause {$where}
862 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
864 //FIXME CRM-4418, now we are handling delete separately
865 //if we introduce 'delete for group' make sure to handle here.
866 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
867 if (CRM_Core_Permission
::check('edit groups')) {
868 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
869 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
873 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
875 $links = self
::actionLinks();
877 $allTypes = CRM_Core_OptionGroup
::values('group_type');
878 $values = $groupsToCount = array();
880 $visibility = CRM_Core_SelectValues
::ufVisibility();
882 while ($object->fetch()) {
883 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
884 //@todo CRM-12209 introduced an ACL check in the whereClause function
885 // it may be that this checking is now obsolete - or that what remains
886 // should be removed to the whereClause (which is also accessed by getCount)
890 $values[$object->id
] = array(
894 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
896 if ($object->saved_search_id
) {
897 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
898 // check if custom search, if so fix view link
899 $customSearchID = CRM_Core_DAO
::getFieldValue(
900 'CRM_Contact_DAO_SavedSearch',
901 $object->saved_search_id
,
905 if ($customSearchID) {
906 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
907 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
911 $action = array_sum(array_keys($newLinks));
914 if (array_key_exists('is_reserved', $object)) {
915 //if group is reserved and I don't have reserved permission, suppress delete/edit
916 if ($object->is_reserved
&& !$reservedPermission) {
917 $action -= CRM_Core_Action
::DELETE
;
918 $action -= CRM_Core_Action
::UPDATE
;
919 $action -= CRM_Core_Action
::DISABLE
;
923 if (array_key_exists('is_active', $object)) {
924 if ($object->is_active
) {
925 $action -= CRM_Core_Action
::ENABLE
;
928 $values[$object->id
]['class'][] = 'disabled';
929 $action -= CRM_Core_Action
::VIEW
;
930 $action -= CRM_Core_Action
::DISABLE
;
934 $action = $action & CRM_Core_Action
::mask($groupPermissions);
936 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
938 $groupsToCount[$object->saved_search_id ?
'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id
;
940 if (isset($values[$object->id
]['group_type'])) {
941 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
942 substr($values[$object->id
]['group_type'], 1, -1)
945 foreach ($groupTypes as $type) {
946 $types[] = CRM_Utils_Array
::value($type, $allTypes);
948 $values[$object->id
]['group_type'] = implode(', ', $types);
950 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
954 'ssid' => $object->saved_search_id
,
958 'group.selector.row',
963 // If group has children, add class for link to view children
964 $values[$object->id
]['is_parent'] = FALSE;
965 if (array_key_exists('children', $values[$object->id
])) {
966 $values[$object->id
]['class'][] = "crm-group-parent";
967 $values[$object->id
]['is_parent'] = TRUE;
970 // If group is a child, add child class
971 if (array_key_exists('parents', $values[$object->id
])) {
972 $values[$object->id
]['class'][] = "crm-group-child";
976 if ($object->org_id
) {
977 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
978 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
981 $values[$object->id
]['org_info'] = ''; // Empty cell
985 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
987 if ($object->created_id
) {
988 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
989 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
994 // Get group counts - executes one query for regular groups and another for smart groups
995 foreach ($groupsToCount as $table => $groups) {
996 $where = "g.group_id IN (" . implode(',', $groups) . ")";
997 if ($table == 'civicrm_group_contact') {
998 $where .= " AND g.status = 'Added'";
1000 // Exclude deleted contacts
1001 $where .= " and c.id = g.contact_id AND c.is_deleted = 0";
1002 $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");
1003 while ($dao->fetch()) {
1004 $values[$dao->group_id
]['count'] = $dao->count
;
1008 // CRM-16905 - Sort by count cannot be done with sql
1009 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1010 usort($values, function($a, $b) {
1011 return $a['count'] - $b['count'];
1013 if (strpos($params['sort'], 'desc')) {
1014 $values = array_reverse($values, TRUE);
1016 return array_slice($values, $params['offset'], $params['rowCount']);
1023 * This function to get hierarchical list of groups (parent followed by children)
1025 * @param array $groupIDs
1026 * Array of group ids.
1028 * @param NULL $parents
1029 * @param string $spacer
1030 * @param bool $titleOnly
1034 public static function getGroupsHierarchy(
1037 $spacer = '<span class="child-indent"></span>',
1040 if (empty($groupIDs)) {
1044 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1045 // <span class="child-icon"></span>
1046 // need to return id, title (w/ spacer), description, visibility
1048 // We need to build a list of tags ordered by hierarchy and sorted by
1049 // name. The hierarchy will be communicated by an accumulation of
1050 // separators in front of the name to give it a visual offset.
1051 // Instead of recursively making mysql queries, we'll make one big
1052 // query and build the hierarchy with the algorithm below.
1054 $args = array(1 => array($groupIdString, 'String'));
1056 SELECT id, title, description, visibility, parents
1058 WHERE id IN $groupIdString
1061 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1062 $parentArray = explode(',', $parents);
1063 $parent = $parentArray[0];
1064 $args[2] = array($parent, 'Integer');
1065 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1067 $query .= " ORDER BY title";
1068 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1070 // Sort the groups into the correct storage by the parent
1071 // $roots represent the current leaf nodes that need to be checked for
1072 // children. $rows represent the unplaced nodes
1073 $roots = $rows = $allGroups = array();
1074 while ($dao->fetch()) {
1075 $allGroups[$dao->id
] = array(
1076 'title' => $dao->title
,
1077 'visibility' => $dao->visibility
,
1078 'description' => $dao->description
,
1081 if ($dao->parents
== $parents) {
1085 'title' => $dao->title
,
1089 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1090 $parentArray = explode(',', $dao->parents
);
1091 $parent = $parentArray[0];
1095 'title' => $dao->title
,
1096 'parents' => $parent,
1101 // While we have nodes left to build, shift the first (alphabetically)
1102 // node of the list, place it in our groups list and loop through the
1103 // list of unplaced nodes to find its children. We make a copy to
1104 // iterate through because we must modify the unplaced nodes list
1106 while (count($roots)) {
1107 $new_roots = array();
1108 $current_rows = $rows;
1109 $root = array_shift($roots);
1110 $groups[$root['id']] = array($root['prefix'], $root['title']);
1112 // As you find the children, append them to the end of the new set
1113 // of roots (maintain alphabetical ordering). Also remove the node
1114 // from the set of unplaced nodes.
1115 if (is_array($current_rows)) {
1116 foreach ($current_rows as $key => $row) {
1117 if ($row['parents'] == $root['id']) {
1118 $new_roots[] = array(
1120 'prefix' => $groups[$root['id']][0] . $spacer,
1121 'title' => $row['title'],
1128 //As a group, insert the new roots into the beginning of the roots
1129 //list. This maintains the hierarchical ordering of the tags.
1130 $roots = array_merge($new_roots, $roots);
1133 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1134 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1135 foreach ($rows as $value) {
1136 $groups[$value['id']] = array($value['prefix'], $value['title']);
1138 // Prefix titles with the calcuated spacing to give the visual
1139 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1140 $groupsReturn = array();
1141 foreach ($groups as $key => $value) {
1143 $groupsReturn[$key] = $value[0] . $value[1];
1146 $groupsReturn[$key] = array(
1147 'title' => $value[0] . $value[1],
1148 'description' => $allGroups[$key]['description'],
1149 'visibility' => $allGroups[$key]['visibility'],
1154 return $groupsReturn;
1158 * @param array $params
1160 * @return NULL|string
1162 public static function getGroupCount(&$params) {
1163 $whereClause = self
::whereClause($params, FALSE);
1164 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1166 if (!empty($params['created_by'])) {
1168 INNER JOIN civicrm_contact createdBy
1169 ON createdBy.id = groups.created_id";
1172 WHERE {$whereClause}";
1173 return CRM_Core_DAO
::singleValueQuery($query, $params);
1177 * Generate permissioned where clause for group search.
1178 * @param array $params
1179 * @param bool $sortBy
1180 * @param bool $excludeHidden
1184 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1186 $title = CRM_Utils_Array
::value('title', $params);
1188 $clauses[] = "groups.title LIKE %1";
1189 if (strpos($title, '%') !== FALSE) {
1190 $params[1] = array($title, 'String', FALSE);
1193 $params[1] = array($title, 'String', TRUE);
1197 $groupType = CRM_Utils_Array
::value('group_type', $params);
1199 $types = explode(',', $groupType);
1200 if (!empty($types)) {
1201 $clauses[] = 'groups.group_type LIKE %2';
1202 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1203 $params[2] = array($typeString, 'String', TRUE);
1207 $visibility = CRM_Utils_Array
::value('visibility', $params);
1209 $clauses[] = 'groups.visibility = %3';
1210 $params[3] = array($visibility, 'String');
1213 $groupStatus = CRM_Utils_Array
::value('status', $params);
1215 switch ($groupStatus) {
1217 $clauses[] = 'groups.is_active = 1';
1218 $params[4] = array($groupStatus, 'Integer');
1222 $clauses[] = 'groups.is_active = 0';
1223 $params[4] = array($groupStatus, 'Integer');
1227 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1232 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1234 $clauses[] = 'groups.parents IS NULL';
1237 // only show child groups of a specific parent group
1238 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1240 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1241 $params[5] = array($parent_id, 'Integer');
1244 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1245 $clauses[] = "createdBy.sort_name LIKE %6";
1246 if (strpos($createdBy, '%') !== FALSE) {
1247 $params[6] = array($createdBy, 'String', FALSE);
1250 $params[6] = array($createdBy, 'String', TRUE);
1254 if (empty($clauses)) {
1255 $clauses[] = 'groups.is_active = 1';
1258 if ($excludeHidden) {
1259 $clauses[] = 'groups.is_hidden = 0';
1262 $clauses[] = self
::getPermissionClause();
1264 return implode(' AND ', $clauses);
1268 * Define action links.
1271 * array of action links
1273 public static function actionLinks() {
1275 CRM_Core_Action
::VIEW
=> array(
1276 'name' => ts('Contacts'),
1277 'url' => 'civicrm/group/search',
1278 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1279 'title' => ts('Group Contacts'),
1281 CRM_Core_Action
::UPDATE
=> array(
1282 'name' => ts('Settings'),
1283 'url' => 'civicrm/group',
1284 'qs' => 'reset=1&action=update&id=%%id%%',
1285 'title' => ts('Edit Group'),
1287 CRM_Core_Action
::DISABLE
=> array(
1288 'name' => ts('Disable'),
1289 'ref' => 'crm-enable-disable',
1290 'title' => ts('Disable Group'),
1292 CRM_Core_Action
::ENABLE
=> array(
1293 'name' => ts('Enable'),
1294 'ref' => 'crm-enable-disable',
1295 'title' => ts('Enable Group'),
1297 CRM_Core_Action
::DELETE
=> array(
1298 'name' => ts('Delete'),
1299 'url' => 'civicrm/group',
1300 'qs' => 'reset=1&action=delete&id=%%id%%',
1301 'title' => ts('Delete Group'),
1309 * @param $whereClause
1310 * @param array $whereParams
1314 public function pagerAtoZ($whereClause, $whereParams) {
1316 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1317 FROM civicrm_group groups
1319 ORDER BY LEFT(groups.title, 1)
1321 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1323 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1327 * Assign Test Value.
1329 * @param string $fieldName
1330 * @param array $fieldDef
1331 * @param int $counter
1333 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1334 if ($fieldName == 'children' ||
$fieldName = 'parents') {
1335 $this->{$fieldName} = "NULL";
1338 parent
::assignTestValues($fieldaName, $fieldDef, $counter);