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