3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 class CRM_Contact_BAO_Group
extends CRM_Contact_DAO_Group
{
40 function __construct() {
41 parent
::__construct();
45 * Takes a bunch of params that are needed to match certain criteria and
46 * retrieves the relevant objects. Typically the valid params are only
47 * group_id. We'll tweak this function to be more full featured over a period
48 * of time. This is the inverse function of create. It also stores all the retrieved
49 * values in the default array
51 * @param array $params (reference ) an assoc array of name/value pairs
52 * @param array $defaults (reference ) an assoc array to hold the flattened values
54 * @return object CRM_Contact_BAO_Group object
58 static function retrieve(&$params, &$defaults) {
59 $group = new CRM_Contact_DAO_Group();
60 $group->copyValues($params);
61 if ($group->find(TRUE)) {
62 CRM_Core_DAO
::storeValues($group, $defaults);
70 * Function to delete the group and all the object that connect to
71 * this group. Incredibly destructive
73 * @param int $id group id
80 static function discard($id) {
81 CRM_Utils_Hook
::pre('delete', 'Group', $id, CRM_Core_DAO
::$_nullArray);
83 $transaction = new CRM_Core_Transaction();
85 // added for CRM-1631 and CRM-1794
86 // delete all subscribed mails with the selected group id
87 $subscribe = new CRM_Mailing_Event_DAO_Subscribe();
88 $subscribe->group_id
= $id;
91 // delete all Subscription records with the selected group id
92 $subHistory = new CRM_Contact_DAO_SubscriptionHistory();
93 $subHistory->group_id
= $id;
94 $subHistory->delete();
96 // delete all crm_group_contact records with the selected group id
97 $groupContact = new CRM_Contact_DAO_GroupContact();
98 $groupContact->group_id
= $id;
99 $groupContact->delete();
101 // make all the 'add_to_group_id' field of 'civicrm_uf_group table', pointing to this group, as null
102 $params = array(1 => array($id, 'Integer'));
103 $query = "UPDATE civicrm_uf_group SET `add_to_group_id`= NULL WHERE `add_to_group_id` = %1";
104 CRM_Core_DAO
::executeQuery($query, $params);
106 $query = "UPDATE civicrm_uf_group SET `limit_listings_group_id`= NULL WHERE `limit_listings_group_id` = %1";
107 CRM_Core_DAO
::executeQuery($query, $params);
109 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
111 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
112 CRM_Core_DAO
::executeQuery($query, $params);
114 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
115 CRM_Core_DAO
::executeQuery($query, $params);
117 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
118 CRM_Core_DAO
::executeQuery($query, $params);
120 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
123 // clear any descendant groups cache if exists
124 $finalGroups = CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
127 // delete from group table
128 $group = new CRM_Contact_DAO_Group();
132 $transaction->commit();
134 CRM_Utils_Hook
::post('delete', 'Group', $id, $group);
136 // delete the recently created Group
137 $groupRecent = array(
141 CRM_Utils_Recent
::del($groupRecent);
145 * Returns an array of the contacts in the given group.
148 static function getGroupContacts($id) {
149 $params = array(array('group', 'IN', array($id => 1), 0, 0));
150 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, array('contact_id'));
155 * Get the count of a members in a group with the specific status
157 * @param int $id group id
158 * @param enum $status status of members in group
160 * @return int count of members in the group with above status
163 static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
164 $groupContact = new CRM_Contact_DAO_GroupContact();
165 $groupIds = array($id);
166 if ($countChildGroups) {
167 $groupIds = CRM_Contact_BAO_GroupNesting
::getDescendentGroupIds($groupIds);
171 $contacts = self
::getGroupContacts($id);
173 foreach ($groupIds as $groupId) {
175 $groupContacts = self
::getGroupContacts($groupId);
176 foreach ($groupContacts as $gcontact) {
177 if ($groupId != $id) {
178 // Loop through main group's contacts
179 // and subtract from the count for each contact which
180 // matches one in the present group, if it is not the
182 foreach ($contacts as $contact) {
183 if ($contact['contact_id'] == $gcontact['contact_id']) {
189 $groupContact->group_id
= $groupId;
190 if (isset($status)) {
191 $groupContact->status
= $status;
193 $groupContact->_query
['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
194 $count +
= $groupContact->count();
200 * Get the list of member for a group id
202 * @param int $lngGroupId this is group id
204 * @return array $aMembers this arrray contains the list of members for this group id
208 static function &getMember($groupID, $useCache = TRUE) {
209 $params = array(array('group', 'IN', array($groupID => 1), 0, 0));
210 $returnProperties = array('contact_id');
211 list($contacts, $_) = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, 0, $useCache);
214 foreach ($contacts as $contact) {
215 $aMembers[$contact['contact_id']] = 1;
222 * Returns array of group object(s) matching a set of one or Group properties.
224 * @param array $param Array of one or more valid property_name=>value pairs.
225 * Limits the set of groups returned.
226 * @param array $returnProperties Which properties should be included in the returned group objects.
227 * (member_count should be last element.)
229 * @return An array of group objects.
233 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
234 * add in essential fields (e.g. id). This should follow a regular pattern like the others
236 static function getGroups(
238 $returnProperties = NULL,
243 $dao = new CRM_Contact_DAO_Group();
244 if (!isset($params['is_active'])) {
248 foreach ($params as $k => $v) {
249 if ($k == 'name' ||
$k == 'title') {
250 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO
::escapeString($v) . '"');
252 elseif ($k == 'group_type') {
253 foreach ((array) $v as $type) {
254 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO
::VALUE_SEPARATOR
. (int) $type . CRM_Core_DAO
::VALUE_SEPARATOR
. "%'");
257 elseif (is_array($v)) {
258 foreach ($v as &$num) {
261 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
269 if ($offset ||
$rowCount) {
270 $offset = ($offset > 0) ?
$offset : 0;
271 $rowCount = ($rowCount > 0) ?
$rowCount : 25;
272 $dao->limit($offset, $rowCount);
276 $dao->orderBy($sort);
279 // return only specific fields if returnproperties are sent
280 if (!empty($returnProperties)) {
282 $dao->selectAdd(implode(',', $returnProperties));
286 $flag = $returnProperties && in_array('member_count', $returnProperties) ?
1 : 0;
289 while ($dao->fetch()) {
290 $group = new CRM_Contact_DAO_Group();
292 $dao->member_count
= CRM_Contact_BAO_Group
::memberCount($dao->id
);
294 $groups[] = clone($dao);
300 * make sure that the user has permission to access this group
302 * @param int $id the id of the object
304 * @return string the permission that the user has (or null)
308 static function checkPermission($id) {
309 $allGroups = CRM_Core_PseudoConstant
::allGroup();
312 if (CRM_Core_Permission
::check('edit all contacts') ||
313 CRM_ACL_API
::groupPermission(CRM_ACL_API
::EDIT
, $id, NULL,
314 'civicrm_saved_search', $allGroups
317 $permissions[] = CRM_Core_Permission
::EDIT
;
320 if (CRM_Core_Permission
::check('view all contacts') ||
321 CRM_ACL_API
::groupPermission(CRM_ACL_API
::VIEW
, $id, NULL,
322 'civicrm_saved_search', $allGroups
325 $permissions[] = CRM_Core_Permission
::VIEW
;
328 if (!empty($permissions) && CRM_Core_Permission
::check('delete contacts')) {
329 // Note: using !empty() in if condition, restricts the scope of delete
330 // permission to groups/contacts that are editable/viewable.
331 // We can remove this !empty condition once we have ACL support for delete functionality.
332 $permissions[] = CRM_Core_Permission
::DELETE
;
341 * @param array $params Associative array of parameters
343 * @return object|null The new group BAO (if created)
347 public static function &create(&$params) {
349 if (CRM_Utils_Array
::value('id', $params)) {
350 CRM_Utils_Hook
::pre('edit', 'Group', $params['id'], $params);
353 CRM_Utils_Hook
::pre('create', 'Group', NULL, $params);
356 // form the name only if missing: CRM-627
357 if (!CRM_Utils_Array
::value('name', $params) &&
358 !CRM_Utils_Array
::value('id', $params)
360 $params['name'] = CRM_Utils_String
::titleToVar($params['title']);
363 // convert params if array type
364 if (isset($params['group_type'])) {
365 if (is_array($params['group_type'])) {
366 $params['group_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
367 array_keys($params['group_type'])
368 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
372 $params['group_type'] = '';
375 $session = CRM_Core_Session
::singleton( );
376 if ($cid = $session->get('userID')) {
377 $params['created_id'] = $cid;
380 $group = new CRM_Contact_BAO_Group();
381 $group->copyValues($params);
382 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
383 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
384 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
385 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
386 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
387 if(isset($group->parents
) && is_array($group->parents
)) {
388 $group->parents
= CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
389 array_keys($group->parents
)
390 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
392 if (!CRM_Utils_Array
::value('id', $params)) {
393 $group->name
.= "_tmp";
401 if (!CRM_Utils_Array
::value('id', $params)) {
402 $group->name
= substr($group->name
, 0, -4) . "_{$group->id}";
405 $group->buildClause();
408 // add custom field values
409 if (CRM_Utils_Array
::value('custom', $params)) {
410 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_group', $group->id
);
413 // make the group, child of domain/site group by default.
414 $domainGroupID = CRM_Core_BAO_Domain
::getGroupId();
415 if (CRM_Utils_Array
::value('no_parent', $params) !== 1) {
416 if (empty($params['parents']) &&
417 $domainGroupID != $group->id
&&
418 CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
421 !CRM_Contact_BAO_GroupNesting
::hasParentGroups($group->id
)
423 // if no parent present and the group doesn't already have any parents,
424 // make sure site group goes as parent
425 $params['parents'] = array($domainGroupID => 1);
427 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
428 $params['parents'] = array($params['parents'] => 1);
431 if (!empty($params['parents'])) {
432 foreach ($params['parents'] as $parentId => $dnc) {
433 if ($parentId && !CRM_Contact_BAO_GroupNesting
::isParentChild($parentId, $group->id
)) {
434 CRM_Contact_BAO_GroupNesting
::add($parentId, $group->id
);
439 // clear any descendant groups cache if exists
440 $finalGroups = CRM_Core_BAO_Cache
::deleteGroup('descendant groups for an org');
442 // this is always required, since we don't know when a
443 // parent group is removed
444 CRM_Contact_BAO_GroupNestingCache
::update();
446 // update group contact cache for all parent groups
447 $parentIds = CRM_Contact_BAO_GroupNesting
::getParentGroupIds($group->id
);
448 foreach ($parentIds as $parentId) {
449 CRM_Contact_BAO_GroupContactCache
::add($parentId);
453 if (CRM_Utils_Array
::value('organization_id', $params)) {
456 $groupOrg['group_id'] = $group->id
;
457 CRM_Contact_BAO_GroupOrganization
::add($groupOrg);
460 CRM_Contact_BAO_GroupContactCache
::add($group->id
);
462 if (CRM_Utils_Array
::value('id', $params)) {
463 CRM_Utils_Hook
::post('edit', 'Group', $group->id
, $group);
466 CRM_Utils_Hook
::post('create', 'Group', $group->id
, $group);
469 $recentOther = array();
470 if (CRM_Core_Permission
::check('edit groups')) {
471 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=update&id=' . $group->id
);
472 // currently same permission we are using for delete a group
473 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id
);
476 // add the recently added group (unless hidden: CRM-6432)
477 if (!$group->is_hidden
) {
478 CRM_Utils_Recent
::add($group->title
,
479 CRM_Utils_System
::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id
),
491 * given a saved search compute the clause and the tables
492 * and store it for future use
494 function buildClause() {
495 $params = array(array('group', 'IN', array($this->id
=> 1), 0, 0));
497 if (!empty($params)) {
498 $tables = $whereTables = array();
499 $this->where_clause
= CRM_Contact_BAO_Query
::getWhereClause($params, NULL, $tables, $whereTables);
500 if (!empty($tables)) {
501 $this->select_tables
= serialize($tables);
503 if (!empty($whereTables)) {
504 $this->where_tables
= serialize($whereTables);
512 * Defines a new smart group
514 * @param array $params Associative array of parameters
516 * @return object|null The new group BAO (if created)
520 public static function createSmartGroup(&$params) {
521 if (CRM_Utils_Array
::value('formValues', $params)) {
523 unset($ssParams['id']);
524 if (isset($ssParams['saved_search_id'])) {
525 $ssParams['id'] = $ssParams['saved_search_id'];
528 $savedSearch = CRM_Contact_BAO_SavedSearch
::create($params);
530 $params['saved_search_id'] = $savedSearch->id
;
536 return self
::create($params);
540 * update the is_active flag in the db
542 * @param int $id id of the database record
543 * @param boolean $isActive value we want to set the is_active field
545 * @return Object DAO object on sucess, null otherwise
548 static function setIsActive($id, $isActive) {
549 return CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
553 * build the condition to retrieve groups.
555 * @param string $groupType type of group(Access/Mailing) OR the key of the group
556 * @param boolen $excludeHidden exclude hidden groups.
558 * @return string $condition
561 static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
563 if ($groupType == 'Mailing') {
564 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '2' . CRM_Core_DAO
::VALUE_SEPARATOR
;
566 elseif ($groupType == 'Access') {
567 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. '1' . CRM_Core_DAO
::VALUE_SEPARATOR
;
569 elseif (!empty($groupType)){
570 // ie we have been given the group key
571 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. $groupType . CRM_Core_DAO
::VALUE_SEPARATOR
;
575 if ($excludeHidden) {
576 $condition = "is_hidden = 0";
581 $condition .= " AND group_type LIKE '%$value%'";
584 $condition = "group_type LIKE '%$value%'";
591 public function __toString() {
596 * This function create the hidden smart group when user perform
597 * contact seach and want to send mailing to search contacts.
599 * @param array $params ( reference ) an assoc array of name/value pairs
601 * @return array ( smartGroupId, ssId ) smart group id and saved search id
605 static function createHiddenSmartGroup($params) {
606 $ssId = CRM_Utils_Array
::value('saved_search_id', $params);
608 //add mapping record only for search builder saved search
610 if ($params['search_context'] == 'builder') {
611 //save the mapping for search builder
613 //save record in mapping table
615 $mappingParams = array('mapping_type' => 'Search Builder');
616 $mapping = CRM_Core_BAO_Mapping
::add($mappingParams, $temp);
617 $mappingId = $mapping->id
;
620 //get the mapping id from saved search
621 $savedSearch = new CRM_Contact_BAO_SavedSearch();
622 $savedSearch->id
= $ssId;
623 $savedSearch->find(TRUE);
624 $mappingId = $savedSearch->mapping_id
;
627 //save mapping fields
628 CRM_Core_BAO_Mapping
::saveMappingFields($params['form_values'], $mappingId);
631 //create/update saved search record.
632 $savedSearch = new CRM_Contact_BAO_SavedSearch();
633 $savedSearch->id
= $ssId;
634 $savedSearch->form_values
= serialize($params['form_values']);
635 $savedSearch->mapping_id
= $mappingId;
636 $savedSearch->search_custom_id
= CRM_Utils_Array
::value('search_custom_id', $params);
637 $savedSearch->save();
639 $ssId = $savedSearch->id
;
644 $smartGroupId = NULL;
645 if (CRM_Utils_Array
::value('saved_search_id', $params)) {
646 $smartGroupId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
649 //create group only when new saved search.
650 $groupParams = array(
651 'title' => "Hidden Smart Group {$ssId}",
652 'is_active' => CRM_Utils_Array
::value('is_active', $params, 1),
653 'is_hidden' => CRM_Utils_Array
::value('is_hidden', $params, 1),
654 'group_type' => CRM_Utils_Array
::value('group_type', $params),
655 'visibility' => CRM_Utils_Array
::value('visibility', $params),
656 'saved_search_id' => $ssId,
659 $smartGroup = self
::create($groupParams);
660 $smartGroupId = $smartGroup->id
;
663 return array($smartGroupId, $ssId);
667 * This function is a wrapper for ajax group selector
669 * @param array $params associated array for params record id.
671 * @return array $groupList associated array of group list
674 public function getGroupListSelector(&$params) {
676 $params['offset'] = ($params['page'] - 1) * $params['rp'];
677 $params['rowCount'] = $params['rp'];
678 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
681 $groups = CRM_Contact_BAO_Group
::getGroupList($params);
683 //skip total if we are making call to show only children
684 if ( !CRM_Utils_Array
::value('parent_id', $params) ) {
686 $params['total'] = CRM_Contact_BAO_Group
::getGroupCount($params);
688 // get all the groups
689 $allGroups = CRM_Core_PseudoConstant
::allGroup();
692 // format params and add links
693 $groupList = array();
694 if (!empty($groups)) {
695 foreach ($groups as $id => $value) {
696 $groupList[$id]['group_id'] = $value['id'];
697 $groupList[$id]['group_name'] = $value['title'];
698 $groupList[$id]['class'] = $value['class'];
700 // append parent names if in search mode
701 if ( !CRM_Utils_Array
::value('parent_id', $params) &&
702 CRM_Utils_Array
::value( 'parents', $value ) ) {
703 $groupIds = explode(',', $value['parents']);
705 foreach($groupIds as $gId) {
706 $title[] = $allGroups[$gId];
708 $groupList[$id]['group_name'] .= '<div class="crm-row-parent-name"><em>'.ts('Child of').'</em>: ' . implode(', ', $title) . '</div>';
709 $groupList[$id]['class'] = '';
712 $groupList[$id]['group_description'] = CRM_Utils_Array
::value('description', $value);
713 if ( CRM_Utils_Array
::value('group_type', $value) ) {
714 $groupList[$id]['group_type'] = $value['group_type'];
717 $groupList[$id]['group_type'] = '';
719 $groupList[$id]['visibility'] = $value['visibility'];
720 $groupList[$id]['links'] = $value['action'];
721 $groupList[$id]['org_info'] = CRM_Utils_Array
::value('org_info', $value);
722 $groupList[$id]['created_by'] = CRM_Utils_Array
::value('created_by', $value);
724 $groupList[$id]['is_parent'] = $value['is_parent'];
731 * This function to get list of groups
733 * @param array $params associated array for params
736 static function getGroupList(&$params) {
737 $config = CRM_Core_Config
::singleton();
739 $whereClause = self
::whereClause($params, FALSE);
741 //$this->pagerAToZ( $whereClause, $params );
743 if (!empty($params['rowCount']) &&
744 $params['rowCount'] > 0
746 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
749 $orderBy = ' ORDER BY groups.title asc';
750 if (!empty($params['sort'])) {
751 $orderBy = ' ORDER BY ' . CRM_Utils_Type
::escape($params['sort'], 'String');
754 $select = $from = $where = "";
756 if (CRM_Core_Permission
::check('administer Multiple Organizations') &&
757 CRM_Core_Permission
::isMultisiteEnabled()
759 $select = ", contact.display_name as org_name, contact.id as org_id";
760 $from = " LEFT JOIN civicrm_group_organization gOrg
761 ON gOrg.group_id = groups.id
762 LEFT JOIN civicrm_contact contact
763 ON contact.id = gOrg.organization_id ";
765 //get the Organization ID
766 $orgID = CRM_Utils_Request
::retrieve('oid', 'Positive', CRM_Core_DAO
::$_nullObject);
768 $where = " AND gOrg.organization_id = {$orgID}";
775 SELECT groups.*, createdBy.sort_name as created_by {$select}
776 FROM civicrm_group groups
777 LEFT JOIN civicrm_contact createdBy
778 ON createdBy.id = groups.created_id
780 WHERE $whereClause {$where}
784 $object = CRM_Core_DAO
::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
786 //FIXME CRM-4418, now we are handling delete separately
787 //if we introduce 'delete for group' make sure to handle here.
788 $groupPermissions = array(CRM_Core_Permission
::VIEW
);
789 if (CRM_Core_Permission
::check('edit groups')) {
790 $groupPermissions[] = CRM_Core_Permission
::EDIT
;
791 $groupPermissions[] = CRM_Core_Permission
::DELETE
;
795 $reservedPermission = CRM_Core_Permission
::check('administer reserved groups');
797 $links = self
::actionLinks();
799 $allTypes = CRM_Core_OptionGroup
::values('group_type');
802 while ($object->fetch()) {
803 $permission = CRM_Contact_BAO_Group
::checkPermission($object->id
, $object->title
);
804 //@todo CRM-12209 introduced an ACL check in the whereClause function
805 // it may be that this checking is now obsolete - or that what remains
806 // should be removed to the whereClause (which is also accessed by getCount)
810 $values[$object->id
] = array();
811 CRM_Core_DAO
::storeValues($object, $values[$object->id
]);
812 if ($object->saved_search_id
) {
813 $values[$object->id
]['title'] .= ' (' . ts('Smart Group') . ')';
814 // check if custom search, if so fix view link
815 $customSearchID = CRM_Core_DAO
::getFieldValue(
816 'CRM_Contact_DAO_SavedSearch',
817 $object->saved_search_id
,
821 if ($customSearchID) {
822 $newLinks[CRM_Core_Action
::VIEW
]['url'] = 'civicrm/contact/search/custom';
823 $newLinks[CRM_Core_Action
::VIEW
]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
827 $action = array_sum(array_keys($newLinks));
830 if (array_key_exists('is_reserved', $object)) {
831 //if group is reserved and I don't have reserved permission, suppress delete/edit
832 if ($object->is_reserved
&& !$reservedPermission) {
833 $action -= CRM_Core_Action
::DELETE
;
834 $action -= CRM_Core_Action
::UPDATE
;
835 $action -= CRM_Core_Action
::DISABLE
;
839 $values[$object->id
]['class'] = '';
840 if (array_key_exists('is_active', $object)) {
841 if ($object->is_active
) {
842 $action -= CRM_Core_Action
::ENABLE
;
845 $values[$object->id
]['class'] = 'disabled';
846 $action -= CRM_Core_Action
::VIEW
;
847 $action -= CRM_Core_Action
::DISABLE
;
851 $action = $action & CRM_Core_Action
::mask($groupPermissions);
853 $values[$object->id
]['visibility'] = CRM_Contact_DAO_Group
::tsEnum('visibility',
854 $values[$object->id
]['visibility']
856 if (isset($values[$object->id
]['group_type'])) {
857 $groupTypes = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
858 substr($values[$object->id
]['group_type'], 1, -1)
861 foreach ($groupTypes as $type) {
862 $types[] = CRM_Utils_Array
::value($type, $allTypes);
864 $values[$object->id
]['group_type'] = implode(', ', $types);
866 $values[$object->id
]['action'] = CRM_Core_Action
::formLink($newLinks,
870 'ssid' => $object->saved_search_id
,
874 // If group has children, add class for link to view children
875 $values[$object->id
]['is_parent'] = false;
876 if (array_key_exists('children', $values[$object->id
])) {
877 $values[$object->id
]['class'] = "crm-group-parent";
878 $values[$object->id
]['is_parent'] = true;
881 // If group is a child, add child class
882 if (array_key_exists('parents', $values[$object->id
])) {
883 $values[$object->id
]['class'] = "crm-group-child";
886 if (array_key_exists('children', $values[$object->id
])
887 && array_key_exists('parents', $values[$object->id
])) {
888 $values[$object->id
]['class'] = "crm-group-child crm-group-parent";
892 if ($object->org_id
) {
893 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
894 $values[$object->id
]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
897 $values[$object->id
]['org_info'] = ''; // Empty cell
901 $values[$object->id
]['org_info'] = NULL; // Collapsed column if all cells are NULL
903 if ($object->created_id
) {
904 $contactUrl = CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
905 $values[$object->id
]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
914 * This function to get hierarchical list of groups (parent followed by children)
916 * @param array $groupIDs array of group ids
920 static function getGroupsHierarchy (
923 $spacer = '<span class="child-indent"></span>',
926 if (empty($groupIDs)) {
930 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
931 // <span class="child-icon"></span>
932 // need to return id, title (w/ spacer), description, visibility
934 // We need to build a list of tags ordered by hierarchy and sorted by
935 // name. The heirarchy will be communicated by an accumulation of
936 // separators in front of the name to give it a visual offset.
937 // Instead of recursively making mysql queries, we'll make one big
938 // query and build the heirarchy with the algorithm below.
940 $args = array(1 => array($groupIdString, 'String'));
942 SELECT id, title, description, visibility, parents
944 WHERE id IN $groupIdString
947 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
948 $parentArray = explode(',', $parents);
949 $parent = $parentArray[0];
950 $args[2] = array($parent, 'Integer');
951 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
953 $query .= " ORDER BY title";
954 $dao = CRM_Core_DAO
::executeQuery($query, $args);
956 // Sort the groups into the correct storage by the parent
957 // $roots represent the current leaf nodes that need to be checked for
958 // children. $rows represent the unplaced nodes
959 $roots = $rows = $allGroups = array();
960 while ($dao->fetch()) {
961 $allGroups[$dao->id
] = array('title' => $dao->title
,
962 'visibility' => $dao->visibility
,
963 'description' => $dao->description
);
965 if ($dao->parents
== $parents) {
966 $roots[] = array('id' => $dao->id
,
968 'title' => $dao->title
);
971 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
972 $parentArray = explode(',', $dao->parents
);
973 $parent = $parentArray[0];
974 $rows[] = array('id' => $dao->id
,
976 'title' => $dao->title
,
977 'parents' => $parent);
981 // While we have nodes left to build, shift the first (alphabetically)
982 // node of the list, place it in our groups list and loop through the
983 // list of unplaced nodes to find its children. We make a copy to
984 // iterate through because we must modify the unplaced nodes list
986 while (count($roots)) {
987 $new_roots = array();
988 $current_rows = $rows;
989 $root = array_shift($roots);
990 $groups[$root['id']] = array($root['prefix'], $root['title']);
992 // As you find the children, append them to the end of the new set
993 // of roots (maintain alphabetical ordering). Also remove the node
994 // from the set of unplaced nodes.
995 if (is_array($current_rows)) {
996 foreach ($current_rows as $key => $row) {
997 if ($row['parents'] == $root['id']) {
998 $new_roots[] = array('id' => $row['id'], 'prefix' => $groups[$root['id']][0] . $spacer, 'title' => $row['title']);
1004 //As a group, insert the new roots into the beginning of the roots
1005 //list. This maintains the hierarchical ordering of the tags.
1006 $roots = array_merge($new_roots, $roots);
1009 // Prefix titles with the calcuated spacing to give the visual
1010 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1011 $groupsReturn = array();
1012 foreach ($groups as $key=>$value) {
1014 $groupsReturn[$key] = $value[0] . $value[1];
1016 $groupsReturn[$key] = array(
1017 'title' => $value[0] . $value[1],
1018 'description' => $allGroups[$key]['description'],
1019 'visibility' => $allGroups[$key]['visibility'],
1024 return $groupsReturn;
1027 static function getGroupCount(&$params) {
1028 $whereClause = self
::whereClause($params, FALSE);
1029 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1031 if (CRM_Utils_Array
::value('created_by', $params)) {
1033 INNER JOIN civicrm_contact createdBy
1034 ON createdBy.id = groups.created_id";
1037 WHERE {$whereClause}";
1038 return CRM_Core_DAO
::singleValueQuery($query, $params);
1041 function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1045 $title = CRM_Utils_Array
::value('title', $params);
1047 $clauses[] = "groups.title LIKE %1";
1048 if (strpos($title, '%') !== FALSE) {
1049 $params[1] = array($title, 'String', FALSE);
1052 $params[1] = array($title, 'String', TRUE);
1056 $groupType = CRM_Utils_Array
::value('group_type', $params);
1058 $types = explode(',', $groupType);
1059 if (!empty($types)) {
1060 $clauses[] = 'groups.group_type LIKE %2';
1061 $typeString = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $types) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1062 $params[2] = array($typeString, 'String', TRUE);
1066 $visibility = CRM_Utils_Array
::value('visibility', $params);
1068 $clauses[] = 'groups.visibility = %3';
1069 $params[3] = array($visibility, 'String');
1072 $groupStatus = CRM_Utils_Array
::value('status', $params);
1074 switch ($groupStatus) {
1076 $clauses[] = 'groups.is_active = 1';
1077 $params[4] = array($groupStatus, 'Integer');
1081 $clauses[] = 'groups.is_active = 0';
1082 $params[4] = array($groupStatus, 'Integer');
1086 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1091 $parentsOnly = CRM_Utils_Array
::value('parentsOnly', $params);
1093 $clauses[] = 'groups.parents IS NULL';
1096 // only show child groups of a specific parent group
1097 $parent_id = CRM_Utils_Array
::value('parent_id', $params);
1099 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1100 $params[5] = array($parent_id, 'Integer');
1103 if ($createdBy = CRM_Utils_Array
::value('created_by', $params)) {
1104 $clauses[] = "createdBy.sort_name LIKE %6";
1105 if (strpos($createdBy, '%') !== FALSE) {
1106 $params[6] = array($createdBy, 'String', FALSE);
1109 $params[6] = array($createdBy, 'String', TRUE);
1115 $this->_sortByCharacter !== null ) {
1117 "groups.title LIKE '" .
1118 strtolower(CRM_Core_DAO::escapeWildCardString($this->_sortByCharacter)) .
1122 // dont do a the below assignement when doing a
1123 // AtoZ pager clause
1125 if ( count( $clauses ) > 1 ) {
1126 $this->assign( 'isSearch', 1 );
1128 $this->assign( 'isSearch', 0 );
1134 if (empty($clauses)) {
1135 $clauses[] = 'groups.is_active = 1';
1138 if ($excludeHidden) {
1139 $clauses[] = 'groups.is_hidden = 0';
1142 if (!CRM_Core_Permission
::check('view all contacts')) {
1143 //get the allowed groups for the current user
1144 $groups = CRM_ACL_API
::group(CRM_ACL_API
::VIEW
);
1145 if (!empty( $groups)) {
1146 $groupList = implode( ', ', array_values( $groups ) );
1147 $clauses[] = "groups.id IN ( $groupList ) ";
1151 return implode(' AND ', $clauses);
1155 * Function to define action links
1157 * @return array $links array of action links
1160 static function actionLinks() {
1162 CRM_Core_Action
::VIEW
=> array(
1163 'name' => ts('Contacts'),
1164 'url' => 'civicrm/group/search',
1165 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1166 'title' => ts('Group Contacts'),
1168 CRM_Core_Action
::UPDATE
=> array(
1169 'name' => ts('Settings'),
1170 'url' => 'civicrm/group',
1171 'qs' => 'reset=1&action=update&id=%%id%%',
1172 'title' => ts('Edit Group'),
1174 CRM_Core_Action
::DISABLE
=> array(
1175 'name' => ts('Disable'),
1176 'extra' => 'onclick = "enableDisable( %%id%%,\'' . 'CRM_Contact_BAO_Group' . '\',\'' . 'enable-disable' . '\' );"',
1177 'ref' => 'disable-action',
1178 'title' => ts('Disable Group'),
1180 CRM_Core_Action
::ENABLE
=> array(
1181 'name' => ts('Enable'),
1182 'extra' => 'onclick = "enableDisable( %%id%%,\'' . 'CRM_Contact_BAO_Group' . '\',\'' . 'disable-enable' . '\' );"',
1183 'ref' => 'enable-action',
1184 'title' => ts('Enable Group'),
1186 CRM_Core_Action
::DELETE
=> array(
1187 'name' => ts('Delete'),
1188 'url' => 'civicrm/group',
1189 'qs' => 'reset=1&action=delete&id=%%id%%',
1190 'title' => ts('Delete Group'),
1197 function pagerAtoZ($whereClause, $whereParams) {
1199 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1200 FROM civicrm_group groups
1202 ORDER BY LEFT(groups.title, 1)
1204 $dao = CRM_Core_DAO
::executeQuery($query, $whereParams);
1206 return CRM_Utils_PagerAToZ
::getAToZBar($dao, $this->_sortByCharacter
, TRUE);