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