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