Add in Test to sort sqli
[civicrm-core.git] / CRM / Contact / BAO / Group.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
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) {
6a488035
TO
133 $params = array(array('group', 'IN', array($id => 1), 0, 0));
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
353 // form the name only if missing: CRM-627
e2b7c67d 354 $nameParam = CRM_Utils_Array::value('name', $params, NULL);
8cc574cf 355 if (!$nameParam && empty($params['id'])) {
6a488035
TO
356 $params['name'] = CRM_Utils_String::titleToVar($params['title']);
357 }
358
359 // convert params if array type
360 if (isset($params['group_type'])) {
361 if (is_array($params['group_type'])) {
362 $params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
af3e0975 363 $params['group_type']
353ffa53 364 ) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035 365 }
568fcb22 366 else {
367 $params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $params['group_type'] . CRM_Core_DAO::VALUE_SEPARATOR;
368 }
6a488035
TO
369 }
370 else {
82d7eb3d 371 $params['group_type'] = NULL;
6a488035
TO
372 }
373
481a74f4 374 $session = CRM_Core_Session::singleton();
d0dfb649
PJ
375 $cid = $session->get('userID');
376 // this action is add
377 if ($cid && empty($params['id'])) {
6a488035
TO
378 $params['created_id'] = $cid;
379 }
d0dfb649
PJ
380 // this action is update
381 if ($cid && !empty($params['id'])) {
382 $params['modified_id'] = $cid;
383 }
6a488035 384
d4fba42a
SL
385 // CRM-19068.
386 // Validate parents parameter when creating group.
387 if (isset($params['parents'])) {
388 if (is_array($params['parents'])) {
389 foreach ($params['parents'] as $parent => $dc) {
1514f450 390 if (!CRM_Utils_Type::validate($parent, 'Integer', FALSE)) {
d4fba42a
SL
391 unset($params['parents'][$parent]);
392 }
393 }
394 }
395 else {
1514f450 396 if (!CRM_Utils_Type::validate($params['parents'], 'Integer', FALSE)) {
d4fba42a
SL
397 unset($params['parents']);
398 }
399 }
400 }
6a488035
TO
401 $group = new CRM_Contact_BAO_Group();
402 $group->copyValues($params);
57c93d72
E
403 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
404 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
405 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
406 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
407 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
22e263ad 408 if (isset($group->parents) && is_array($group->parents)) {
57c93d72 409 $group->parents = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
353ffa53
TO
410 array_keys($group->parents)
411 ) . CRM_Core_DAO::VALUE_SEPARATOR;
57c93d72 412 }
a7488080 413 if (empty($params['id']) &&
e2b7c67d 414 !$nameParam
0aab99e7 415 ) {
6a488035
TO
416 $group->name .= "_tmp";
417 }
418 $group->save();
419
420 if (!$group->id) {
421 return NULL;
422 }
423
a7488080 424 if (empty($params['id']) &&
e2b7c67d 425 !$nameParam
0aab99e7 426 ) {
6a488035
TO
427 $group->name = substr($group->name, 0, -4) . "_{$group->id}";
428 }
429
430 $group->buildClause();
431 $group->save();
432
433 // add custom field values
a7488080 434 if (!empty($params['custom'])) {
6a488035
TO
435 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_group', $group->id);
436 }
437
438 // make the group, child of domain/site group by default.
439 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
440 if (CRM_Utils_Array::value('no_parent', $params) !== 1) {
441 if (empty($params['parents']) &&
442 $domainGroupID != $group->id &&
aaffa79f 443 Civi::settings()->get('is_enabled') &&
6a488035
TO
444 !CRM_Contact_BAO_GroupNesting::hasParentGroups($group->id)
445 ) {
446 // if no parent present and the group doesn't already have any parents,
447 // make sure site group goes as parent
448 $params['parents'] = array($domainGroupID => 1);
449 }
450 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
451 $params['parents'] = array($params['parents'] => 1);
452 }
453
454 if (!empty($params['parents'])) {
455 foreach ($params['parents'] as $parentId => $dnc) {
1514f450 456 if (CRM_Utils_Type::validate($parentId, 'Integer', FALSE)) {
d4fba42a
SL
457 if ($parentId && !CRM_Contact_BAO_GroupNesting::isParentChild($parentId, $group->id)) {
458 CRM_Contact_BAO_GroupNesting::add($parentId, $group->id);
459 }
6a488035
TO
460 }
461 }
462 }
463
6a488035
TO
464 // this is always required, since we don't know when a
465 // parent group is removed
466 CRM_Contact_BAO_GroupNestingCache::update();
467
468 // update group contact cache for all parent groups
469 $parentIds = CRM_Contact_BAO_GroupNesting::getParentGroupIds($group->id);
470 foreach ($parentIds as $parentId) {
471 CRM_Contact_BAO_GroupContactCache::add($parentId);
472 }
473 }
474
a7488080 475 if (!empty($params['organization_id'])) {
6a488035
TO
476 $groupOrg = $params;
477 $groupOrg['group_id'] = $group->id;
478 CRM_Contact_BAO_GroupOrganization::add($groupOrg);
479 }
480
430bf241 481 CRM_Utils_System::flushCache();
6a488035
TO
482 CRM_Contact_BAO_GroupContactCache::add($group->id);
483
a7488080 484 if (!empty($params['id'])) {
6a488035
TO
485 CRM_Utils_Hook::post('edit', 'Group', $group->id, $group);
486 }
487 else {
488 CRM_Utils_Hook::post('create', 'Group', $group->id, $group);
489 }
490
491 $recentOther = array();
492 if (CRM_Core_Permission::check('edit groups')) {
493 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=update&id=' . $group->id);
494 // currently same permission we are using for delete a group
495 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id);
496 }
497
498 // add the recently added group (unless hidden: CRM-6432)
499 if (!$group->is_hidden) {
500 CRM_Utils_Recent::add($group->title,
501 CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id),
502 $group->id,
503 'Group',
504 NULL,
505 NULL,
506 $recentOther
507 );
508 }
509 return $group;
510 }
511
512 /**
100fef9d 513 * Given a saved search compute the clause and the tables
6a488035
TO
514 * and store it for future use
515 */
00be9182 516 public function buildClause() {
1dbdc161 517 $params = array(array('group', 'IN', array($this->id), 0, 0));
6a488035
TO
518
519 if (!empty($params)) {
520 $tables = $whereTables = array();
521 $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
522 if (!empty($tables)) {
523 $this->select_tables = serialize($tables);
524 }
525 if (!empty($whereTables)) {
526 $this->where_tables = serialize($whereTables);
527 }
528 }
6a488035
TO
529 }
530
531 /**
fe482240 532 * Defines a new smart group.
6a488035 533 *
77c5b619
TO
534 * @param array $params
535 * Associative array of parameters.
6a488035 536 *
72b3a70c
CW
537 * @return CRM_Contact_BAO_Group|NULL
538 * The new group BAO (if created)
6a488035
TO
539 */
540 public static function createSmartGroup(&$params) {
a7488080 541 if (!empty($params['formValues'])) {
6a488035
TO
542 $ssParams = $params;
543 unset($ssParams['id']);
544 if (isset($ssParams['saved_search_id'])) {
545 $ssParams['id'] = $ssParams['saved_search_id'];
546 }
547
548 $savedSearch = CRM_Contact_BAO_SavedSearch::create($params);
549
550 $params['saved_search_id'] = $savedSearch->id;
551 }
552 else {
553 return NULL;
554 }
555
556 return self::create($params);
557 }
558
559 /**
fe482240 560 * Update the is_active flag in the db.
6a488035 561 *
77c5b619
TO
562 * @param int $id
563 * Id of the database record.
564 * @param bool $isActive
565 * Value we want to set the is_active field.
6a488035 566 *
16b10e64 567 * @return CRM_Core_DAO|null
3f8d2862 568 * DAO object on success, NULL otherwise
6a488035 569 */
00be9182 570 public static function setIsActive($id, $isActive) {
6a488035
TO
571 return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
572 }
573
574 /**
100fef9d 575 * Build the condition to retrieve groups.
6a488035 576 *
77c5b619
TO
577 * @param string $groupType
578 * Type of group(Access/Mailing) OR the key of the group.
3f8d2862 579 * @param bool $excludeHidden exclude hidden groups.
6a488035 580 *
a6c01b45 581 * @return string
6a488035 582 */
00be9182 583 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
6a488035
TO
584 $value = NULL;
585 if ($groupType == 'Mailing') {
586 $value = CRM_Core_DAO::VALUE_SEPARATOR . '2' . CRM_Core_DAO::VALUE_SEPARATOR;
587 }
588 elseif ($groupType == 'Access') {
589 $value = CRM_Core_DAO::VALUE_SEPARATOR . '1' . CRM_Core_DAO::VALUE_SEPARATOR;
590 }
9b873358 591 elseif (!empty($groupType)) {
6a488035
TO
592 // ie we have been given the group key
593 $value = CRM_Core_DAO::VALUE_SEPARATOR . $groupType . CRM_Core_DAO::VALUE_SEPARATOR;
594 }
595
596 $condition = NULL;
597 if ($excludeHidden) {
598 $condition = "is_hidden = 0";
599 }
600
601 if ($value) {
602 if ($condition) {
603 $condition .= " AND group_type LIKE '%$value%'";
604 }
605 else {
606 $condition = "group_type LIKE '%$value%'";
607 }
608 }
609
610 return $condition;
611 }
612
47c89d6b 613 /**
fe482240 614 * Get permission relevant clauses.
47c89d6b
EM
615 * CRM-12209
616 *
aaac0e0b
EM
617 * @param bool $force
618 *
47c89d6b
EM
619 * @return array
620 */
aaac0e0b
EM
621 public static function getPermissionClause($force = FALSE) {
622 static $clause = 1;
47c89d6b 623 static $retrieved = FALSE;
9486be34 624 if (!$retrieved || $force) {
625 if (CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts')) {
626 $clause = 1;
47c89d6b 627 }
aaac0e0b 628 else {
9486be34 629 //get the allowed groups for the current user
630 $groups = CRM_ACL_API::group(CRM_ACL_API::VIEW);
631 if (!empty($groups)) {
632 $groupList = implode(', ', array_values($groups));
633 $clause = "groups.id IN ( $groupList ) ";
634 }
635 else {
636 $clause = '1 = 0';
637 }
aaac0e0b 638 }
47c89d6b
EM
639 }
640 $retrieved = TRUE;
641 return $clause;
642 }
643
86538308
EM
644 /**
645 * @return string
646 */
6a488035
TO
647 public function __toString() {
648 return $this->title;
649 }
650
651 /**
652 * This function create the hidden smart group when user perform
b44e3f84 653 * contact search and want to send mailing to search contacts.
6a488035 654 *
77c5b619
TO
655 * @param array $params
656 * ( reference ) an assoc array of name/value pairs.
6a488035 657 *
a6c01b45
CW
658 * @return array
659 * ( smartGroupId, ssId ) smart group id and saved search id
6a488035 660 */
00be9182 661 public static function createHiddenSmartGroup($params) {
6a488035
TO
662 $ssId = CRM_Utils_Array::value('saved_search_id', $params);
663
664 //add mapping record only for search builder saved search
665 $mappingId = NULL;
666 if ($params['search_context'] == 'builder') {
667 //save the mapping for search builder
668 if (!$ssId) {
669 //save record in mapping table
353ffa53 670 $temp = array();
6a488035 671 $mappingParams = array('mapping_type' => 'Search Builder');
353ffa53
TO
672 $mapping = CRM_Core_BAO_Mapping::add($mappingParams, $temp);
673 $mappingId = $mapping->id;
6a488035
TO
674 }
675 else {
676 //get the mapping id from saved search
677 $savedSearch = new CRM_Contact_BAO_SavedSearch();
678 $savedSearch->id = $ssId;
679 $savedSearch->find(TRUE);
680 $mappingId = $savedSearch->mapping_id;
681 }
682
683 //save mapping fields
684 CRM_Core_BAO_Mapping::saveMappingFields($params['form_values'], $mappingId);
685 }
686
687 //create/update saved search record.
688 $savedSearch = new CRM_Contact_BAO_SavedSearch();
689 $savedSearch->id = $ssId;
690 $savedSearch->form_values = serialize($params['form_values']);
691 $savedSearch->mapping_id = $mappingId;
692 $savedSearch->search_custom_id = CRM_Utils_Array::value('search_custom_id', $params);
693 $savedSearch->save();
694
695 $ssId = $savedSearch->id;
696 if (!$ssId) {
697 return NULL;
698 }
699
700 $smartGroupId = NULL;
a7488080 701 if (!empty($params['saved_search_id'])) {
6a488035
TO
702 $smartGroupId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
703 }
704 else {
705 //create group only when new saved search.
706 $groupParams = array(
707 'title' => "Hidden Smart Group {$ssId}",
708 'is_active' => CRM_Utils_Array::value('is_active', $params, 1),
709 'is_hidden' => CRM_Utils_Array::value('is_hidden', $params, 1),
710 'group_type' => CRM_Utils_Array::value('group_type', $params),
711 'visibility' => CRM_Utils_Array::value('visibility', $params),
712 'saved_search_id' => $ssId,
713 );
714
715 $smartGroup = self::create($groupParams);
716 $smartGroupId = $smartGroup->id;
717 }
718
719 return array($smartGroupId, $ssId);
720 }
721
722 /**
fe482240 723 * wrapper for ajax group selector.
6a488035 724 *
77c5b619
TO
725 * @param array $params
726 * Associated array for params record id.
6a488035 727 *
a6c01b45
CW
728 * @return array
729 * associated array of group list
16b10e64
CW
730 * -rp = rowcount
731 * -page= offset
d3e86119
TO
732 * @todo there seems little reason for the small number of functions that call this to pass in
733 * params that then need to be translated in this function since they are coding them when calling
6a488035 734 */
bca4d720 735 static public function getGroupListSelector(&$params) {
6a488035 736 // format the params
353ffa53 737 $params['offset'] = ($params['page'] - 1) * $params['rp'];
6a488035 738 $params['rowCount'] = $params['rp'];
353ffa53 739 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
6a488035
TO
740
741 // get groups
742 $groups = CRM_Contact_BAO_Group::getGroupList($params);
743
744 //skip total if we are making call to show only children
a7488080 745 if (empty($params['parent_id'])) {
6a488035
TO
746 // add total
747 $params['total'] = CRM_Contact_BAO_Group::getGroupCount($params);
748
749 // get all the groups
750 $allGroups = CRM_Core_PseudoConstant::allGroup();
751 }
752
753 // format params and add links
754 $groupList = array();
3b448eca
JL
755 foreach ($groups as $id => $value) {
756 $group = array();
757 $group['group_id'] = $value['id'];
758 $group['count'] = $value['count'];
759 $group['title'] = $value['title'];
760
761 // append parent names if in search mode
762 if (empty($params['parent_id']) && !empty($value['parents'])) {
763 $group['parent_id'] = $value['parents'];
764 $groupIds = explode(',', $value['parents']);
765 $title = array();
766 foreach ($groupIds as $gId) {
767 $title[] = $allGroups[$gId];
768 }
769 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
770 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
771 }
772 $group['DT_RowId'] = 'row_' . $value['id'];
46d33c7a 773 if (empty($params['parentsOnly'])) {
fe6e4e4b 774 foreach ($value['class'] as $id => $class) {
be632a8a 775 if ($class == 'crm-group-parent') {
3b448eca 776 unset($value['class'][$id]);
6a488035 777 }
6a488035 778 }
3b448eca
JL
779 }
780 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
781 $group['DT_RowAttr'] = array();
782 $group['DT_RowAttr']['data-id'] = $value['id'];
783 $group['DT_RowAttr']['data-entity'] = 'group';
6a488035 784
3b448eca 785 $group['description'] = CRM_Utils_Array::value('description', $value);
6a488035 786
3b448eca
JL
787 if (!empty($value['group_type'])) {
788 $group['group_type'] = $value['group_type'];
789 }
790 else {
791 $group['group_type'] = '';
6a488035 792 }
3b448eca
JL
793
794 $group['visibility'] = $value['visibility'];
795 $group['links'] = $value['action'];
796 $group['org_info'] = CRM_Utils_Array::value('org_info', $value);
797 $group['created_by'] = CRM_Utils_Array::value('created_by', $value);
798
799 $group['is_parent'] = $value['is_parent'];
800
1e223804 801 array_push($groupList, $group);
6a488035 802 }
3b448eca
JL
803
804 $groupsDT = array();
805 $groupsDT['data'] = $groupList;
806 $groupsDT['recordsTotal'] = $params['total'];
807 $groupsDT['recordsFiltered'] = $params['total'];
808
809 return $groupsDT;
6a488035
TO
810 }
811
812 /**
fe482240 813 * This function to get list of groups.
6a488035 814 *
77c5b619
TO
815 * @param array $params
816 * Associated array for params.
80ad33e7
EM
817 *
818 * @return array
6a488035 819 */
00be9182 820 public static function getGroupList(&$params) {
6a488035
TO
821 $config = CRM_Core_Config::singleton();
822
823 $whereClause = self::whereClause($params, FALSE);
f90c40b9 824
6a488035
TO
825 //$this->pagerAToZ( $whereClause, $params );
826
827 if (!empty($params['rowCount']) &&
828 $params['rowCount'] > 0
829 ) {
830 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
831 }
832
833 $orderBy = ' ORDER BY groups.title asc';
21d32567
DL
834 if (!empty($params['sort'])) {
835 $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
1d19a8f2
CW
836
837 // CRM-16905 - Sort by count cannot be done with sql
838 if (strpos($params['sort'], 'count') === 0) {
839 $orderBy = $limit = '';
840 }
6a488035
TO
841 }
842
843 $select = $from = $where = "";
844 $groupOrg = FALSE;
845 if (CRM_Core_Permission::check('administer Multiple Organizations') &&
846 CRM_Core_Permission::isMultisiteEnabled()
847 ) {
848 $select = ", contact.display_name as org_name, contact.id as org_id";
849 $from = " LEFT JOIN civicrm_group_organization gOrg
850 ON gOrg.group_id = groups.id
851 LEFT JOIN civicrm_contact contact
852 ON contact.id = gOrg.organization_id ";
853
854 //get the Organization ID
855 $orgID = CRM_Utils_Request::retrieve('oid', 'Positive', CRM_Core_DAO::$_nullObject);
856 if ($orgID) {
857 $where = " AND gOrg.organization_id = {$orgID}";
858 }
859
860 $groupOrg = TRUE;
861 }
862
863 $query = "
cbe32e2f 864 SELECT groups.*, createdBy.sort_name as created_by {$select}
6a488035 865 FROM civicrm_group groups
7f4b344c
CW
866 LEFT JOIN civicrm_contact createdBy
867 ON createdBy.id = groups.created_id
868 {$from}
6a488035
TO
869 WHERE $whereClause {$where}
870 {$orderBy}
871 {$limit}";
872
873 $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
874
875 //FIXME CRM-4418, now we are handling delete separately
876 //if we introduce 'delete for group' make sure to handle here.
877 $groupPermissions = array(CRM_Core_Permission::VIEW);
878 if (CRM_Core_Permission::check('edit groups')) {
879 $groupPermissions[] = CRM_Core_Permission::EDIT;
880 $groupPermissions[] = CRM_Core_Permission::DELETE;
881 }
882
883 // CRM-9936
884 $reservedPermission = CRM_Core_Permission::check('administer reserved groups');
885
886 $links = self::actionLinks();
887
888 $allTypes = CRM_Core_OptionGroup::values('group_type');
cbe32e2f 889 $values = $groupsToCount = array();
6a488035 890
e3c75a92 891 $visibility = CRM_Core_SelectValues::ufVisibility();
892
6a488035
TO
893 while ($object->fetch()) {
894 $permission = CRM_Contact_BAO_Group::checkPermission($object->id, $object->title);
0f8844a1 895 //@todo CRM-12209 introduced an ACL check in the whereClause function
896 // it may be that this checking is now obsolete - or that what remains
897 // should be removed to the whereClause (which is also accessed by getCount)
898
6a488035
TO
899 if ($permission) {
900 $newLinks = $links;
cbe32e2f
CW
901 $values[$object->id] = array(
902 'class' => array(),
903 'count' => '0',
904 );
6a488035 905 CRM_Core_DAO::storeValues($object, $values[$object->id]);
93abd831 906
6a488035
TO
907 if ($object->saved_search_id) {
908 $values[$object->id]['title'] .= ' (' . ts('Smart Group') . ')';
909 // check if custom search, if so fix view link
910 $customSearchID = CRM_Core_DAO::getFieldValue(
911 'CRM_Contact_DAO_SavedSearch',
912 $object->saved_search_id,
913 'search_custom_id'
914 );
915
916 if ($customSearchID) {
917 $newLinks[CRM_Core_Action::VIEW]['url'] = 'civicrm/contact/search/custom';
918 $newLinks[CRM_Core_Action::VIEW]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
919 }
920 }
921
922 $action = array_sum(array_keys($newLinks));
923
924 // CRM-9936
925 if (array_key_exists('is_reserved', $object)) {
926 //if group is reserved and I don't have reserved permission, suppress delete/edit
927 if ($object->is_reserved && !$reservedPermission) {
928 $action -= CRM_Core_Action::DELETE;
929 $action -= CRM_Core_Action::UPDATE;
930 $action -= CRM_Core_Action::DISABLE;
931 }
932 }
933
6a488035
TO
934 if (array_key_exists('is_active', $object)) {
935 if ($object->is_active) {
936 $action -= CRM_Core_Action::ENABLE;
937 }
938 else {
7d644ac8 939 $values[$object->id]['class'][] = 'disabled';
6a488035
TO
940 $action -= CRM_Core_Action::VIEW;
941 $action -= CRM_Core_Action::DISABLE;
942 }
943 }
944
945 $action = $action & CRM_Core_Action::mask($groupPermissions);
946
e3c75a92 947 $values[$object->id]['visibility'] = $visibility[$values[$object->id]['visibility']];
948
cbe32e2f 949 $groupsToCount[$object->saved_search_id ? 'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id;
7f4b344c 950
6a488035
TO
951 if (isset($values[$object->id]['group_type'])) {
952 $groupTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
953 substr($values[$object->id]['group_type'], 1, -1)
954 );
955 $types = array();
956 foreach ($groupTypes as $type) {
957 $types[] = CRM_Utils_Array::value($type, $allTypes);
958 }
959 $values[$object->id]['group_type'] = implode(', ', $types);
960 }
961 $values[$object->id]['action'] = CRM_Core_Action::formLink($newLinks,
962 $action,
963 array(
964 'id' => $object->id,
965 'ssid' => $object->saved_search_id,
87dab4a4
AH
966 ),
967 ts('more'),
968 FALSE,
969 'group.selector.row',
970 'Group',
971 $object->id
6a488035
TO
972 );
973
974 // If group has children, add class for link to view children
ab8a593e 975 $values[$object->id]['is_parent'] = FALSE;
6a488035 976 if (array_key_exists('children', $values[$object->id])) {
7d644ac8 977 $values[$object->id]['class'][] = "crm-group-parent";
4eeb9a5b 978 $values[$object->id]['is_parent'] = TRUE;
6a488035
TO
979 }
980
981 // If group is a child, add child class
982 if (array_key_exists('parents', $values[$object->id])) {
7d644ac8 983 $values[$object->id]['class'][] = "crm-group-child";
6a488035
TO
984 }
985
986 if ($groupOrg) {
987 if ($object->org_id) {
988 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
989 $values[$object->id]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
990 }
991 else {
992 $values[$object->id]['org_info'] = ''; // Empty cell
993 }
994 }
995 else {
996 $values[$object->id]['org_info'] = NULL; // Collapsed column if all cells are NULL
997 }
998 if ($object->created_id) {
999 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
1000 $values[$object->id]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
1001 }
1002 }
1003 }
1004
e96ee3a2 1005 // Get group counts - executes one query for regular groups and another for smart groups
cbe32e2f 1006 foreach ($groupsToCount as $table => $groups) {
e96ee3a2 1007 $where = "g.group_id IN (" . implode(',', $groups) . ")";
b08455a1 1008 if ($table == 'civicrm_group_contact') {
e96ee3a2 1009 $where .= " AND g.status = 'Added'";
b08455a1 1010 }
e96ee3a2
CW
1011 // Exclude deleted contacts
1012 $where .= " and c.id = g.contact_id AND c.is_deleted = 0";
1013 $dao = CRM_Core_DAO::executeQuery("SELECT g.group_id, COUNT(g.id) as `count` FROM $table g, civicrm_contact c WHERE $where GROUP BY g.group_id");
22e263ad 1014 while ($dao->fetch()) {
cbe32e2f
CW
1015 $values[$dao->group_id]['count'] = $dao->count;
1016 }
1017 }
1018
1d19a8f2
CW
1019 // CRM-16905 - Sort by count cannot be done with sql
1020 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1021 usort($values, function($a, $b) {
1022 return $a['count'] - $b['count'];
1023 });
1024 if (strpos($params['sort'], 'desc')) {
1025 $values = array_reverse($values, TRUE);
1026 }
1027 return array_slice($values, $params['offset'], $params['rowCount']);
1028 }
1029
6a488035
TO
1030 return $values;
1031 }
1032
1033 /**
1034 * This function to get hierarchical list of groups (parent followed by children)
1035 *
77c5b619
TO
1036 * @param array $groupIDs
1037 * Array of group ids.
80ad33e7 1038 *
e60f24eb 1039 * @param NULL $parents
80ad33e7
EM
1040 * @param string $spacer
1041 * @param bool $titleOnly
f828fa2c 1042 *
80ad33e7 1043 * @return array
6a488035 1044 */
2da40d21 1045 public static function getGroupsHierarchy(
f828fa2c 1046 $groupIDs,
90d1fee5 1047 $parents = NULL,
6a488035
TO
1048 $spacer = '<span class="child-indent"></span>',
1049 $titleOnly = FALSE
90d1fee5 1050 ) {
f828fa2c
DL
1051 if (empty($groupIDs)) {
1052 return array();
1053 }
1054
1055 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
90d1fee5 1056 // <span class="child-icon"></span>
1057 // need to return id, title (w/ spacer), description, visibility
1058
1059 // We need to build a list of tags ordered by hierarchy and sorted by
b44e3f84 1060 // name. The hierarchy will be communicated by an accumulation of
90d1fee5 1061 // separators in front of the name to give it a visual offset.
1062 // Instead of recursively making mysql queries, we'll make one big
b44e3f84 1063 // query and build the hierarchy with the algorithm below.
90d1fee5 1064 $groups = array();
1065 $args = array(1 => array($groupIdString, 'String'));
1066 $query = "
f828fa2c
DL
1067SELECT id, title, description, visibility, parents
1068FROM civicrm_group
1069WHERE id IN $groupIdString
1070";
90d1fee5 1071 if ($parents) {
1072 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1073 $parentArray = explode(',', $parents);
1074 $parent = $parentArray[0];
1075 $args[2] = array($parent, 'Integer');
1076 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1077 }
1078 $query .= " ORDER BY title";
1079 $dao = CRM_Core_DAO::executeQuery($query, $args);
1080
1081 // Sort the groups into the correct storage by the parent
1082 // $roots represent the current leaf nodes that need to be checked for
1083 // children. $rows represent the unplaced nodes
1084 $roots = $rows = $allGroups = array();
1085 while ($dao->fetch()) {
1086 $allGroups[$dao->id] = array(
1087 'title' => $dao->title,
1088 'visibility' => $dao->visibility,
21dfd5f5 1089 'description' => $dao->description,
90d1fee5 1090 );
1091
1092 if ($dao->parents == $parents) {
1093 $roots[] = array(
1094 'id' => $dao->id,
1095 'prefix' => '',
21dfd5f5 1096 'title' => $dao->title,
90d1fee5 1097 );
1098 }
1099 else {
1100 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1101 $parentArray = explode(',', $dao->parents);
1102 $parent = $parentArray[0];
1103 $rows[] = array(
1104 'id' => $dao->id,
1105 'prefix' => '',
1106 'title' => $dao->title,
21dfd5f5 1107 'parents' => $parent,
90d1fee5 1108 );
1109 }
1110 }
1111 $dao->free();
1112 // While we have nodes left to build, shift the first (alphabetically)
1113 // node of the list, place it in our groups list and loop through the
1114 // list of unplaced nodes to find its children. We make a copy to
1115 // iterate through because we must modify the unplaced nodes list
1116 // during the loop.
1117 while (count($roots)) {
1118 $new_roots = array();
1119 $current_rows = $rows;
1120 $root = array_shift($roots);
1121 $groups[$root['id']] = array($root['prefix'], $root['title']);
1122
1123 // As you find the children, append them to the end of the new set
1124 // of roots (maintain alphabetical ordering). Also remove the node
1125 // from the set of unplaced nodes.
1126 if (is_array($current_rows)) {
1127 foreach ($current_rows as $key => $row) {
1128 if ($row['parents'] == $root['id']) {
1129 $new_roots[] = array(
1130 'id' => $row['id'],
1131 'prefix' => $groups[$root['id']][0] . $spacer,
21dfd5f5 1132 'title' => $row['title'],
90d1fee5 1133 );
1134 unset($rows[$key]);
1135 }
1136 }
1137 }
1138
1139 //As a group, insert the new roots into the beginning of the roots
1140 //list. This maintains the hierarchical ordering of the tags.
1141 $roots = array_merge($new_roots, $roots);
1142 }
1143
1144 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1145 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1146 foreach ($rows as $value) {
1147 $groups[$value['id']] = array($value['prefix'], $value['title']);
1148 }
1149 // Prefix titles with the calcuated spacing to give the visual
1150 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1151 $groupsReturn = array();
1152 foreach ($groups as $key => $value) {
1153 if ($titleOnly) {
1154 $groupsReturn[$key] = $value[0] . $value[1];
1155 }
1156 else {
1157 $groupsReturn[$key] = array(
1158 'title' => $value[0] . $value[1],
1159 'description' => $allGroups[$key]['description'],
1160 'visibility' => $allGroups[$key]['visibility'],
1161 );
1162 }
1163 }
1164
1165 return $groupsReturn;
6a488035
TO
1166 }
1167
86538308 1168 /**
c490a46a 1169 * @param array $params
86538308 1170 *
e60f24eb 1171 * @return NULL|string
86538308 1172 */
00be9182 1173 public static function getGroupCount(&$params) {
6a488035
TO
1174 $whereClause = self::whereClause($params, FALSE);
1175 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1176
a7488080 1177 if (!empty($params['created_by'])) {
6a488035
TO
1178 $query .= "
1179INNER JOIN civicrm_contact createdBy
1180 ON createdBy.id = groups.created_id";
1181 }
1182 $query .= "
1183WHERE {$whereClause}";
1184 return CRM_Core_DAO::singleValueQuery($query, $params);
1185 }
1186
47c89d6b 1187 /**
fe482240 1188 * Generate permissioned where clause for group search.
c490a46a 1189 * @param array $params
47c89d6b
EM
1190 * @param bool $sortBy
1191 * @param bool $excludeHidden
1192 *
1193 * @return string
1194 */
00be9182 1195 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
6a488035 1196 $values = array();
6a488035
TO
1197 $title = CRM_Utils_Array::value('title', $params);
1198 if ($title) {
1199 $clauses[] = "groups.title LIKE %1";
1200 if (strpos($title, '%') !== FALSE) {
1201 $params[1] = array($title, 'String', FALSE);
1202 }
1203 else {
1204 $params[1] = array($title, 'String', TRUE);
1205 }
1206 }
1207
1208 $groupType = CRM_Utils_Array::value('group_type', $params);
1209 if ($groupType) {
1210 $types = explode(',', $groupType);
1211 if (!empty($types)) {
353ffa53 1212 $clauses[] = 'groups.group_type LIKE %2';
6a488035 1213 $typeString = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $types) . CRM_Core_DAO::VALUE_SEPARATOR;
353ffa53 1214 $params[2] = array($typeString, 'String', TRUE);
6a488035
TO
1215 }
1216 }
1217
1218 $visibility = CRM_Utils_Array::value('visibility', $params);
1219 if ($visibility) {
1220 $clauses[] = 'groups.visibility = %3';
1221 $params[3] = array($visibility, 'String');
1222 }
1223
1224 $groupStatus = CRM_Utils_Array::value('status', $params);
1225 if ($groupStatus) {
1226 switch ($groupStatus) {
1227 case 1:
1228 $clauses[] = 'groups.is_active = 1';
1229 $params[4] = array($groupStatus, 'Integer');
1230 break;
1231
1232 case 2:
1233 $clauses[] = 'groups.is_active = 0';
1234 $params[4] = array($groupStatus, 'Integer');
1235 break;
1236
1237 case 3:
1238 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1239 break;
1240 }
1241 }
1242
1243 $parentsOnly = CRM_Utils_Array::value('parentsOnly', $params);
1244 if ($parentsOnly) {
1245 $clauses[] = 'groups.parents IS NULL';
1246 }
1247
1248 // only show child groups of a specific parent group
1249 $parent_id = CRM_Utils_Array::value('parent_id', $params);
1250 if ($parent_id) {
1251 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1252 $params[5] = array($parent_id, 'Integer');
1253 }
1254
1255 if ($createdBy = CRM_Utils_Array::value('created_by', $params)) {
1256 $clauses[] = "createdBy.sort_name LIKE %6";
1257 if (strpos($createdBy, '%') !== FALSE) {
1258 $params[6] = array($createdBy, 'String', FALSE);
1259 }
1260 else {
1261 $params[6] = array($createdBy, 'String', TRUE);
1262 }
1263 }
1264
6a488035
TO
1265 if (empty($clauses)) {
1266 $clauses[] = 'groups.is_active = 1';
1267 }
1268
1269 if ($excludeHidden) {
1270 $clauses[] = 'groups.is_hidden = 0';
1271 }
33421d01 1272
aaac0e0b 1273 $clauses[] = self::getPermissionClause();
6a488035
TO
1274
1275 return implode(' AND ', $clauses);
1276 }
1277
1278 /**
fe482240 1279 * Define action links.
6a488035 1280 *
a6c01b45
CW
1281 * @return array
1282 * array of action links
6a488035 1283 */
00be9182 1284 public static function actionLinks() {
6a488035
TO
1285 $links = array(
1286 CRM_Core_Action::VIEW => array(
1287 'name' => ts('Contacts'),
1288 'url' => 'civicrm/group/search',
1289 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1290 'title' => ts('Group Contacts'),
1291 ),
1292 CRM_Core_Action::UPDATE => array(
1293 'name' => ts('Settings'),
1294 'url' => 'civicrm/group',
1295 'qs' => 'reset=1&action=update&id=%%id%%',
1296 'title' => ts('Edit Group'),
1297 ),
1298 CRM_Core_Action::DISABLE => array(
1299 'name' => ts('Disable'),
4d17a233 1300 'ref' => 'crm-enable-disable',
6a488035
TO
1301 'title' => ts('Disable Group'),
1302 ),
1303 CRM_Core_Action::ENABLE => array(
1304 'name' => ts('Enable'),
4d17a233 1305 'ref' => 'crm-enable-disable',
6a488035
TO
1306 'title' => ts('Enable Group'),
1307 ),
1308 CRM_Core_Action::DELETE => array(
1309 'name' => ts('Delete'),
1310 'url' => 'civicrm/group',
1311 'qs' => 'reset=1&action=delete&id=%%id%%',
1312 'title' => ts('Delete Group'),
1313 ),
1314 );
1315
1316 return $links;
1317 }
1318
86538308
EM
1319 /**
1320 * @param $whereClause
100fef9d 1321 * @param array $whereParams
86538308
EM
1322 *
1323 * @return string
1324 */
00be9182 1325 public function pagerAtoZ($whereClause, $whereParams) {
6a488035
TO
1326 $query = "
1327 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1328 FROM civicrm_group groups
1329 WHERE $whereClause
1330 ORDER BY LEFT(groups.title, 1)
1331 ";
1332 $dao = CRM_Core_DAO::executeQuery($query, $whereParams);
1333
1334 return CRM_Utils_PagerAToZ::getAToZBar($dao, $this->_sortByCharacter, TRUE);
1335 }
96025800 1336
c955c26c
SL
1337 /**
1338 * Assign Test Value.
1339 *
1340 * @param string $fieldName
1341 * @param array $fieldDef
1342 * @param int $counter
1343 */
1344 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1345 if ($fieldName == 'children' || $fieldName = 'parents') {
1346 $this->{$fieldName} = "NULL";
1347 }
1348 else {
1349 parent::assignTestValues($fieldaName, $fieldDef, $counter);
1350 }
1351 }
1352
6a488035 1353}