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