Merge pull request #258 from colemanw/groupEdit
[civicrm-core.git] / CRM / Contact / BAO / Group.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35 class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group {
36
37 /**
38 * class constructor
39 */
40 function __construct() {
41 parent::__construct();
42 }
43
44 /**
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
50 *
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
53 *
54 * @return object CRM_Contact_BAO_Group object
55 * @access public
56 * @static
57 */
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);
63 return $group;
64 }
65
66 return NULL;
67 }
68
69 /**
70 * Function to delete the group and all the object that connect to
71 * this group. Incredibly destructive
72 *
73 * @param int $id group id
74 *
75 * @return null
76 * @access public
77 * @static
78 *
79 */
80 static function discard($id) {
81 CRM_Utils_Hook::pre('delete', 'Group', $id, CRM_Core_DAO::$_nullArray);
82
83 $transaction = new CRM_Core_Transaction();
84
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;
89 $subscribe->delete();
90
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();
95
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();
100
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);
105
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);
108
109 // make sure u delete all the entries from civicrm_mailing_group and civicrm_campaign_group
110 // CRM-6186
111 $query = "DELETE FROM civicrm_mailing_group where entity_table = 'civicrm_group' AND entity_id = %1";
112 CRM_Core_DAO::executeQuery($query, $params);
113
114 $query = "DELETE FROM civicrm_campaign_group where entity_table = 'civicrm_group' AND entity_id = %1";
115 CRM_Core_DAO::executeQuery($query, $params);
116
117 $query = "DELETE FROM civicrm_acl_entity_role where entity_table = 'civicrm_group' AND entity_id = %1";
118 CRM_Core_DAO::executeQuery($query, $params);
119
120 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
121 'is_enabled'
122 )) {
123 // clear any descendant groups cache if exists
124 $finalGroups = CRM_Core_BAO_Cache::deleteGroup('descendant groups for an org');
125 }
126
127 // delete from group table
128 $group = new CRM_Contact_DAO_Group();
129 $group->id = $id;
130 $group->delete();
131
132 $transaction->commit();
133
134 CRM_Utils_Hook::post('delete', 'Group', $id, $group);
135
136 // delete the recently created Group
137 $groupRecent = array(
138 'id' => $id,
139 'type' => 'Group',
140 );
141 CRM_Utils_Recent::del($groupRecent);
142 }
143
144 /**
145 * Returns an array of the contacts in the given group.
146 *
147 */
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'));
151 return $contacts;
152 }
153
154 /**
155 * Get the count of a members in a group with the specific status
156 *
157 * @param int $id group id
158 * @param enum $status status of members in group
159 *
160 * @return int count of members in the group with above status
161 * @access public
162 */
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);
168 }
169 $count = 0;
170
171 $contacts = self::getGroupContacts($id);
172
173 foreach ($groupIds as $groupId) {
174
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
181 // main group
182 foreach ($contacts as $contact) {
183 if ($contact['contact_id'] == $gcontact['contact_id']) {
184 $count--;
185 }
186 }
187 }
188 }
189 $groupContact->group_id = $groupId;
190 if (isset($status)) {
191 $groupContact->status = $status;
192 }
193 $groupContact->_query['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
194 $count += $groupContact->count();
195 }
196 return $count;
197 }
198
199 /**
200 * Get the list of member for a group id
201 *
202 * @param int $lngGroupId this is group id
203 *
204 * @return array $aMembers this arrray contains the list of members for this group id
205 * @access public
206 * @static
207 */
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);
212
213 $aMembers = array();
214 foreach ($contacts as $contact) {
215 $aMembers[$contact['contact_id']] = 1;
216 }
217
218 return $aMembers;
219 }
220
221 /**
222 * Returns array of group object(s) matching a set of one or Group properties.
223 *
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.)
228 *
229 * @return An array of group objects.
230 *
231 * @access public
232 *
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
235 */
236 static function getGroups(
237 $params = NULL,
238 $returnProperties = NULL,
239 $sort = NULL,
240 $offset = NULL,
241 $rowCount = NULL
242 ) {
243 $dao = new CRM_Contact_DAO_Group();
244 $dao->is_active = 1;
245 if ($params) {
246 foreach ($params as $k => $v) {
247 if ($k == 'name' || $k == 'title') {
248 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO::escapeString($v) . '"');
249 }
250 elseif (is_array($v)) {
251 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
252 }
253 else {
254 $dao->$k = $v;
255 }
256 }
257 }
258
259 if ($offset || $rowCount) {
260 $offset = ($offset > 0) ? $offset : 0;
261 $rowCount = ($rowCount > 0) ? $rowCount : 25;
262 $dao->limit($offset, $rowCount);
263 }
264
265 if ($sort) {
266 $dao->orderBy($sort);
267 }
268
269 // return only specific fields if returnproperties are sent
270 if (!empty($returnProperties)) {
271 $dao->selectAdd();
272 $dao->selectAdd(implode(',', $returnProperties));
273 }
274 $dao->find();
275
276 $flag = $returnProperties && in_array('member_count', $returnProperties) ? 1 : 0;
277
278 $groups = array();
279 while ($dao->fetch()) {
280 $group = new CRM_Contact_DAO_Group();
281 if ($flag) {
282 $dao->member_count = CRM_Contact_BAO_Group::memberCount($dao->id);
283 }
284 $groups[] = clone($dao);
285 }
286 return $groups;
287 }
288
289 /**
290 * make sure that the user has permission to access this group
291 *
292 * @param int $id the id of the object
293 *
294 * @return string the permission that the user has (or null)
295 * @access public
296 * @static
297 */
298 static function checkPermission($id) {
299 $allGroups = CRM_Core_PseudoConstant::allGroup();
300
301 $permissions = NULL;
302 if (CRM_Core_Permission::check('edit all contacts') ||
303 CRM_ACL_API::groupPermission(CRM_ACL_API::EDIT, $id, NULL,
304 'civicrm_saved_search', $allGroups
305 )
306 ) {
307 $permissions[] = CRM_Core_Permission::EDIT;
308 }
309
310 if (CRM_Core_Permission::check('view all contacts') ||
311 CRM_ACL_API::groupPermission(CRM_ACL_API::VIEW, $id, NULL,
312 'civicrm_saved_search', $allGroups
313 )
314 ) {
315 $permissions[] = CRM_Core_Permission::VIEW;
316 }
317
318 if (!empty($permissions) && CRM_Core_Permission::check('delete contacts')) {
319 // Note: using !empty() in if condition, restricts the scope of delete
320 // permission to groups/contacts that are editable/viewable.
321 // We can remove this !empty condition once we have ACL support for delete functionality.
322 $permissions[] = CRM_Core_Permission::DELETE;
323 }
324
325 return $permissions;
326 }
327
328 /**
329 * Create a new group
330 *
331 * @param array $params Associative array of parameters
332 *
333 * @return object|null The new group BAO (if created)
334 * @access public
335 * @static
336 */
337 public static function &create(&$params) {
338
339 if (CRM_Utils_Array::value('id', $params)) {
340 CRM_Utils_Hook::pre('edit', 'Group', $params['id'], $params);
341 }
342 else {
343 CRM_Utils_Hook::pre('create', 'Group', NULL, $params);
344 }
345
346 // form the name only if missing: CRM-627
347 if (!CRM_Utils_Array::value('name', $params) &&
348 !CRM_Utils_Array::value('id', $params)
349 ) {
350 $params['name'] = CRM_Utils_String::titleToVar($params['title']);
351 }
352
353 // convert params if array type
354 if (isset($params['group_type'])) {
355 if (is_array($params['group_type'])) {
356 $params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
357 array_keys($params['group_type'])
358 ) . CRM_Core_DAO::VALUE_SEPARATOR;
359 }
360 }
361 else {
362 $params['group_type'] = '';
363 }
364
365 $session = CRM_Core_Session::singleton( );
366 if ($cid = $session->get('userID')) {
367 $params['created_id'] = $cid;
368 }
369
370 $group = new CRM_Contact_BAO_Group();
371 $group->copyValues($params);
372
373 if (!CRM_Utils_Array::value('id', $params)) {
374 $group->name .= "_tmp";
375 }
376 $group->save();
377
378 if (!$group->id) {
379 return NULL;
380 }
381
382 if (!CRM_Utils_Array::value('id', $params)) {
383 $group->name = substr($group->name, 0, -4) . "_{$group->id}";
384 }
385
386 $group->buildClause();
387 $group->save();
388
389 // add custom field values
390 if (CRM_Utils_Array::value('custom', $params)) {
391 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_group', $group->id);
392 }
393
394 // make the group, child of domain/site group by default.
395 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
396 if (CRM_Utils_Array::value('no_parent', $params) !== 1) {
397 if (empty($params['parents']) &&
398 $domainGroupID != $group->id &&
399 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
400 'is_enabled'
401 ) &&
402 !CRM_Contact_BAO_GroupNesting::hasParentGroups($group->id)
403 ) {
404 // if no parent present and the group doesn't already have any parents,
405 // make sure site group goes as parent
406 $params['parents'] = array($domainGroupID => 1);
407 }
408 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
409 $params['parents'] = array($params['parents'] => 1);
410 }
411
412 if (!empty($params['parents'])) {
413 foreach ($params['parents'] as $parentId => $dnc) {
414 if ($parentId && !CRM_Contact_BAO_GroupNesting::isParentChild($parentId, $group->id)) {
415 CRM_Contact_BAO_GroupNesting::add($parentId, $group->id);
416 }
417 }
418 }
419
420 // clear any descendant groups cache if exists
421 $finalGroups = CRM_Core_BAO_Cache::deleteGroup('descendant groups for an org');
422
423 // this is always required, since we don't know when a
424 // parent group is removed
425 CRM_Contact_BAO_GroupNestingCache::update();
426
427 // update group contact cache for all parent groups
428 $parentIds = CRM_Contact_BAO_GroupNesting::getParentGroupIds($group->id);
429 foreach ($parentIds as $parentId) {
430 CRM_Contact_BAO_GroupContactCache::add($parentId);
431 }
432 }
433
434 if (CRM_Utils_Array::value('organization_id', $params)) {
435 $groupOrg = array();
436 $groupOrg = $params;
437 $groupOrg['group_id'] = $group->id;
438 CRM_Contact_BAO_GroupOrganization::add($groupOrg);
439 }
440
441 CRM_Contact_BAO_GroupContactCache::add($group->id);
442
443 if (CRM_Utils_Array::value('id', $params)) {
444 CRM_Utils_Hook::post('edit', 'Group', $group->id, $group);
445 }
446 else {
447 CRM_Utils_Hook::post('create', 'Group', $group->id, $group);
448 }
449
450 $recentOther = array();
451 if (CRM_Core_Permission::check('edit groups')) {
452 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=update&id=' . $group->id);
453 // currently same permission we are using for delete a group
454 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id);
455 }
456
457 // add the recently added group (unless hidden: CRM-6432)
458 if (!$group->is_hidden) {
459 CRM_Utils_Recent::add($group->title,
460 CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id),
461 $group->id,
462 'Group',
463 NULL,
464 NULL,
465 $recentOther
466 );
467 }
468 return $group;
469 }
470
471 /**
472 * given a saved search compute the clause and the tables
473 * and store it for future use
474 */
475 function buildClause() {
476 $params = array(array('group', 'IN', array($this->id => 1), 0, 0));
477
478 if (!empty($params)) {
479 $tables = $whereTables = array();
480 $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
481 if (!empty($tables)) {
482 $this->select_tables = serialize($tables);
483 }
484 if (!empty($whereTables)) {
485 $this->where_tables = serialize($whereTables);
486 }
487 }
488
489 return;
490 }
491
492 /**
493 * Defines a new smart group
494 *
495 * @param array $params Associative array of parameters
496 *
497 * @return object|null The new group BAO (if created)
498 * @access public
499 * @static
500 */
501 public static function createSmartGroup(&$params) {
502 if (CRM_Utils_Array::value('formValues', $params)) {
503 $ssParams = $params;
504 unset($ssParams['id']);
505 if (isset($ssParams['saved_search_id'])) {
506 $ssParams['id'] = $ssParams['saved_search_id'];
507 }
508
509 $savedSearch = CRM_Contact_BAO_SavedSearch::create($params);
510
511 $params['saved_search_id'] = $savedSearch->id;
512 }
513 else {
514 return NULL;
515 }
516
517 return self::create($params);
518 }
519
520 /**
521 * update the is_active flag in the db
522 *
523 * @param int $id id of the database record
524 * @param boolean $isActive value we want to set the is_active field
525 *
526 * @return Object DAO object on sucess, null otherwise
527 * @static
528 */
529 static function setIsActive($id, $isActive) {
530 return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
531 }
532
533 /**
534 * build the condition to retrieve groups.
535 *
536 * @param string $groupType type of group(Access/Mailing) OR the key of the group
537 * @param boolen $excludeHidden exclude hidden groups.
538 *
539 * @return string $condition
540 * @static
541 */
542 static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
543 $value = NULL;
544 if ($groupType == 'Mailing') {
545 $value = CRM_Core_DAO::VALUE_SEPARATOR . '2' . CRM_Core_DAO::VALUE_SEPARATOR;
546 }
547 elseif ($groupType == 'Access') {
548 $value = CRM_Core_DAO::VALUE_SEPARATOR . '1' . CRM_Core_DAO::VALUE_SEPARATOR;
549 }
550 elseif (!empty($groupType)){
551 // ie we have been given the group key
552 $value = CRM_Core_DAO::VALUE_SEPARATOR . $groupType . CRM_Core_DAO::VALUE_SEPARATOR;
553 }
554
555 $condition = NULL;
556 if ($excludeHidden) {
557 $condition = "is_hidden = 0";
558 }
559
560 if ($value) {
561 if ($condition) {
562 $condition .= " AND group_type LIKE '%$value%'";
563 }
564 else {
565 $condition = "group_type LIKE '%$value%'";
566 }
567 }
568
569 return $condition;
570 }
571
572 public function __toString() {
573 return $this->title;
574 }
575
576 /**
577 * This function create the hidden smart group when user perform
578 * contact seach and want to send mailing to search contacts.
579 *
580 * @param array $params ( reference ) an assoc array of name/value pairs
581 *
582 * @return array ( smartGroupId, ssId ) smart group id and saved search id
583 * @access public
584 * @static
585 */
586 static function createHiddenSmartGroup($params) {
587 $ssId = CRM_Utils_Array::value('saved_search_id', $params);
588
589 //add mapping record only for search builder saved search
590 $mappingId = NULL;
591 if ($params['search_context'] == 'builder') {
592 //save the mapping for search builder
593 if (!$ssId) {
594 //save record in mapping table
595 $temp = array();
596 $mappingParams = array('mapping_type' => 'Search Builder');
597 $mapping = CRM_Core_BAO_Mapping::add($mappingParams, $temp);
598 $mappingId = $mapping->id;
599 }
600 else {
601 //get the mapping id from saved search
602 $savedSearch = new CRM_Contact_BAO_SavedSearch();
603 $savedSearch->id = $ssId;
604 $savedSearch->find(TRUE);
605 $mappingId = $savedSearch->mapping_id;
606 }
607
608 //save mapping fields
609 CRM_Core_BAO_Mapping::saveMappingFields($params['form_values'], $mappingId);
610 }
611
612 //create/update saved search record.
613 $savedSearch = new CRM_Contact_BAO_SavedSearch();
614 $savedSearch->id = $ssId;
615 $savedSearch->form_values = serialize($params['form_values']);
616 $savedSearch->mapping_id = $mappingId;
617 $savedSearch->search_custom_id = CRM_Utils_Array::value('search_custom_id', $params);
618 $savedSearch->save();
619
620 $ssId = $savedSearch->id;
621 if (!$ssId) {
622 return NULL;
623 }
624
625 $smartGroupId = NULL;
626 if (CRM_Utils_Array::value('saved_search_id', $params)) {
627 $smartGroupId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
628 }
629 else {
630 //create group only when new saved search.
631 $groupParams = array(
632 'title' => "Hidden Smart Group {$ssId}",
633 'is_active' => CRM_Utils_Array::value('is_active', $params, 1),
634 'is_hidden' => CRM_Utils_Array::value('is_hidden', $params, 1),
635 'group_type' => CRM_Utils_Array::value('group_type', $params),
636 'visibility' => CRM_Utils_Array::value('visibility', $params),
637 'saved_search_id' => $ssId,
638 );
639
640 $smartGroup = self::create($groupParams);
641 $smartGroupId = $smartGroup->id;
642 }
643
644 return array($smartGroupId, $ssId);
645 }
646
647 /**
648 * This function is a wrapper for ajax group selector
649 *
650 * @param array $params associated array for params record id.
651 *
652 * @return array $groupList associated array of group list
653 * @access public
654 */
655 public function getGroupListSelector(&$params) {
656 // format the params
657 $params['offset'] = ($params['page'] - 1) * $params['rp'];
658 $params['rowCount'] = $params['rp'];
659 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
660
661 // get groups
662 $groups = CRM_Contact_BAO_Group::getGroupList($params);
663
664 //skip total if we are making call to show only children
665 if ( !CRM_Utils_Array::value('parent_id', $params) ) {
666 // add total
667 $params['total'] = CRM_Contact_BAO_Group::getGroupCount($params);
668
669 // get all the groups
670 $allGroups = CRM_Core_PseudoConstant::allGroup();
671 }
672
673 // format params and add links
674 $groupList = array();
675 if (!empty($groups)) {
676 foreach ($groups as $id => $value) {
677 $groupList[$id]['group_id'] = $value['id'];
678 $groupList[$id]['group_name'] = $value['title'];
679 $groupList[$id]['class'] = $value['class'];
680
681 // append parent names if in search mode
682 if ( !CRM_Utils_Array::value('parent_id', $params) &&
683 CRM_Utils_Array::value( 'parents', $value ) ) {
684 $groupIds = explode(',', $value['parents']);
685 $title = array();
686 foreach($groupIds as $gId) {
687 $title[] = $allGroups[$gId];
688 }
689 $groupList[$id]['group_name'] .= '<div class="crm-row-parent-name"><em>'.ts('Child of').'</em>: ' . implode(', ', $title) . '</div>';
690 $groupList[$id]['class'] = '';
691 }
692
693 $groupList[$id]['group_description'] = CRM_Utils_Array::value('description', $value);
694 if ( CRM_Utils_Array::value('group_type', $value) ) {
695 $groupList[$id]['group_type'] = $value['group_type'];
696 }
697 else {
698 $groupList[$id]['group_type'] = '';
699 }
700 $groupList[$id]['visibility'] = $value['visibility'];
701 $groupList[$id]['links'] = $value['action'];
702 $groupList[$id]['org_info'] = CRM_Utils_Array::value('org_info', $value);
703 $groupList[$id]['created_by'] = CRM_Utils_Array::value('created_by', $value);
704
705 $groupList[$id]['is_parent'] = $value['is_parent'];
706 }
707 return $groupList;
708 }
709 }
710
711 /**
712 * This function to get list of groups
713 *
714 * @param array $params associated array for params
715 * @access public
716 */
717 static function getGroupList(&$params) {
718 $config = CRM_Core_Config::singleton();
719
720 $whereClause = self::whereClause($params, FALSE);
721
722 //$this->pagerAToZ( $whereClause, $params );
723
724 if (!empty($params['rowCount']) &&
725 $params['rowCount'] > 0
726 ) {
727 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
728 }
729
730 $orderBy = ' ORDER BY groups.title asc';
731 if (CRM_Utils_Array::value('sort', $params)) {
732 $orderBy = ' ORDER BY ' . CRM_Utils_Array::value('sort', $params);
733 }
734
735 $select = $from = $where = "";
736 $groupOrg = FALSE;
737 if (CRM_Core_Permission::check('administer Multiple Organizations') &&
738 CRM_Core_Permission::isMultisiteEnabled()
739 ) {
740 $select = ", contact.display_name as org_name, contact.id as org_id";
741 $from = " LEFT JOIN civicrm_group_organization gOrg
742 ON gOrg.group_id = groups.id
743 LEFT JOIN civicrm_contact contact
744 ON contact.id = gOrg.organization_id ";
745
746 //get the Organization ID
747 $orgID = CRM_Utils_Request::retrieve('oid', 'Positive', CRM_Core_DAO::$_nullObject);
748 if ($orgID) {
749 $where = " AND gOrg.organization_id = {$orgID}";
750 }
751
752 $groupOrg = TRUE;
753 }
754
755 $query = "
756 SELECT groups.*, createdBy.sort_name as created_by {$select}
757 FROM civicrm_group groups
758 LEFT JOIN civicrm_contact createdBy
759 ON createdBy.id = groups.created_id
760 {$from}
761 WHERE $whereClause {$where}
762 {$orderBy}
763 {$limit}";
764
765 $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
766
767 //FIXME CRM-4418, now we are handling delete separately
768 //if we introduce 'delete for group' make sure to handle here.
769 $groupPermissions = array(CRM_Core_Permission::VIEW);
770 if (CRM_Core_Permission::check('edit groups')) {
771 $groupPermissions[] = CRM_Core_Permission::EDIT;
772 $groupPermissions[] = CRM_Core_Permission::DELETE;
773 }
774
775 // CRM-9936
776 $reservedPermission = CRM_Core_Permission::check('administer reserved groups');
777
778 $links = self::actionLinks();
779
780 $allTypes = CRM_Core_OptionGroup::values('group_type');
781 $values = array();
782
783 while ($object->fetch()) {
784 $permission = CRM_Contact_BAO_Group::checkPermission($object->id, $object->title);
785 //@todo CRM-12209 introduced an ACL check in the whereClause function
786 // it may be that this checking is now obsolete - or that what remains
787 // should be removed to the whereClause (which is also accessed by getCount)
788
789 if ($permission) {
790 $newLinks = $links;
791 $values[$object->id] = array();
792 CRM_Core_DAO::storeValues($object, $values[$object->id]);
793 if ($object->saved_search_id) {
794 $values[$object->id]['title'] .= ' (' . ts('Smart Group') . ')';
795 // check if custom search, if so fix view link
796 $customSearchID = CRM_Core_DAO::getFieldValue(
797 'CRM_Contact_DAO_SavedSearch',
798 $object->saved_search_id,
799 'search_custom_id'
800 );
801
802 if ($customSearchID) {
803 $newLinks[CRM_Core_Action::VIEW]['url'] = 'civicrm/contact/search/custom';
804 $newLinks[CRM_Core_Action::VIEW]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
805 }
806 }
807
808 $action = array_sum(array_keys($newLinks));
809
810 // CRM-9936
811 if (array_key_exists('is_reserved', $object)) {
812 //if group is reserved and I don't have reserved permission, suppress delete/edit
813 if ($object->is_reserved && !$reservedPermission) {
814 $action -= CRM_Core_Action::DELETE;
815 $action -= CRM_Core_Action::UPDATE;
816 $action -= CRM_Core_Action::DISABLE;
817 }
818 }
819
820 $values[$object->id]['class'] = '';
821 if (array_key_exists('is_active', $object)) {
822 if ($object->is_active) {
823 $action -= CRM_Core_Action::ENABLE;
824 }
825 else {
826 $values[$object->id]['class'] = 'disabled';
827 $action -= CRM_Core_Action::VIEW;
828 $action -= CRM_Core_Action::DISABLE;
829 }
830 }
831
832 $action = $action & CRM_Core_Action::mask($groupPermissions);
833
834 $values[$object->id]['visibility'] = CRM_Contact_DAO_Group::tsEnum('visibility',
835 $values[$object->id]['visibility']
836 );
837 if (isset($values[$object->id]['group_type'])) {
838 $groupTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
839 substr($values[$object->id]['group_type'], 1, -1)
840 );
841 $types = array();
842 foreach ($groupTypes as $type) {
843 $types[] = CRM_Utils_Array::value($type, $allTypes);
844 }
845 $values[$object->id]['group_type'] = implode(', ', $types);
846 }
847 $values[$object->id]['action'] = CRM_Core_Action::formLink($newLinks,
848 $action,
849 array(
850 'id' => $object->id,
851 'ssid' => $object->saved_search_id,
852 )
853 );
854
855 // If group has children, add class for link to view children
856 $values[$object->id]['is_parent'] = false;
857 if (array_key_exists('children', $values[$object->id])) {
858 $values[$object->id]['class'] = "crm-group-parent";
859 $values[$object->id]['is_parent'] = true;
860 }
861
862 // If group is a child, add child class
863 if (array_key_exists('parents', $values[$object->id])) {
864 $values[$object->id]['class'] = "crm-group-child";
865 }
866
867 if (array_key_exists('children', $values[$object->id])
868 && array_key_exists('parents', $values[$object->id])) {
869 $values[$object->id]['class'] = "crm-group-child crm-group-parent";
870 }
871
872 if ($groupOrg) {
873 if ($object->org_id) {
874 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
875 $values[$object->id]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
876 }
877 else {
878 $values[$object->id]['org_info'] = ''; // Empty cell
879 }
880 }
881 else {
882 $values[$object->id]['org_info'] = NULL; // Collapsed column if all cells are NULL
883 }
884 if ($object->created_id) {
885 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
886 $values[$object->id]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
887 }
888 }
889 }
890
891 return $values;
892 }
893
894 /**
895 * This function to get hierarchical list of groups (parent followed by children)
896 *
897 * @param array $groupIDs array of group ids
898 *
899 * @access public
900 */
901 static function getGroupsHierarchy (
902 $groupIDs,
903 $parents = NULL,
904 $spacer = '<span class="child-indent"></span>',
905 $titleOnly = FALSE
906 ) {
907 if (empty($groupIDs)) {
908 return array();
909 }
910
911 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
912 // <span class="child-icon"></span>
913 // need to return id, title (w/ spacer), description, visibility
914
915 // We need to build a list of tags ordered by hierarchy and sorted by
916 // name. The heirarchy will be communicated by an accumulation of
917 // separators in front of the name to give it a visual offset.
918 // Instead of recursively making mysql queries, we'll make one big
919 // query and build the heirarchy with the algorithm below.
920 $groups = array();
921 $args = array(1 => array($groupIdString, 'String'));
922 $query = "
923 SELECT id, title, description, visibility, parents
924 FROM civicrm_group
925 WHERE id IN $groupIdString
926 ";
927 if ($parents) {
928 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
929 $parentArray = explode(',', $parents);
930 $parent = $parentArray[0];
931 $args[2] = array($parent, 'Integer');
932 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
933 }
934 $query .= " ORDER BY title";
935 $dao = CRM_Core_DAO::executeQuery($query, $args);
936
937 // Sort the groups into the correct storage by the parent
938 // $roots represent the current leaf nodes that need to be checked for
939 // children. $rows represent the unplaced nodes
940 $roots = $rows = $allGroups = array();
941 while ($dao->fetch()) {
942 $allGroups[$dao->id] = array('title' => $dao->title,
943 'visibility' => $dao->visibility,
944 'description' => $dao->description);
945
946 if ($dao->parents == $parents) {
947 $roots[] = array('id' => $dao->id,
948 'prefix' => '',
949 'title' => $dao->title);
950 }
951 else {
952 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
953 $parentArray = explode(',', $dao->parents);
954 $parent = $parentArray[0];
955 $rows[] = array('id' => $dao->id,
956 'prefix' => '',
957 'title' => $dao->title,
958 'parents' => $parent);
959 }
960 }
961 $dao->free();
962 // While we have nodes left to build, shift the first (alphabetically)
963 // node of the list, place it in our groups list and loop through the
964 // list of unplaced nodes to find its children. We make a copy to
965 // iterate through because we must modify the unplaced nodes list
966 // during the loop.
967 while (count($roots)) {
968 $new_roots = array();
969 $current_rows = $rows;
970 $root = array_shift($roots);
971 $groups[$root['id']] = array($root['prefix'], $root['title']);
972
973 // As you find the children, append them to the end of the new set
974 // of roots (maintain alphabetical ordering). Also remove the node
975 // from the set of unplaced nodes.
976 if (is_array($current_rows)) {
977 foreach ($current_rows as $key => $row) {
978 if ($row['parents'] == $root['id']) {
979 $new_roots[] = array('id' => $row['id'], 'prefix' => $groups[$root['id']][0] . $spacer, 'title' => $row['title']);
980 unset($rows[$key]);
981 }
982 }
983 }
984
985 //As a group, insert the new roots into the beginning of the roots
986 //list. This maintains the hierarchical ordering of the tags.
987 $roots = array_merge($new_roots, $roots);
988 }
989
990 // Prefix titles with the calcuated spacing to give the visual
991 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
992 $groupsReturn = array();
993 foreach ($groups as $key=>$value) {
994 if ($titleOnly) {
995 $groupsReturn[$key] = $value[0] . $value[1];
996 } else {
997 $groupsReturn[$key] = array(
998 'title' => $value[0] . $value[1],
999 'description' => $allGroups[$key]['description'],
1000 'visibility' => $allGroups[$key]['visibility'],
1001 );
1002 }
1003 }
1004
1005 return $groupsReturn;
1006 }
1007
1008 static function getGroupCount(&$params) {
1009 $whereClause = self::whereClause($params, FALSE);
1010 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1011
1012 if (CRM_Utils_Array::value('created_by', $params)) {
1013 $query .= "
1014 INNER JOIN civicrm_contact createdBy
1015 ON createdBy.id = groups.created_id";
1016 }
1017 $query .= "
1018 WHERE {$whereClause}";
1019 return CRM_Core_DAO::singleValueQuery($query, $params);
1020 }
1021
1022 function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1023 $values = array();
1024 $clauses = array();
1025
1026 $title = CRM_Utils_Array::value('title', $params);
1027 if ($title) {
1028 $clauses[] = "groups.title LIKE %1";
1029 if (strpos($title, '%') !== FALSE) {
1030 $params[1] = array($title, 'String', FALSE);
1031 }
1032 else {
1033 $params[1] = array($title, 'String', TRUE);
1034 }
1035 }
1036
1037 $groupType = CRM_Utils_Array::value('group_type', $params);
1038 if ($groupType) {
1039 $types = explode(',', $groupType);
1040 if (!empty($types)) {
1041 $clauses[] = 'groups.group_type LIKE %2';
1042 $typeString = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $types) . CRM_Core_DAO::VALUE_SEPARATOR;
1043 $params[2] = array($typeString, 'String', TRUE);
1044 }
1045 }
1046
1047 $visibility = CRM_Utils_Array::value('visibility', $params);
1048 if ($visibility) {
1049 $clauses[] = 'groups.visibility = %3';
1050 $params[3] = array($visibility, 'String');
1051 }
1052
1053 $groupStatus = CRM_Utils_Array::value('status', $params);
1054 if ($groupStatus) {
1055 switch ($groupStatus) {
1056 case 1:
1057 $clauses[] = 'groups.is_active = 1';
1058 $params[4] = array($groupStatus, 'Integer');
1059 break;
1060
1061 case 2:
1062 $clauses[] = 'groups.is_active = 0';
1063 $params[4] = array($groupStatus, 'Integer');
1064 break;
1065
1066 case 3:
1067 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1068 break;
1069 }
1070 }
1071
1072 $parentsOnly = CRM_Utils_Array::value('parentsOnly', $params);
1073 if ($parentsOnly) {
1074 $clauses[] = 'groups.parents IS NULL';
1075 }
1076
1077 // only show child groups of a specific parent group
1078 $parent_id = CRM_Utils_Array::value('parent_id', $params);
1079 if ($parent_id) {
1080 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1081 $params[5] = array($parent_id, 'Integer');
1082 }
1083
1084 if ($createdBy = CRM_Utils_Array::value('created_by', $params)) {
1085 $clauses[] = "createdBy.sort_name LIKE %6";
1086 if (strpos($createdBy, '%') !== FALSE) {
1087 $params[6] = array($createdBy, 'String', FALSE);
1088 }
1089 else {
1090 $params[6] = array($createdBy, 'String', TRUE);
1091 }
1092 }
1093
1094 /*
1095 if ( $sortBy &&
1096 $this->_sortByCharacter !== null ) {
1097 $clauses[] =
1098 "groups.title LIKE '" .
1099 strtolower(CRM_Core_DAO::escapeWildCardString($this->_sortByCharacter)) .
1100 "%'";
1101 }
1102
1103 // dont do a the below assignement when doing a
1104 // AtoZ pager clause
1105 if ( $sortBy ) {
1106 if ( count( $clauses ) > 1 ) {
1107 $this->assign( 'isSearch', 1 );
1108 } else {
1109 $this->assign( 'isSearch', 0 );
1110 }
1111 }
1112 */
1113
1114
1115 if (empty($clauses)) {
1116 $clauses[] = 'groups.is_active = 1';
1117 }
1118
1119 if ($excludeHidden) {
1120 $clauses[] = 'groups.is_hidden = 0';
1121 }
1122 //CRM-12209
1123 if (!CRM_Core_Permission::check('view all contacts')) {
1124 //get the allowed groups for the current user
1125 $groups = CRM_ACL_API::group(CRM_ACL_API::VIEW);
1126 if (!empty( $groups)) {
1127 $groupList = implode( ', ', array_values( $groups ) );
1128 $clauses[] = "groups.id IN ( $groupList ) ";
1129 }
1130 }
1131
1132 return implode(' AND ', $clauses);
1133 }
1134
1135 /**
1136 * Function to define action links
1137 *
1138 * @return array $links array of action links
1139 * @access public
1140 */
1141 static function actionLinks() {
1142 $links = array(
1143 CRM_Core_Action::VIEW => array(
1144 'name' => ts('Contacts'),
1145 'url' => 'civicrm/group/search',
1146 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1147 'title' => ts('Group Contacts'),
1148 ),
1149 CRM_Core_Action::UPDATE => array(
1150 'name' => ts('Settings'),
1151 'url' => 'civicrm/group',
1152 'qs' => 'reset=1&action=update&id=%%id%%',
1153 'title' => ts('Edit Group'),
1154 ),
1155 CRM_Core_Action::DISABLE => array(
1156 'name' => ts('Disable'),
1157 'extra' => 'onclick = "enableDisable( %%id%%,\'' . 'CRM_Contact_BAO_Group' . '\',\'' . 'enable-disable' . '\' );"',
1158 'ref' => 'disable-action',
1159 'title' => ts('Disable Group'),
1160 ),
1161 CRM_Core_Action::ENABLE => array(
1162 'name' => ts('Enable'),
1163 'extra' => 'onclick = "enableDisable( %%id%%,\'' . 'CRM_Contact_BAO_Group' . '\',\'' . 'disable-enable' . '\' );"',
1164 'ref' => 'enable-action',
1165 'title' => ts('Enable Group'),
1166 ),
1167 CRM_Core_Action::DELETE => array(
1168 'name' => ts('Delete'),
1169 'url' => 'civicrm/group',
1170 'qs' => 'reset=1&action=delete&id=%%id%%',
1171 'title' => ts('Delete Group'),
1172 ),
1173 );
1174
1175 return $links;
1176 }
1177
1178 function pagerAtoZ($whereClause, $whereParams) {
1179 $query = "
1180 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1181 FROM civicrm_group groups
1182 WHERE $whereClause
1183 ORDER BY LEFT(groups.title, 1)
1184 ";
1185 $dao = CRM_Core_DAO::executeQuery($query, $whereParams);
1186
1187 return CRM_Utils_PagerAToZ::getAToZBar($dao, $this->_sortByCharacter, TRUE);
1188 }
1189 }
1190