Fix Syntax Conformance test
[civicrm-core.git] / CRM / Contact / BAO / Group.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2016
32 */
33 class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group {
34
35 /**
36 * Class constructor.
37 */
38 public function __construct() {
39 parent::__construct();
40 }
41
42 /**
43 * Retrieve DB object based on input parameters.
44 *
45 * It also stores all the retrieved values in the default array.
46 *
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.
51 *
52 * @return CRM_Contact_BAO_Group
53 */
54 public static function retrieve(&$params, &$defaults) {
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 }
61 }
62
63 /**
64 * Delete the group and all the object that connect to this group.
65 *
66 * Incredibly destructive.
67 *
68 * @param int $id Group id.
69 */
70 public static function discard($id) {
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
110 if (Civi::settings()->get('is_enabled')) {
111 // clear any descendant groups cache if exists
112 CRM_Core_BAO_Cache::deleteGroup('descendant groups for an org');
113 }
114
115 // delete from group table
116 $group = new CRM_Contact_DAO_Group();
117 $group->id = $id;
118 $group->delete();
119
120 $transaction->commit();
121
122 CRM_Utils_Hook::post('delete', 'Group', $id, $group);
123
124 // delete the recently created Group
125 $groupRecent = array(
126 'id' => $id,
127 'type' => 'Group',
128 );
129 CRM_Utils_Recent::del($groupRecent);
130 }
131
132 /**
133 * Returns an array of the contacts in the given group.
134 *
135 * @param int $id
136 */
137 public static function getGroupContacts($id) {
138 $params = array(array('group', 'IN', array($id => 1), 0, 0));
139 list($contacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, array('contact_id'));
140 return $contacts;
141 }
142
143 /**
144 * Get the count of a members in a group with the specific status.
145 *
146 * @param int $id
147 * Group id.
148 * @param string $status
149 * status of members in group
150 * @param bool $countChildGroups
151 *
152 * @return int
153 * count of members in the group with above status
154 */
155 public static function memberCount($id, $status = 'Added', $countChildGroups = FALSE) {
156 $groupContact = new CRM_Contact_DAO_GroupContact();
157 $groupIds = array($id);
158 if ($countChildGroups) {
159 $groupIds = CRM_Contact_BAO_GroupNesting::getDescendentGroupIds($groupIds);
160 }
161 $count = 0;
162
163 $contacts = self::getGroupContacts($id);
164
165 foreach ($groupIds as $groupId) {
166
167 $groupContacts = self::getGroupContacts($groupId);
168 foreach ($groupContacts as $gcontact) {
169 if ($groupId != $id) {
170 // Loop through main group's contacts
171 // and subtract from the count for each contact which
172 // matches one in the present group, if it is not the
173 // main group
174 foreach ($contacts as $contact) {
175 if ($contact['contact_id'] == $gcontact['contact_id']) {
176 $count--;
177 }
178 }
179 }
180 }
181 $groupContact->group_id = $groupId;
182 if (isset($status)) {
183 $groupContact->status = $status;
184 }
185 $groupContact->_query['condition'] = 'WHERE contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)';
186 $count += $groupContact->count();
187 }
188 return $count;
189 }
190
191 /**
192 * Get the list of member for a group id.
193 *
194 * @param int $groupID
195 * @param bool $useCache
196 * @param int $limit
197 * Number to limit to (or 0 for unlimited).
198 *
199 * @return array
200 * this array contains the list of members for this group id
201 */
202 public static function getMember($groupID, $useCache = TRUE, $limit = 0) {
203 $params = array(array('group', '=', $groupID, 0, 0));
204 $returnProperties = array('contact_id');
205 list($contacts) = CRM_Contact_BAO_Query::apiQuery($params, $returnProperties, NULL, NULL, 0, $limit, $useCache);
206
207 $aMembers = array();
208 foreach ($contacts as $contact) {
209 $aMembers[$contact['contact_id']] = 1;
210 }
211
212 return $aMembers;
213 }
214
215 /**
216 * Returns array of group object(s) matching a set of one or Group properties.
217 *
218 * @param array $params
219 * Limits the set of groups returned.
220 * @param array $returnProperties
221 * Which properties should be included in the returned group objects.
222 * (member_count should be last element.)
223 * @param string $sort
224 * @param int $offset
225 * @param int $rowCount
226 *
227 * @return array
228 * Array of group objects.
229 *
230 *
231 * @todo other BAO functions that use returnProperties (e.g. Query Objects) receive the array flipped & filled with 1s and
232 * add in essential fields (e.g. id). This should follow a regular pattern like the others
233 */
234 public static function getGroups(
235 $params = NULL,
236 $returnProperties = NULL,
237 $sort = NULL,
238 $offset = NULL,
239 $rowCount = NULL
240 ) {
241 $dao = new CRM_Contact_DAO_Group();
242 if (!isset($params['is_active'])) {
243 $dao->is_active = 1;
244 }
245 if ($params) {
246 foreach ($params as $k => $v) {
247 if ($k == 'name' || $k == 'title') {
248 $dao->whereAdd($k . ' LIKE "' . CRM_Core_DAO::escapeString($v) . '"');
249 }
250 elseif ($k == 'group_type') {
251 foreach ((array) $v as $type) {
252 $dao->whereAdd($k . " LIKE '%" . CRM_Core_DAO::VALUE_SEPARATOR . (int) $type . CRM_Core_DAO::VALUE_SEPARATOR . "%'");
253 }
254 }
255 elseif (is_array($v)) {
256 foreach ($v as &$num) {
257 $num = (int) $num;
258 }
259 $dao->whereAdd($k . ' IN (' . implode(',', $v) . ')');
260 }
261 else {
262 $dao->$k = $v;
263 }
264 }
265 }
266
267 if ($offset || $rowCount) {
268 $offset = ($offset > 0) ? $offset : 0;
269 $rowCount = ($rowCount > 0) ? $rowCount : 25;
270 $dao->limit($offset, $rowCount);
271 }
272
273 if ($sort) {
274 $dao->orderBy($sort);
275 }
276
277 // return only specific fields if returnproperties are sent
278 if (!empty($returnProperties)) {
279 $dao->selectAdd();
280 $dao->selectAdd(implode(',', $returnProperties));
281 }
282 $dao->find();
283
284 $flag = $returnProperties && in_array('member_count', $returnProperties) ? 1 : 0;
285
286 $groups = array();
287 while ($dao->fetch()) {
288 $group = new CRM_Contact_DAO_Group();
289 if ($flag) {
290 $dao->member_count = CRM_Contact_BAO_Group::memberCount($dao->id);
291 }
292 $groups[] = clone($dao);
293 }
294 return $groups;
295 }
296
297 /**
298 * Make sure that the user has permission to access this group.
299 *
300 * @param int $id
301 * The id of the object.
302 * @param bool $excludeHidden
303 * Should hidden groups be excluded.
304 * Logically this is the wrong place to filter hidden groups out as that is
305 * not a permission issue. However, as other functions may rely on that defaulting to
306 * FALSE for now & only the api call is calling with true.
307 *
308 * @return array
309 * The permission that the user has (or NULL)
310 */
311 public static function checkPermission($id, $excludeHidden = FALSE) {
312 $allGroups = CRM_Core_PseudoConstant::allGroup(NULL, $excludeHidden);
313
314 $permissions = NULL;
315 if (CRM_Core_Permission::check('edit all contacts') ||
316 CRM_ACL_API::groupPermission(CRM_ACL_API::EDIT, $id, NULL,
317 'civicrm_saved_search', $allGroups
318 )
319 ) {
320 $permissions[] = CRM_Core_Permission::EDIT;
321 }
322
323 if (CRM_Core_Permission::check('view all contacts') ||
324 CRM_ACL_API::groupPermission(CRM_ACL_API::VIEW, $id, NULL,
325 'civicrm_saved_search', $allGroups
326 )
327 ) {
328 $permissions[] = CRM_Core_Permission::VIEW;
329 }
330
331 if (!empty($permissions) && CRM_Core_Permission::check('delete contacts')) {
332 // Note: using !empty() in if condition, restricts the scope of delete
333 // permission to groups/contacts that are editable/viewable.
334 // We can remove this !empty condition once we have ACL support for delete functionality.
335 $permissions[] = CRM_Core_Permission::DELETE;
336 }
337
338 return $permissions;
339 }
340
341 /**
342 * Create a new group.
343 *
344 * @param array $params
345 *
346 * @return CRM_Contact_BAO_Group|NULL
347 * The new group BAO (if created)
348 */
349 public static function create(&$params) {
350
351 if (!empty($params['id'])) {
352 CRM_Utils_Hook::pre('edit', 'Group', $params['id'], $params);
353 }
354 else {
355 CRM_Utils_Hook::pre('create', 'Group', NULL, $params);
356 }
357
358 // form the name only if missing: CRM-627
359 $nameParam = CRM_Utils_Array::value('name', $params, NULL);
360 if (!$nameParam && empty($params['id'])) {
361 $params['name'] = CRM_Utils_String::titleToVar($params['title']);
362 }
363
364 // convert params if array type
365 if (isset($params['group_type'])) {
366 if (is_array($params['group_type'])) {
367 $params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
368 $params['group_type']
369 ) . CRM_Core_DAO::VALUE_SEPARATOR;
370 }
371 else {
372 $params['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $params['group_type'] . CRM_Core_DAO::VALUE_SEPARATOR;
373 }
374 }
375 else {
376 $params['group_type'] = NULL;
377 }
378
379 $session = CRM_Core_Session::singleton();
380 $cid = $session->get('userID');
381 // this action is add
382 if ($cid && empty($params['id'])) {
383 $params['created_id'] = $cid;
384 }
385 // this action is update
386 if ($cid && !empty($params['id'])) {
387 $params['modified_id'] = $cid;
388 }
389
390 $group = new CRM_Contact_BAO_Group();
391 $group->copyValues($params);
392 //@todo very hacky fix for the fact this function wants to receive 'parents' as an array further down but
393 // needs it as a separated string for the DB. Preferred approaches are having the copyParams or save fn
394 // use metadata to translate the array to the appropriate DB type or altering the param in the api layer,
395 // or at least altering the param in same section as 'group_type' rather than repeating here. However, further down
396 // we need the $params one to be in it's original form & we are not sure what test coverage we have on that
397 if (isset($group->parents) && is_array($group->parents)) {
398 $group->parents = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
399 array_keys($group->parents)
400 ) . CRM_Core_DAO::VALUE_SEPARATOR;
401 }
402 if (empty($params['id']) &&
403 !$nameParam
404 ) {
405 $group->name .= "_tmp";
406 }
407 $group->save();
408
409 if (!$group->id) {
410 return NULL;
411 }
412
413 if (empty($params['id']) &&
414 !$nameParam
415 ) {
416 $group->name = substr($group->name, 0, -4) . "_{$group->id}";
417 }
418
419 $group->buildClause();
420 $group->save();
421
422 // add custom field values
423 if (!empty($params['custom'])) {
424 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_group', $group->id);
425 }
426
427 // make the group, child of domain/site group by default.
428 $domainGroupID = CRM_Core_BAO_Domain::getGroupId();
429 if (CRM_Utils_Array::value('no_parent', $params) !== 1) {
430 if (empty($params['parents']) &&
431 $domainGroupID != $group->id &&
432 Civi::settings()->get('is_enabled') &&
433 !CRM_Contact_BAO_GroupNesting::hasParentGroups($group->id)
434 ) {
435 // if no parent present and the group doesn't already have any parents,
436 // make sure site group goes as parent
437 $params['parents'] = array($domainGroupID => 1);
438 }
439 elseif (array_key_exists('parents', $params) && !is_array($params['parents'])) {
440 $params['parents'] = array($params['parents'] => 1);
441 }
442
443 if (!empty($params['parents'])) {
444 foreach ($params['parents'] as $parentId => $dnc) {
445 if ($parentId && !CRM_Contact_BAO_GroupNesting::isParentChild($parentId, $group->id)) {
446 CRM_Contact_BAO_GroupNesting::add($parentId, $group->id);
447 }
448 }
449 }
450
451 // clear any descendant groups cache if exists
452 $finalGroups = CRM_Core_BAO_Cache::deleteGroup('descendant groups for an org');
453
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
465 if (!empty($params['organization_id'])) {
466 $groupOrg = $params;
467 $groupOrg['group_id'] = $group->id;
468 CRM_Contact_BAO_GroupOrganization::add($groupOrg);
469 }
470
471 CRM_Contact_BAO_GroupContactCache::add($group->id);
472
473 if (!empty($params['id'])) {
474 CRM_Utils_Hook::post('edit', 'Group', $group->id, $group);
475 }
476 else {
477 CRM_Utils_Hook::post('create', 'Group', $group->id, $group);
478 }
479
480 $recentOther = array();
481 if (CRM_Core_Permission::check('edit groups')) {
482 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=update&id=' . $group->id);
483 // currently same permission we are using for delete a group
484 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/group', 'reset=1&action=delete&id=' . $group->id);
485 }
486
487 // add the recently added group (unless hidden: CRM-6432)
488 if (!$group->is_hidden) {
489 CRM_Utils_Recent::add($group->title,
490 CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id),
491 $group->id,
492 'Group',
493 NULL,
494 NULL,
495 $recentOther
496 );
497 }
498 return $group;
499 }
500
501 /**
502 * Given a saved search compute the clause and the tables
503 * and store it for future use
504 */
505 public function buildClause() {
506 $params = array(array('group', 'IN', array($this->id), 0, 0));
507
508 if (!empty($params)) {
509 $tables = $whereTables = array();
510 $this->where_clause = CRM_Contact_BAO_Query::getWhereClause($params, NULL, $tables, $whereTables);
511 if (!empty($tables)) {
512 $this->select_tables = serialize($tables);
513 }
514 if (!empty($whereTables)) {
515 $this->where_tables = serialize($whereTables);
516 }
517 }
518 }
519
520 /**
521 * Defines a new smart group.
522 *
523 * @param array $params
524 * Associative array of parameters.
525 *
526 * @return CRM_Contact_BAO_Group|NULL
527 * The new group BAO (if created)
528 */
529 public static function createSmartGroup(&$params) {
530 if (!empty($params['formValues'])) {
531 $ssParams = $params;
532 unset($ssParams['id']);
533 if (isset($ssParams['saved_search_id'])) {
534 $ssParams['id'] = $ssParams['saved_search_id'];
535 }
536
537 $savedSearch = CRM_Contact_BAO_SavedSearch::create($params);
538
539 $params['saved_search_id'] = $savedSearch->id;
540 }
541 else {
542 return NULL;
543 }
544
545 return self::create($params);
546 }
547
548 /**
549 * Update the is_active flag in the db.
550 *
551 * @param int $id
552 * Id of the database record.
553 * @param bool $isActive
554 * Value we want to set the is_active field.
555 *
556 * @return CRM_Core_DAO|null
557 * DAO object on success, NULL otherwise
558 */
559 public static function setIsActive($id, $isActive) {
560 return CRM_Core_DAO::setFieldValue('CRM_Contact_DAO_Group', $id, 'is_active', $isActive);
561 }
562
563 /**
564 * Build the condition to retrieve groups.
565 *
566 * @param string $groupType
567 * Type of group(Access/Mailing) OR the key of the group.
568 * @param bool $excludeHidden exclude hidden groups.
569 *
570 * @return string
571 */
572 public static function groupTypeCondition($groupType = NULL, $excludeHidden = TRUE) {
573 $value = NULL;
574 if ($groupType == 'Mailing') {
575 $value = CRM_Core_DAO::VALUE_SEPARATOR . '2' . CRM_Core_DAO::VALUE_SEPARATOR;
576 }
577 elseif ($groupType == 'Access') {
578 $value = CRM_Core_DAO::VALUE_SEPARATOR . '1' . CRM_Core_DAO::VALUE_SEPARATOR;
579 }
580 elseif (!empty($groupType)) {
581 // ie we have been given the group key
582 $value = CRM_Core_DAO::VALUE_SEPARATOR . $groupType . CRM_Core_DAO::VALUE_SEPARATOR;
583 }
584
585 $condition = NULL;
586 if ($excludeHidden) {
587 $condition = "is_hidden = 0";
588 }
589
590 if ($value) {
591 if ($condition) {
592 $condition .= " AND group_type LIKE '%$value%'";
593 }
594 else {
595 $condition = "group_type LIKE '%$value%'";
596 }
597 }
598
599 return $condition;
600 }
601
602 /**
603 * Get permission relevant clauses.
604 * CRM-12209
605 *
606 * @param bool $force
607 *
608 * @return array
609 */
610 public static function getPermissionClause($force = FALSE) {
611 static $clause = 1;
612 static $retrieved = FALSE;
613 if (!$retrieved || $force) {
614 if (CRM_Core_Permission::check('view all contacts') || CRM_Core_Permission::check('edit all contacts')) {
615 $clause = 1;
616 }
617 else {
618 //get the allowed groups for the current user
619 $groups = CRM_ACL_API::group(CRM_ACL_API::VIEW);
620 if (!empty($groups)) {
621 $groupList = implode(', ', array_values($groups));
622 $clause = "groups.id IN ( $groupList ) ";
623 }
624 else {
625 $clause = '1 = 0';
626 }
627 }
628 }
629 $retrieved = TRUE;
630 return $clause;
631 }
632
633 /**
634 * @return string
635 */
636 public function __toString() {
637 return $this->title;
638 }
639
640 /**
641 * This function create the hidden smart group when user perform
642 * contact search and want to send mailing to search contacts.
643 *
644 * @param array $params
645 * ( reference ) an assoc array of name/value pairs.
646 *
647 * @return array
648 * ( smartGroupId, ssId ) smart group id and saved search id
649 */
650 public static function createHiddenSmartGroup($params) {
651 $ssId = CRM_Utils_Array::value('saved_search_id', $params);
652
653 //add mapping record only for search builder saved search
654 $mappingId = NULL;
655 if ($params['search_context'] == 'builder') {
656 //save the mapping for search builder
657 if (!$ssId) {
658 //save record in mapping table
659 $temp = array();
660 $mappingParams = array('mapping_type' => 'Search Builder');
661 $mapping = CRM_Core_BAO_Mapping::add($mappingParams, $temp);
662 $mappingId = $mapping->id;
663 }
664 else {
665 //get the mapping id from saved search
666 $savedSearch = new CRM_Contact_BAO_SavedSearch();
667 $savedSearch->id = $ssId;
668 $savedSearch->find(TRUE);
669 $mappingId = $savedSearch->mapping_id;
670 }
671
672 //save mapping fields
673 CRM_Core_BAO_Mapping::saveMappingFields($params['form_values'], $mappingId);
674 }
675
676 //create/update saved search record.
677 $savedSearch = new CRM_Contact_BAO_SavedSearch();
678 $savedSearch->id = $ssId;
679 $savedSearch->form_values = serialize($params['form_values']);
680 $savedSearch->mapping_id = $mappingId;
681 $savedSearch->search_custom_id = CRM_Utils_Array::value('search_custom_id', $params);
682 $savedSearch->save();
683
684 $ssId = $savedSearch->id;
685 if (!$ssId) {
686 return NULL;
687 }
688
689 $smartGroupId = NULL;
690 if (!empty($params['saved_search_id'])) {
691 $smartGroupId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $ssId, 'id', 'saved_search_id');
692 }
693 else {
694 //create group only when new saved search.
695 $groupParams = array(
696 'title' => "Hidden Smart Group {$ssId}",
697 'is_active' => CRM_Utils_Array::value('is_active', $params, 1),
698 'is_hidden' => CRM_Utils_Array::value('is_hidden', $params, 1),
699 'group_type' => CRM_Utils_Array::value('group_type', $params),
700 'visibility' => CRM_Utils_Array::value('visibility', $params),
701 'saved_search_id' => $ssId,
702 );
703
704 $smartGroup = self::create($groupParams);
705 $smartGroupId = $smartGroup->id;
706 }
707
708 return array($smartGroupId, $ssId);
709 }
710
711 /**
712 * wrapper for ajax group selector.
713 *
714 * @param array $params
715 * Associated array for params record id.
716 *
717 * @return array
718 * associated array of group list
719 * -rp = rowcount
720 * -page= offset
721 * @todo there seems little reason for the small number of functions that call this to pass in
722 * params that then need to be translated in this function since they are coding them when calling
723 */
724 static public function getGroupListSelector(&$params) {
725 // format the params
726 $params['offset'] = ($params['page'] - 1) * $params['rp'];
727 $params['rowCount'] = $params['rp'];
728 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
729
730 // get groups
731 $groups = CRM_Contact_BAO_Group::getGroupList($params);
732
733 //skip total if we are making call to show only children
734 if (empty($params['parent_id'])) {
735 // add total
736 $params['total'] = CRM_Contact_BAO_Group::getGroupCount($params);
737
738 // get all the groups
739 $allGroups = CRM_Core_PseudoConstant::allGroup();
740 }
741
742 // format params and add links
743 $groupList = array();
744 foreach ($groups as $id => $value) {
745 $group = array();
746 $group['group_id'] = $value['id'];
747 $group['count'] = $value['count'];
748 $group['title'] = $value['title'];
749
750 // append parent names if in search mode
751 if (empty($params['parent_id']) && !empty($value['parents'])) {
752 $group['parent_id'] = $value['parents'];
753 $groupIds = explode(',', $value['parents']);
754 $title = array();
755 foreach ($groupIds as $gId) {
756 $title[] = $allGroups[$gId];
757 }
758 $group['title'] .= '<div class="crm-row-parent-name"><em>' . ts('Child of') . '</em>: ' . implode(', ', $title) . '</div>';
759 $value['class'] = array_diff($value['class'], array('crm-row-parent'));
760 }
761 $group['DT_RowId'] = 'row_' . $value['id'];
762 if (empty($params['parentsOnly'])) {
763 foreach ($value['class'] as $id => $class) {
764 if ($class == 'crm-group-parent') {
765 unset($value['class'][$id]);
766 }
767 }
768 }
769 $group['DT_RowClass'] = 'crm-entity ' . implode(' ', $value['class']);
770 $group['DT_RowAttr'] = array();
771 $group['DT_RowAttr']['data-id'] = $value['id'];
772 $group['DT_RowAttr']['data-entity'] = 'group';
773
774 $group['description'] = CRM_Utils_Array::value('description', $value);
775
776 if (!empty($value['group_type'])) {
777 $group['group_type'] = $value['group_type'];
778 }
779 else {
780 $group['group_type'] = '';
781 }
782
783 $group['visibility'] = $value['visibility'];
784 $group['links'] = $value['action'];
785 $group['org_info'] = CRM_Utils_Array::value('org_info', $value);
786 $group['created_by'] = CRM_Utils_Array::value('created_by', $value);
787
788 $group['is_parent'] = $value['is_parent'];
789
790 array_push($groupList, $group);
791 }
792
793 $groupsDT = array();
794 $groupsDT['data'] = $groupList;
795 $groupsDT['recordsTotal'] = $params['total'];
796 $groupsDT['recordsFiltered'] = $params['total'];
797
798 return $groupsDT;
799 }
800
801 /**
802 * This function to get list of groups.
803 *
804 * @param array $params
805 * Associated array for params.
806 *
807 * @return array
808 */
809 public static function getGroupList(&$params) {
810 $config = CRM_Core_Config::singleton();
811
812 $whereClause = self::whereClause($params, FALSE);
813
814 //$this->pagerAToZ( $whereClause, $params );
815
816 if (!empty($params['rowCount']) &&
817 $params['rowCount'] > 0
818 ) {
819 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
820 }
821
822 $orderBy = ' ORDER BY groups.title asc';
823 if (!empty($params['sort'])) {
824 $orderBy = ' ORDER BY ' . CRM_Utils_Type::escape($params['sort'], 'String');
825
826 // CRM-16905 - Sort by count cannot be done with sql
827 if (strpos($params['sort'], 'count') === 0) {
828 $orderBy = $limit = '';
829 }
830 }
831
832 $select = $from = $where = "";
833 $groupOrg = FALSE;
834 if (CRM_Core_Permission::check('administer Multiple Organizations') &&
835 CRM_Core_Permission::isMultisiteEnabled()
836 ) {
837 $select = ", contact.display_name as org_name, contact.id as org_id";
838 $from = " LEFT JOIN civicrm_group_organization gOrg
839 ON gOrg.group_id = groups.id
840 LEFT JOIN civicrm_contact contact
841 ON contact.id = gOrg.organization_id ";
842
843 //get the Organization ID
844 $orgID = CRM_Utils_Request::retrieve('oid', 'Positive', CRM_Core_DAO::$_nullObject);
845 if ($orgID) {
846 $where = " AND gOrg.organization_id = {$orgID}";
847 }
848
849 $groupOrg = TRUE;
850 }
851
852 $query = "
853 SELECT groups.*, createdBy.sort_name as created_by {$select}
854 FROM civicrm_group groups
855 LEFT JOIN civicrm_contact createdBy
856 ON createdBy.id = groups.created_id
857 {$from}
858 WHERE $whereClause {$where}
859 {$orderBy}
860 {$limit}";
861
862 $object = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contact_DAO_Group');
863
864 //FIXME CRM-4418, now we are handling delete separately
865 //if we introduce 'delete for group' make sure to handle here.
866 $groupPermissions = array(CRM_Core_Permission::VIEW);
867 if (CRM_Core_Permission::check('edit groups')) {
868 $groupPermissions[] = CRM_Core_Permission::EDIT;
869 $groupPermissions[] = CRM_Core_Permission::DELETE;
870 }
871
872 // CRM-9936
873 $reservedPermission = CRM_Core_Permission::check('administer reserved groups');
874
875 $links = self::actionLinks();
876
877 $allTypes = CRM_Core_OptionGroup::values('group_type');
878 $values = $groupsToCount = array();
879
880 $visibility = CRM_Core_SelectValues::ufVisibility();
881
882 while ($object->fetch()) {
883 $permission = CRM_Contact_BAO_Group::checkPermission($object->id, $object->title);
884 //@todo CRM-12209 introduced an ACL check in the whereClause function
885 // it may be that this checking is now obsolete - or that what remains
886 // should be removed to the whereClause (which is also accessed by getCount)
887
888 if ($permission) {
889 $newLinks = $links;
890 $values[$object->id] = array(
891 'class' => array(),
892 'count' => '0',
893 );
894 CRM_Core_DAO::storeValues($object, $values[$object->id]);
895
896 if ($object->saved_search_id) {
897 $values[$object->id]['title'] .= ' (' . ts('Smart Group') . ')';
898 // check if custom search, if so fix view link
899 $customSearchID = CRM_Core_DAO::getFieldValue(
900 'CRM_Contact_DAO_SavedSearch',
901 $object->saved_search_id,
902 'search_custom_id'
903 );
904
905 if ($customSearchID) {
906 $newLinks[CRM_Core_Action::VIEW]['url'] = 'civicrm/contact/search/custom';
907 $newLinks[CRM_Core_Action::VIEW]['qs'] = "reset=1&force=1&ssID={$object->saved_search_id}";
908 }
909 }
910
911 $action = array_sum(array_keys($newLinks));
912
913 // CRM-9936
914 if (array_key_exists('is_reserved', $object)) {
915 //if group is reserved and I don't have reserved permission, suppress delete/edit
916 if ($object->is_reserved && !$reservedPermission) {
917 $action -= CRM_Core_Action::DELETE;
918 $action -= CRM_Core_Action::UPDATE;
919 $action -= CRM_Core_Action::DISABLE;
920 }
921 }
922
923 if (array_key_exists('is_active', $object)) {
924 if ($object->is_active) {
925 $action -= CRM_Core_Action::ENABLE;
926 }
927 else {
928 $values[$object->id]['class'][] = 'disabled';
929 $action -= CRM_Core_Action::VIEW;
930 $action -= CRM_Core_Action::DISABLE;
931 }
932 }
933
934 $action = $action & CRM_Core_Action::mask($groupPermissions);
935
936 $values[$object->id]['visibility'] = $visibility[$values[$object->id]['visibility']];
937
938 $groupsToCount[$object->saved_search_id ? 'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id;
939
940 if (isset($values[$object->id]['group_type'])) {
941 $groupTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR,
942 substr($values[$object->id]['group_type'], 1, -1)
943 );
944 $types = array();
945 foreach ($groupTypes as $type) {
946 $types[] = CRM_Utils_Array::value($type, $allTypes);
947 }
948 $values[$object->id]['group_type'] = implode(', ', $types);
949 }
950 $values[$object->id]['action'] = CRM_Core_Action::formLink($newLinks,
951 $action,
952 array(
953 'id' => $object->id,
954 'ssid' => $object->saved_search_id,
955 ),
956 ts('more'),
957 FALSE,
958 'group.selector.row',
959 'Group',
960 $object->id
961 );
962
963 // If group has children, add class for link to view children
964 $values[$object->id]['is_parent'] = FALSE;
965 if (array_key_exists('children', $values[$object->id])) {
966 $values[$object->id]['class'][] = "crm-group-parent";
967 $values[$object->id]['is_parent'] = TRUE;
968 }
969
970 // If group is a child, add child class
971 if (array_key_exists('parents', $values[$object->id])) {
972 $values[$object->id]['class'][] = "crm-group-child";
973 }
974
975 if ($groupOrg) {
976 if ($object->org_id) {
977 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->org_id}");
978 $values[$object->id]['org_info'] = "<a href='{$contactUrl}'>{$object->org_name}</a>";
979 }
980 else {
981 $values[$object->id]['org_info'] = ''; // Empty cell
982 }
983 }
984 else {
985 $values[$object->id]['org_info'] = NULL; // Collapsed column if all cells are NULL
986 }
987 if ($object->created_id) {
988 $contactUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$object->created_id}");
989 $values[$object->id]['created_by'] = "<a href='{$contactUrl}'>{$object->created_by}</a>";
990 }
991 }
992 }
993
994 // Get group counts - executes one query for regular groups and another for smart groups
995 foreach ($groupsToCount as $table => $groups) {
996 $where = "g.group_id IN (" . implode(',', $groups) . ")";
997 if ($table == 'civicrm_group_contact') {
998 $where .= " AND g.status = 'Added'";
999 }
1000 // Exclude deleted contacts
1001 $where .= " and c.id = g.contact_id AND c.is_deleted = 0";
1002 $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");
1003 while ($dao->fetch()) {
1004 $values[$dao->group_id]['count'] = $dao->count;
1005 }
1006 }
1007
1008 // CRM-16905 - Sort by count cannot be done with sql
1009 if (!empty($params['sort']) && strpos($params['sort'], 'count') === 0) {
1010 usort($values, function($a, $b) {
1011 return $a['count'] - $b['count'];
1012 });
1013 if (strpos($params['sort'], 'desc')) {
1014 $values = array_reverse($values, TRUE);
1015 }
1016 return array_slice($values, $params['offset'], $params['rowCount']);
1017 }
1018
1019 return $values;
1020 }
1021
1022 /**
1023 * This function to get hierarchical list of groups (parent followed by children)
1024 *
1025 * @param array $groupIDs
1026 * Array of group ids.
1027 *
1028 * @param NULL $parents
1029 * @param string $spacer
1030 * @param bool $titleOnly
1031 *
1032 * @return array
1033 */
1034 public static function getGroupsHierarchy(
1035 $groupIDs,
1036 $parents = NULL,
1037 $spacer = '<span class="child-indent"></span>',
1038 $titleOnly = FALSE
1039 ) {
1040 if (empty($groupIDs)) {
1041 return array();
1042 }
1043
1044 $groupIdString = '(' . implode(',', array_keys($groupIDs)) . ')';
1045 // <span class="child-icon"></span>
1046 // need to return id, title (w/ spacer), description, visibility
1047
1048 // We need to build a list of tags ordered by hierarchy and sorted by
1049 // name. The hierarchy will be communicated by an accumulation of
1050 // separators in front of the name to give it a visual offset.
1051 // Instead of recursively making mysql queries, we'll make one big
1052 // query and build the hierarchy with the algorithm below.
1053 $groups = array();
1054 $args = array(1 => array($groupIdString, 'String'));
1055 $query = "
1056 SELECT id, title, description, visibility, parents
1057 FROM civicrm_group
1058 WHERE id IN $groupIdString
1059 ";
1060 if ($parents) {
1061 // group can have > 1 parent so parents may be comma separated list (eg. '1,2,5'). We just grab and match on 1st parent.
1062 $parentArray = explode(',', $parents);
1063 $parent = $parentArray[0];
1064 $args[2] = array($parent, 'Integer');
1065 $query .= " AND SUBSTRING_INDEX(parents, ',', 1) = %2";
1066 }
1067 $query .= " ORDER BY title";
1068 $dao = CRM_Core_DAO::executeQuery($query, $args);
1069
1070 // Sort the groups into the correct storage by the parent
1071 // $roots represent the current leaf nodes that need to be checked for
1072 // children. $rows represent the unplaced nodes
1073 $roots = $rows = $allGroups = array();
1074 while ($dao->fetch()) {
1075 $allGroups[$dao->id] = array(
1076 'title' => $dao->title,
1077 'visibility' => $dao->visibility,
1078 'description' => $dao->description,
1079 );
1080
1081 if ($dao->parents == $parents) {
1082 $roots[] = array(
1083 'id' => $dao->id,
1084 'prefix' => '',
1085 'title' => $dao->title,
1086 );
1087 }
1088 else {
1089 // group can have > 1 parent so $dao->parents may be comma separated list (eg. '1,2,5'). Grab and match on 1st parent.
1090 $parentArray = explode(',', $dao->parents);
1091 $parent = $parentArray[0];
1092 $rows[] = array(
1093 'id' => $dao->id,
1094 'prefix' => '',
1095 'title' => $dao->title,
1096 'parents' => $parent,
1097 );
1098 }
1099 }
1100 $dao->free();
1101 // While we have nodes left to build, shift the first (alphabetically)
1102 // node of the list, place it in our groups list and loop through the
1103 // list of unplaced nodes to find its children. We make a copy to
1104 // iterate through because we must modify the unplaced nodes list
1105 // during the loop.
1106 while (count($roots)) {
1107 $new_roots = array();
1108 $current_rows = $rows;
1109 $root = array_shift($roots);
1110 $groups[$root['id']] = array($root['prefix'], $root['title']);
1111
1112 // As you find the children, append them to the end of the new set
1113 // of roots (maintain alphabetical ordering). Also remove the node
1114 // from the set of unplaced nodes.
1115 if (is_array($current_rows)) {
1116 foreach ($current_rows as $key => $row) {
1117 if ($row['parents'] == $root['id']) {
1118 $new_roots[] = array(
1119 'id' => $row['id'],
1120 'prefix' => $groups[$root['id']][0] . $spacer,
1121 'title' => $row['title'],
1122 );
1123 unset($rows[$key]);
1124 }
1125 }
1126 }
1127
1128 //As a group, insert the new roots into the beginning of the roots
1129 //list. This maintains the hierarchical ordering of the tags.
1130 $roots = array_merge($new_roots, $roots);
1131 }
1132
1133 // below is the redundant looping to ensure child groups are populated in the case where user does not have
1134 // access to parent groups ( esp. using ACL permissions and logged in user can assess only child groups )
1135 foreach ($rows as $value) {
1136 $groups[$value['id']] = array($value['prefix'], $value['title']);
1137 }
1138 // Prefix titles with the calcuated spacing to give the visual
1139 // appearance of ordering when transformed into HTML in the form layer. Add description and visibility.
1140 $groupsReturn = array();
1141 foreach ($groups as $key => $value) {
1142 if ($titleOnly) {
1143 $groupsReturn[$key] = $value[0] . $value[1];
1144 }
1145 else {
1146 $groupsReturn[$key] = array(
1147 'title' => $value[0] . $value[1],
1148 'description' => $allGroups[$key]['description'],
1149 'visibility' => $allGroups[$key]['visibility'],
1150 );
1151 }
1152 }
1153
1154 return $groupsReturn;
1155 }
1156
1157 /**
1158 * @param array $params
1159 *
1160 * @return NULL|string
1161 */
1162 public static function getGroupCount(&$params) {
1163 $whereClause = self::whereClause($params, FALSE);
1164 $query = "SELECT COUNT(*) FROM civicrm_group groups";
1165
1166 if (!empty($params['created_by'])) {
1167 $query .= "
1168 INNER JOIN civicrm_contact createdBy
1169 ON createdBy.id = groups.created_id";
1170 }
1171 $query .= "
1172 WHERE {$whereClause}";
1173 return CRM_Core_DAO::singleValueQuery($query, $params);
1174 }
1175
1176 /**
1177 * Generate permissioned where clause for group search.
1178 * @param array $params
1179 * @param bool $sortBy
1180 * @param bool $excludeHidden
1181 *
1182 * @return string
1183 */
1184 public static function whereClause(&$params, $sortBy = TRUE, $excludeHidden = TRUE) {
1185 $values = array();
1186 $title = CRM_Utils_Array::value('title', $params);
1187 if ($title) {
1188 $clauses[] = "groups.title LIKE %1";
1189 if (strpos($title, '%') !== FALSE) {
1190 $params[1] = array($title, 'String', FALSE);
1191 }
1192 else {
1193 $params[1] = array($title, 'String', TRUE);
1194 }
1195 }
1196
1197 $groupType = CRM_Utils_Array::value('group_type', $params);
1198 if ($groupType) {
1199 $types = explode(',', $groupType);
1200 if (!empty($types)) {
1201 $clauses[] = 'groups.group_type LIKE %2';
1202 $typeString = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $types) . CRM_Core_DAO::VALUE_SEPARATOR;
1203 $params[2] = array($typeString, 'String', TRUE);
1204 }
1205 }
1206
1207 $visibility = CRM_Utils_Array::value('visibility', $params);
1208 if ($visibility) {
1209 $clauses[] = 'groups.visibility = %3';
1210 $params[3] = array($visibility, 'String');
1211 }
1212
1213 $groupStatus = CRM_Utils_Array::value('status', $params);
1214 if ($groupStatus) {
1215 switch ($groupStatus) {
1216 case 1:
1217 $clauses[] = 'groups.is_active = 1';
1218 $params[4] = array($groupStatus, 'Integer');
1219 break;
1220
1221 case 2:
1222 $clauses[] = 'groups.is_active = 0';
1223 $params[4] = array($groupStatus, 'Integer');
1224 break;
1225
1226 case 3:
1227 $clauses[] = '(groups.is_active = 0 OR groups.is_active = 1 )';
1228 break;
1229 }
1230 }
1231
1232 $parentsOnly = CRM_Utils_Array::value('parentsOnly', $params);
1233 if ($parentsOnly) {
1234 $clauses[] = 'groups.parents IS NULL';
1235 }
1236
1237 // only show child groups of a specific parent group
1238 $parent_id = CRM_Utils_Array::value('parent_id', $params);
1239 if ($parent_id) {
1240 $clauses[] = 'groups.id IN (SELECT child_group_id FROM civicrm_group_nesting WHERE parent_group_id = %5)';
1241 $params[5] = array($parent_id, 'Integer');
1242 }
1243
1244 if ($createdBy = CRM_Utils_Array::value('created_by', $params)) {
1245 $clauses[] = "createdBy.sort_name LIKE %6";
1246 if (strpos($createdBy, '%') !== FALSE) {
1247 $params[6] = array($createdBy, 'String', FALSE);
1248 }
1249 else {
1250 $params[6] = array($createdBy, 'String', TRUE);
1251 }
1252 }
1253
1254 if (empty($clauses)) {
1255 $clauses[] = 'groups.is_active = 1';
1256 }
1257
1258 if ($excludeHidden) {
1259 $clauses[] = 'groups.is_hidden = 0';
1260 }
1261
1262 $clauses[] = self::getPermissionClause();
1263
1264 return implode(' AND ', $clauses);
1265 }
1266
1267 /**
1268 * Define action links.
1269 *
1270 * @return array
1271 * array of action links
1272 */
1273 public static function actionLinks() {
1274 $links = array(
1275 CRM_Core_Action::VIEW => array(
1276 'name' => ts('Contacts'),
1277 'url' => 'civicrm/group/search',
1278 'qs' => 'reset=1&force=1&context=smog&gid=%%id%%',
1279 'title' => ts('Group Contacts'),
1280 ),
1281 CRM_Core_Action::UPDATE => array(
1282 'name' => ts('Settings'),
1283 'url' => 'civicrm/group',
1284 'qs' => 'reset=1&action=update&id=%%id%%',
1285 'title' => ts('Edit Group'),
1286 ),
1287 CRM_Core_Action::DISABLE => array(
1288 'name' => ts('Disable'),
1289 'ref' => 'crm-enable-disable',
1290 'title' => ts('Disable Group'),
1291 ),
1292 CRM_Core_Action::ENABLE => array(
1293 'name' => ts('Enable'),
1294 'ref' => 'crm-enable-disable',
1295 'title' => ts('Enable Group'),
1296 ),
1297 CRM_Core_Action::DELETE => array(
1298 'name' => ts('Delete'),
1299 'url' => 'civicrm/group',
1300 'qs' => 'reset=1&action=delete&id=%%id%%',
1301 'title' => ts('Delete Group'),
1302 ),
1303 );
1304
1305 return $links;
1306 }
1307
1308 /**
1309 * @param $whereClause
1310 * @param array $whereParams
1311 *
1312 * @return string
1313 */
1314 public function pagerAtoZ($whereClause, $whereParams) {
1315 $query = "
1316 SELECT DISTINCT UPPER(LEFT(groups.title, 1)) as sort_name
1317 FROM civicrm_group groups
1318 WHERE $whereClause
1319 ORDER BY LEFT(groups.title, 1)
1320 ";
1321 $dao = CRM_Core_DAO::executeQuery($query, $whereParams);
1322
1323 return CRM_Utils_PagerAToZ::getAToZBar($dao, $this->_sortByCharacter, TRUE);
1324 }
1325
1326 /**
1327 * Assign Test Value.
1328 *
1329 * @param string $fieldName
1330 * @param array $fieldDef
1331 * @param int $counter
1332 */
1333 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
1334 if ($fieldName == 'children' || $fieldName == 'parents') {
1335 $this->{$fieldName} = "NULL";
1336 }
1337 else {
1338 parent::assignTestValues($fieldName, $fieldDef, $counter);
1339 }
1340 }
1341
1342 }