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