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