3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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(1 => $id), 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 CRM_Utils_Array
::convertCheckboxFormatToArray($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 (!empty($params['parents'])) {
388 $parents = is_array($params['parents']) ?
array_keys($params['parents']) : (array) $params['parents'];
389 foreach ($parents as $parent) {
390 CRM_Utils_Type
::validate($parent, 'Integer');
393 $group = new CRM_Contact_BAO_Group();
394 $group->copyValues($params);
395 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
396 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
397 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
398 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
399 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
400 if (isset($group->parents
) && is_array($group->parents
)) {
401 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
402 array_keys($group->parents
)
403 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
405 if (empty($params['id']) &&
408 $group->name
.= "_tmp";
416 if (empty($params['id']) &&
419 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
422 $group->buildClause();
425 // add custom field values
426 if (!empty($params['custom'])) {
427 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
430 // make the group, child of domain/site group by default.
431 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
432 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
433 if (empty($params['parents']) &&
434 $domainGroupID != $group->id
&&
435 Civi
::settings()->get('is_enabled') &&
436 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
438 // if no parent present and the group doesn't already have any parents,
439 // make sure site group goes as parent
440 $params['parents'] = array($domainGroupID => 1);
442 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
443 $params['parents'] = array($params['parents'] => 1);
446 if (!empty($params['parents'])) {
447 foreach ($params['parents'] as $parentId => $dnc) {
448 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
449 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
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);
472 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
474 if (!empty($params['id'])) {
475 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
478 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
481 $recentOther = array();
482 if (CRM_Core_Permission
::check('edit groups')) {
483 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
484 // currently same permission we are using for delete a group
485 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
488 // add the recently added group (unless hidden: CRM-6432)
489 if (!$group->is_hidden
) {
490 CRM_Utils_Recent
::add($group->title
,
491 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
503 * Given a saved search compute the clause and the tables
504 * and store it for future use
506 public function buildClause() {
507 $params = array(array('group', 'IN', array($this->id
), 0, 0));
509 if (!empty($params)) {
510 $tables = $whereTables = array();
511 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
512 if (!empty($tables)) {
513 $this->select_tables
= serialize($tables);
515 if (!empty($whereTables)) {
516 $this->where_tables
= serialize($whereTables);
522 * Defines a new smart group.
524 * @param array $params
525 * Associative array of parameters.
527 * @return CRM_Contact_BAO_Group|NULL
528 * The new group BAO (if created)
530 public static function createSmartGroup(&$params) {
531 if (!empty($params['formValues'])) {
533 unset($ssParams['id']);
534 if (isset($ssParams['saved_search_id'])) {
535 $ssParams['id'] = $ssParams['saved_search_id'];
538 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
540 $params['saved_search_id'] = $savedSearch->id
;
546 return self
::create($params);
550 * Update the is_active flag in the db.
553 * Id of the database record.
554 * @param bool $isActive
555 * Value we want to set the is_active field.
557 * @return CRM_Core_DAO|null
558 * DAO object on success, NULL otherwise
560 public static function setIsActive($id, $isActive) {
561 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
565 * Build the condition to retrieve groups.
567 * @param string $groupType
568 * Type of group(Access/Mailing) OR the key of the group.
569 * @param bool $excludeHidden exclude hidden groups.
573 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
575 if ($groupType == 'Mailing') {
576 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
578 elseif ($groupType == 'Access') {
579 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
581 elseif (!empty($groupType)) {
582 // ie we have been given the group key
583 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
587 if ($excludeHidden) {
588 $condition = "is_hidden = 0";
593 $condition .= " AND group_type LIKE '%$value%'";
596 $condition = "group_type LIKE '%$value%'";
604 * Get permission relevant clauses.
611 public static function getPermissionClause($force = FALSE) {
613 static $retrieved = FALSE;
614 if (!$retrieved ||
$force) {
615 if (CRM_Core_Permission
::check('view all contacts') || CRM_Core_Permission
::check('edit all contacts')) {
619 //get the allowed groups for the current user
620 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
621 if (!empty($groups)) {
622 $groupList = implode(', ', array_values($groups));
623 $clause = "groups.id IN ( $groupList ) ";
635 * Flush caches that hold group data.
637 * (Actually probably some overkill at the moment.)
639 protected static function flushCaches() {
640 CRM_Utils_System
::flushCache();
641 $staticCaches = array(
642 'CRM_Core_PseudoConstant' => 'groups',
643 'CRM_ACL_API' => 'group_permission',
644 'CRM_ACL_BAO_ACL' => 'permissioned_groups',
646 foreach ($staticCaches as $class => $key) {
647 if (isset(Civi
::$statics[$class][$key])) {
648 unset(Civi
::$statics[$class][$key]);
656 public function __toString() {
661 * This function create the hidden smart group when user perform
662 * contact search and want to send mailing to search contacts.
664 * @param array $params
665 * ( reference ) an assoc array of name/value pairs.
668 * ( smartGroupId, ssId ) smart group id and saved search id
670 public static function createHiddenSmartGroup($params) {
671 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
673 //add mapping record only for search builder saved search
675 if ($params['search_context'] == 'builder') {
676 //save the mapping for search builder
678 //save record in mapping table
679 $mappingParams = array(
680 'mapping_type_id' => CRM_Core_OptionGroup
::getValue('mapping_type',
685 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams);
686 $mappingId = $mapping->id
;
689 //get the mapping id from saved search
690 $savedSearch = new CRM_Contact_BAO_SavedSearch();
691 $savedSearch->id
= $ssId;
692 $savedSearch->find(TRUE);
693 $mappingId = $savedSearch->mapping_id
;
696 //save mapping fields
697 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
700 //create/update saved search record.
701 $savedSearch = new CRM_Contact_BAO_SavedSearch();
702 $savedSearch->id
= $ssId;
703 $savedSearch->form_values
= serialize($params['form_values']);
704 $savedSearch->mapping_id
= $mappingId;
705 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
706 $savedSearch->save();
708 $ssId = $savedSearch->id
;
713 $smartGroupId = NULL;
714 if (!empty($params['saved_search_id'])) {
715 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
718 //create group only when new saved search.
719 $groupParams = array(
720 'title' => "Hidden Smart Group {$ssId}",
721 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
722 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
723 'group_type' => CRM_Utils_Array
::value('group_type', $params),
724 'visibility' => CRM_Utils_Array
::value('visibility', $params),
725 'saved_search_id' => $ssId,
728 $smartGroup = self
::create($groupParams);
729 $smartGroupId = $smartGroup->id
;
732 // Update mapping with the name and description of the hidden smart group.
734 $mappingParams = array(
736 'name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'name', 'id'),
737 'description' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $smartGroupId, 'description', 'id'),
738 'mapping_type_id' => CRM_Core_OptionGroup
::getValue('mapping_type',
743 CRM_Core_BAO_Mapping
::add($mappingParams);
746 return array($smartGroupId, $ssId);
750 * wrapper for ajax group selector.
752 * @param array $params
753 * Associated array for params record id.
756 * associated array of group list
759 * @todo there seems little reason for the small number of functions that call this to pass in
760 * params that then need to be translated in this function since they are coding them when calling
762 static public function getGroupListSelector(&$params) {
764 $params['offset'] = ($params['page'] - 1) * $params['rp'];
765 $params['rowCount'] = $params['rp'];
766 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
769 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
771 //skip total if we are making call to show only children
772 if (empty($params['parent_id'])) {
774 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
776 // get all the groups
777 $allGroups = CRM_Core_PseudoConstant
::allGroup();
780 // format params and add links
781 $groupList = array();
782 foreach ($groups as $id => $value) {
784 $group['group_id'] = $value['id'];
785 $group['count'] = $value['count'];
786 $group['title'] = $value['title'];
788 // append parent names if in search mode
789 if (empty($params['parent_id']) && !empty($value['parents'])) {
790 $group['parent_id'] = $value['parents'];
791 $groupIds = explode(',', $value['parents']);
793 foreach ($groupIds as $gId) {
794 $title[] = $allGroups[$gId];
796 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
797 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
799 $group['DT_RowId'] = 'row_' . $value['id'];
800 if (empty($params['parentsOnly'])) {
801 foreach ($value['class'] as $id => $class) {
802 if ($class == 'crm-group-parent') {
803 unset($value['class'][$id]);
807 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
808 $group['DT_RowAttr'] = array();
809 $group['DT_RowAttr']['data-id'] = $value['id'];
810 $group['DT_RowAttr']['data-entity'] = 'group';
812 $group['description'] = CRM_Utils_Array
::value('description', $value);
814 if (!empty($value['group_type'])) {
815 $group['group_type'] = $value['group_type'];
818 $group['group_type'] = '';
821 $group['visibility'] = $value['visibility'];
822 $group['links'] = $value['action'];
823 $group['org_info'] = CRM_Utils_Array
::value('org_info', $value);
824 $group['created_by'] = CRM_Utils_Array
::value('created_by', $value);
826 $group['is_parent'] = $value['is_parent'];
828 array_push($groupList, $group);
832 $groupsDT['data'] = $groupList;
833 $groupsDT['recordsTotal'] = !empty($params['total']) ?
$params['total'] : NULL;
834 $groupsDT['recordsFiltered'] = !empty($params['total']) ?
$params['total'] : NULL;
840 * This function to get list of groups.
842 * @param array $params
843 * Associated array for params.
847 public static function getGroupList(&$params) {
848 $whereClause = self
::whereClause($params, FALSE);
851 if (!empty($params['rowCount']) &&
852 $params['rowCount'] > 0
854 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
857 $orderBy = ' ORDER BY groups.title asc';
858 if (!empty($params['sort'])) {
859 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
861 // CRM-16905 - Sort by count cannot be done with sql
862 if (strpos($params['sort'], 'count') === 0) {
863 $orderBy = $limit = '';
867 $select = $from = $where = "";
869 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
870 CRM_Core_Permission
::isMultisiteEnabled()
872 $select = ", contact.display_name as org_name, contact.id as org_id";
873 $from = " LEFT JOIN civicrm_group_organization gOrg
874 ON gOrg.group_id = groups.id
875 LEFT JOIN civicrm_contact contact
876 ON contact.id = gOrg.organization_id ";
878 //get the Organization ID
879 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive');
881 $where = " AND gOrg.organization_id = {$orgID}";
888 SELECT groups.*, createdBy.sort_name as created_by {$select}
889 FROM civicrm_group groups
890 LEFT JOIN civicrm_contact createdBy
891 ON createdBy.id = groups.created_id
893 WHERE $whereClause {$where}
897 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
899 //FIXME CRM-4418, now we are handling delete separately
900 //if we introduce 'delete for group' make sure to handle here.
901 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
902 if (CRM_Core_Permission
::check('edit groups')) {
903 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
904 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
908 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
910 $links = self
::actionLinks();
912 $allTypes = CRM_Core_OptionGroup
::values('group_type');
915 $visibility = CRM_Core_SelectValues
::ufVisibility();
917 while ($object->fetch()) {
919 $values[$object->id
] = array(
923 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
925 if ($object->saved_search_id
) {
926 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
927 // check if custom search, if so fix view link
928 $customSearchID = CRM_Core_DAO
::getFieldValue(
929 'CRM_Contact_DAO_SavedSearch',
930 $object->saved_search_id
,
934 if ($customSearchID) {
935 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
936 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
940 $action = array_sum(array_keys($newLinks));
943 if (array_key_exists('is_reserved', $object)) {
944 //if group is reserved and I don't have reserved permission, suppress delete/edit
945 if ($object->is_reserved
&& !$reservedPermission) {
946 $action -= CRM_Core_Action
::DELETE
;
947 $action -= CRM_Core_Action
::UPDATE
;
948 $action -= CRM_Core_Action
::DISABLE
;
952 if (array_key_exists('is_active', $object)) {
953 if ($object->is_active
) {
954 $action -= CRM_Core_Action
::ENABLE
;
957 $values[$object->id
]['class'][] = 'disabled';
958 $action -= CRM_Core_Action
::VIEW
;
959 $action -= CRM_Core_Action
::DISABLE
;
963 $action = $action & CRM_Core_Action
::mask($groupPermissions);
965 $values[$object->id
]['visibility'] = $visibility[$values[$object->id
]['visibility']];
967 if (isset($values[$object->id
]['group_type'])) {
968 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
969 substr($values[$object->id
]['group_type'], 1, -1)
972 foreach ($groupTypes as $type) {
973 $types[] = CRM_Utils_Array
::value($type, $allTypes);
975 $values[$object->id
]['group_type'] = implode(', ', $types);
977 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
981 'ssid' => $object->saved_search_id
,
985 'group.selector.row',
990 // If group has children, add class for link to view children
991 $values[$object->id
]['is_parent'] = FALSE;
992 if (array_key_exists('children', $values[$object->id
])) {
993 $values[$object->id
]['class'][] = "crm-group-parent";
994 $values[$object->id
]['is_parent'] = TRUE;
997 // If group is a child, add child class
998 if (array_key_exists('parents', $values[$object->id
])) {
999 $values[$object->id
]['class'][] = "crm-group-child";
1003 if ($object->org_id
) {
1004 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
1005 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
1008 $values[$object->id
]['org_info'] = ''; // Empty cell
1012 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
1014 if ($object->created_id
) {
1015 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
1016 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
1019 // get group contact count using Contact.GetCount API
1020 $values[$object->id
]['count'] = civicrm_api3('Contact', 'getcount', array('group' => $object->id
));
1023 // CRM-16905 - Sort by count cannot be done with sql
1024 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1025 usort($values, function($a, $b) {
1026 return $a['count'] - $b['count'];
1028 if (strpos($params['sort'], 'desc')) {
1029 $values = array_reverse($values, TRUE);
1031 return array_slice($values, $params['offset'], $params['rowCount']);
1038 * This function to get hierarchical list of groups (parent followed by children)
1040 * @param array $groupIDs
1041 * Array of group ids.
1043 * @param NULL $parents
1044 * @param string $spacer
1045 * @param bool $titleOnly
1049 public static function getGroupsHierarchy(
1052 $spacer = '<span class="child-indent"></span>',
1055 if (empty($groupIDs)) {
1059 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1060 // <span class="child-icon"></span>
1061 // need to return id, title (w/ spacer), description, visibility
1063 // We need to build a list of tags ordered by hierarchy and sorted by
1064 // name. The hierarchy will be communicated by an accumulation of
1065 // separators in front of the name to give it a visual offset.
1066 // Instead of recursively making mysql queries, we'll make one big
1067 // query and build the hierarchy with the algorithm below.
1069 $args = array(1 => array($groupIdString, 'String'));
1071 SELECT id, title, description, visibility, parents
1073 WHERE id IN $groupIdString
1076 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1077 $parentArray = explode(',', $parents);
1078 $parent = $parentArray[0];
1079 $args[2] = array($parent, 'Integer');
1080 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1082 $query .= " ORDER BY title";
1083 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1085 // Sort the groups into the correct storage by the parent
1086 // $roots represent the current leaf nodes that need to be checked for
1087 // children. $rows represent the unplaced nodes
1088 // $tree contains the child nodes based on their parent_id.
1091 while ($dao->fetch()) {
1092 if ($dao->parents
) {
1093 $parentArray = explode(',', $dao->parents
);
1094 $parent = $parentArray[0];
1095 $tree[$parent][] = array(
1097 'title' => $dao->title
,
1098 'visibility' => $dao->visibility
,
1099 'description' => $dao->description
,
1105 'title' => $dao->title
,
1106 'visibility' => $dao->visibility
,
1107 'description' => $dao->description
,
1113 $hierarchy = array();
1114 for ($i = 0; $i < count($roots); $i++
) {
1115 self
::buildGroupHierarchy($hierarchy, $roots[$i], $tree, $titleOnly, $spacer, 0);
1121 * Build a list with groups on alphabetical order and child groups after the parent group.
1123 * This is a recursive function filling the $hierarchy parameter.
1132 private static function buildGroupHierarchy(&$hierarchy, $group, $tree, $titleOnly, $spacer, $level) {
1133 $spaces = str_repeat($spacer, $level);
1136 $hierarchy[$group['id']] = $spaces . $group['title'];
1139 $hierarchy[$group['id']] = array(
1140 'title' => $spaces . $group['title'],
1141 'description' => $group['description'],
1142 'visibility' => $group['visibility'],
1146 // For performance reasons we use a for loop rather than a foreach.
1147 // Metrics for performance in an installation with 2867 groups a foreach
1148 // caused the function getGroupsHierarchy with a foreach execution takes
1149 // around 2.2 seoonds (2,200 ms).
1150 // Changing to a for loop execustion takes around 0.02 seconds (20 ms).
1151 if (isset($tree[$group['id']]) && is_array($tree[$group['id']])) {
1152 for ($i = 0; $i < count($tree[$group['id']]); $i++
) {
1153 self
::buildGroupHierarchy($hierarchy, $tree[$group['id']][$i], $tree, $titleOnly, $spacer, $level +
1);
1159 * @param array $params
1161 * @return NULL|string
1163 public static function getGroupCount(&$params) {
1164 $whereClause = self
::whereClause($params, FALSE);
1165 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1167 if (!empty($params['created_by'])) {
1169 INNER JOIN civicrm_contact createdBy
1170 ON createdBy.id = groups.created_id";
1173 WHERE {$whereClause}";
1174 return CRM_Core_DAO
::singleValueQuery($query, $params);
1178 * Generate permissioned where clause for group search.
1179 * @param array $params
1180 * @param bool $sortBy
1181 * @param bool $excludeHidden
1185 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1187 $title = CRM_Utils_Array
::value('title', $params);
1189 $clauses[] = "groups.title LIKE %1";
1190 if (strpos($title, '%') !== FALSE) {
1191 $params[1] = array($title, 'String', FALSE);
1194 $params[1] = array($title, 'String', TRUE);
1198 $groupType = CRM_Utils_Array
::value('group_type', $params);
1200 $types = explode(',', $groupType);
1201 if (!empty($types)) {
1202 $clauses[] = 'groups.group_type LIKE %2';
1203 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1204 $params[2] = array($typeString, 'String', TRUE);
1208 $visibility = CRM_Utils_Array
::value('visibility', $params);
1210 $clauses[] = 'groups.visibility = %3';
1211 $params[3] = array($visibility, 'String');
1214 $groupStatus = CRM_Utils_Array
::value('status', $params);
1216 switch ($groupStatus) {
1218 $clauses[] = 'groups.is_active = 1';
1219 $params[4] = array($groupStatus, 'Integer');
1223 $clauses[] = 'groups.is_active = 0';
1224 $params[4] = array($groupStatus, 'Integer');
1228 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1233 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1235 $clauses[] = 'groups.parents IS NULL';
1238 // only show child groups of a specific parent group
1239 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1241 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1242 $params[5] = array($parent_id, 'Integer');
1245 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1246 $clauses[] = "createdBy.sort_name LIKE %6";
1247 if (strpos($createdBy, '%') !== FALSE) {
1248 $params[6] = array($createdBy, 'String', FALSE);
1251 $params[6] = array($createdBy, 'String', TRUE);
1255 if (empty($clauses)) {
1256 $clauses[] = 'groups.is_active = 1';
1259 if ($excludeHidden) {
1260 $clauses[] = 'groups.is_hidden = 0';
1263 $clauses[] = self
::getPermissionClause();
1265 return implode(' AND ', $clauses);
1269 * Define action links.
1272 * array of action links
1274 public static function actionLinks() {
1276 CRM_Core_Action
::VIEW
=> array(
1277 'name' => ts('Contacts'),
1278 'url' => 'civicrm/group/search',
1279 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1280 'title' => ts('Group Contacts'),
1282 CRM_Core_Action
::UPDATE
=> array(
1283 'name' => ts('Settings'),
1284 'url' => 'civicrm/group',
1285 'qs' => 'reset=1&action=update&id=%%id%%',
1286 'title' => ts('Edit Group'),
1288 CRM_Core_Action
::DISABLE
=> array(
1289 'name' => ts('Disable'),
1290 'ref' => 'crm-enable-disable',
1291 'title' => ts('Disable Group'),
1293 CRM_Core_Action
::ENABLE
=> array(
1294 'name' => ts('Enable'),
1295 'ref' => 'crm-enable-disable',
1296 'title' => ts('Enable Group'),
1298 CRM_Core_Action
::DELETE
=> array(
1299 'name' => ts('Delete'),
1300 'url' => 'civicrm/group',
1301 'qs' => 'reset=1&action=delete&id=%%id%%',
1302 'title' => ts('Delete Group'),
1310 * @param $whereClause
1311 * @param array $whereParams
1315 public function pagerAtoZ($whereClause, $whereParams) {
1317 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1318 FROM civicrm_group groups
1320 ORDER BY LEFT(groups.title, 1)
1322 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1324 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);
1328 * Assign Test Value.
1330 * @param string $fieldName
1331 * @param array $fieldDef
1332 * @param int $counter
1334 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1335 if ($fieldName == 'children' ||
$fieldName == 'parents') {
1336 $this->{$fieldName} = "NULL";
1339 parent
::assignTestValues($fieldName, $fieldDef, $counter);
1344 * Get child group ids
1346 * @param array $regularGroupIDs
1351 public static function getChildGroupIds($regularGroupIDs) {
1352 $childGroupIDs = array();
1354 foreach ($regularGroupIDs as $regularGroupID) {
1355 // temporary store the child group ID(s) of regular group identified by $id,
1356 // later merge with main child group array
1357 $tempChildGroupIDs = array();
1358 // check that the regular group has any child group, if not then continue
1359 if ($childrenFound = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $regularGroupID, 'children')) {
1360 $tempChildGroupIDs[] = $childrenFound;
1365 // as civicrm_group.children stores multiple group IDs in comma imploded string format,
1366 // so we need to convert it into array of child group IDs first
1367 $tempChildGroupIDs = explode(',', implode(',', $tempChildGroupIDs));
1368 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1369 // recursively fetch the child group IDs
1370 while (count($tempChildGroupIDs)) {
1371 $tempChildGroupIDs = self
::getChildGroupIds($tempChildGroupIDs);
1372 if (count($tempChildGroupIDs)) {
1373 $childGroupIDs = array_merge($childGroupIDs, $tempChildGroupIDs);
1378 return $childGroupIDs;