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