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