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