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