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