a6733dea09e3c8587e48707efa1ef8fbf830b963
[civicrm-core.git] / CRM / Group / Form / Edit.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35
36 /**
37 * This class is to build the form for adding Group
38 */
39 class CRM_Group_Form_Edit extends CRM_Core_Form {
40
41 /**
42 * The group id, used when editing a group
43 *
44 * @var int
45 */
46 protected $_id;
47
48 /**
49 * The group object, if an id is present
50 *
51 * @var object
52 */
53 protected $_group;
54
55 /**
56 * The title of the group being deleted
57 *
58 * @var string
59 */
60 protected $_title;
61
62 /**
63 * Store the group values
64 *
65 * @var array
66 */
67 protected $_groupValues;
68
69 /**
70 * What blocks should we show and hide.
71 *
72 * @var CRM_Core_ShowHideBlocks
73 */
74 protected $_showHide;
75
76 /**
77 * The civicrm_group_organization table id
78 *
79 * @var int
80 */
81 protected $_groupOrganizationID;
82
83 /**
84 * Set up variables to build the form.
85 *
86 * @return void
87 * @acess protected
88 */
89 public function preProcess() {
90 $this->_id = $this->get('id');
91 if ($this->_id) {
92 $breadCrumb = array(
93 array(
94 'title' => ts('Manage Groups'),
95 'url' => CRM_Utils_System::url('civicrm/group',
96 'reset=1'
97 ),
98 ),
99 );
100 CRM_Utils_System::appendBreadCrumb($breadCrumb);
101
102 $this->_groupValues = array();
103 $params = array('id' => $this->_id);
104 $this->_group = CRM_Contact_BAO_Group::retrieve($params, $this->_groupValues);
105 $this->_title = $this->_groupValues['title'];
106 }
107
108 $this->assign('action', $this->_action);
109 $this->assign('showBlockJS', TRUE);
110
111 if ($this->_action == CRM_Core_Action::DELETE) {
112 if (isset($this->_id)) {
113 $this->assign('title', $this->_title);
114 $this->assign('count', CRM_Contact_BAO_Group::memberCount($this->_id));
115 CRM_Utils_System::setTitle(ts('Confirm Group Delete'));
116 }
117 if ($this->_groupValues['is_reserved'] == 1 && !CRM_Core_Permission::check('administer reserved groups')) {
118 CRM_Core_Error::statusBounce(ts("You do not have sufficient permission to delete this reserved group."));
119 }
120 }
121 else {
122 if ($this->_groupValues['is_reserved'] == 1 && !CRM_Core_Permission::check('administer reserved groups')) {
123 CRM_Core_Error::statusBounce(ts("You do not have sufficient permission to change settings for this reserved group."));
124 }
125 if (isset($this->_id)) {
126 $groupValues = array(
127 'id' => $this->_id,
128 'title' => $this->_title,
129 'saved_search_id' => isset($this->_groupValues['saved_search_id']) ? $this->_groupValues['saved_search_id'] : '',
130 );
131 if (isset($this->_groupValues['saved_search_id'])) {
132 $groupValues['mapping_id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch',
133 $this->_groupValues['saved_search_id'],
134 'mapping_id'
135 );
136 $groupValues['search_custom_id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_SavedSearch',
137 $this->_groupValues['saved_search_id'],
138 'search_custom_id'
139 );
140 }
141 if (!empty($this->_groupValues['created_id'])) {
142 $groupValues['created_by'] = CRM_Core_DAO::getFieldValue("CRM_Contact_DAO_Contact", $this->_groupValues['created_id'], 'sort_name', 'id');
143 }
144
145 if (!empty($this->_groupValues['modified_id'])) {
146 $groupValues['modified_by'] = CRM_Core_DAO::getFieldValue("CRM_Contact_DAO_Contact", $this->_groupValues['modified_id'], 'sort_name', 'id');
147 }
148
149 $this->assign_by_ref('group', $groupValues);
150
151 CRM_Utils_System::setTitle(ts('Group Settings: %1', array(1 => $this->_title)));
152 }
153 $session = CRM_Core_Session::singleton();
154 $session->pushUserContext(CRM_Utils_System::url('civicrm/group', 'reset=1'));
155 }
156
157 //build custom data
158 CRM_Custom_Form_CustomData::preProcess($this, NULL, NULL, 1, 'Group', $this->_id);
159 }
160
161 /**
162 * Set default values for the form. LocationType that in edit/view mode
163 * the default values are retrieved from the database
164 *
165 * @return array
166 */
167 public function setDefaultValues() {
168 $defaults = array();
169
170 if (isset($this->_id)) {
171 $defaults = $this->_groupValues;
172 if (!empty($defaults['group_type'])) {
173 $types = explode(CRM_Core_DAO::VALUE_SEPARATOR,
174 substr($defaults['group_type'], 1, -1)
175 );
176 $defaults['group_type'] = array();
177 foreach ($types as $type) {
178 $defaults['group_type'][$type] = 1;
179 }
180 }
181
182 if (CRM_Core_Permission::check('administer Multiple Organizations') && CRM_Core_Permission::isMultisiteEnabled()) {
183 CRM_Contact_BAO_GroupOrganization::retrieve($this->_id, $defaults);
184 }
185 }
186
187 if (!((CRM_Core_Permission::check('access CiviMail')) ||
188 (CRM_Mailing_Info::workflowEnabled() &&
189 CRM_Core_Permission::check('create mailings')
190 )
191 )
192 ) {
193 $groupTypes = CRM_Core_OptionGroup::values('group_type', TRUE);
194 if ($defaults['group_type'][$groupTypes['Mailing List']] == 1) {
195 $this->assign('freezeMailignList', $groupTypes['Mailing List']);
196 }
197 else {
198 $this->assign('hideMailignList', $groupTypes['Mailing List']);
199 }
200 }
201
202 if (empty($defaults['parents'])) {
203 $defaults['parents'] = CRM_Core_BAO_Domain::getGroupId();
204 }
205
206 // custom data set defaults
207 $defaults += CRM_Custom_Form_CustomData::setDefaultValues($this);
208 return $defaults;
209 }
210
211 /**
212 * Build the form object.
213 *
214 * @return void
215 */
216 public function buildQuickForm() {
217 if ($this->_action == CRM_Core_Action::DELETE) {
218 $this->addButtons(array(
219 array(
220 'type' => 'next',
221 'name' => ts('Delete Group'),
222 'isDefault' => TRUE,
223 ),
224 array(
225 'type' => 'cancel',
226 'name' => ts('Cancel'),
227 ),
228 )
229 );
230 return;
231 }
232
233 // We want the "new group" form to redirect the user
234 if ($this->_action == CRM_Core_Action::ADD) {
235 $this->preventAjaxSubmit();
236 }
237
238 $this->applyFilter('__ALL__', 'trim');
239 $this->add('text', 'title', ts('Name') . ' ',
240 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title'), TRUE
241 );
242
243 $this->add('textarea', 'description', ts('Description') . ' ',
244 CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'description')
245 );
246
247 $groupTypes = CRM_Core_OptionGroup::values('group_type', TRUE);
248 $config = CRM_Core_Config::singleton();
249 if (isset($this->_id) && !empty($this->_groupValues['saved_search_id'])) {
250 unset($groupTypes['Access Control']);
251 }
252
253 if (!empty($groupTypes)) {
254 $this->addCheckBox('group_type',
255 ts('Group Type'),
256 $groupTypes,
257 NULL, NULL, NULL, NULL, '&nbsp;&nbsp;&nbsp;'
258 );
259 }
260
261 $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::groupVisibility(), TRUE);
262
263 //CRM-14190
264 $parentGroups = self::buildParentGroups($this);
265
266 if (CRM_Core_Permission::check('administer Multiple Organizations') && CRM_Core_Permission::isMultisiteEnabled()) {
267 //group organization Element
268 $props = array('api' => array('params' => array('contact_type' => 'Organization')));
269 $this->addEntityRef('organization_id', ts('Organization'), $props);
270 }
271
272 // is_reserved property CRM-9936
273 $this->addElement('checkbox', 'is_reserved', ts('Reserved Group?'));
274 if (!CRM_Core_Permission::check('administer reserved groups')) {
275 $this->freeze('is_reserved');
276 }
277
278 //build custom data
279 CRM_Custom_Form_CustomData::buildQuickForm($this);
280
281 $this->addButtons(array(
282 array(
283 'type' => 'upload',
284 'name' => ($this->_action == CRM_Core_Action::ADD) ? ts('Continue') : ts('Save'),
285 'isDefault' => TRUE,
286 ),
287 array(
288 'type' => 'cancel',
289 'name' => ts('Cancel'),
290 ),
291 )
292 );
293
294 $doParentCheck = FALSE;
295 if (CRM_Core_Permission::isMultisiteEnabled()) {
296 $doParentCheck = ($this->_id && CRM_Core_BAO_Domain::isDomainGroup($this->_id)) ? FALSE : TRUE;
297 }
298
299 $options = array(
300 'selfObj' => $this,
301 'parentGroups' => $parentGroups,
302 'doParentCheck' => $doParentCheck,
303 );
304 $this->addFormRule(array('CRM_Group_Form_Edit', 'formRule'), $options);
305 }
306
307 /**
308 * Global validation rules for the form.
309 *
310 * @param array $fields
311 * Posted values of the form.
312 * @param array $fileParams
313 * @param $options
314 *
315 * @return array
316 * list of errors to be posted back to the form
317 */
318 public static function formRule($fields, $fileParams, $options) {
319 $errors = array();
320
321 $doParentCheck = $options['doParentCheck'];
322 $self = &$options['selfObj'];
323
324 if ($doParentCheck) {
325 $parentGroups = $options['parentGroups'];
326
327 $grpRemove = 0;
328 foreach ($fields as $key => $val) {
329 if (substr($key, 0, 20) == 'remove_parent_group_') {
330 $grpRemove++;
331 }
332 }
333
334 $grpAdd = 0;
335 if (!empty($fields['parents'])) {
336 $grpAdd++;
337 }
338
339 if ((count($parentGroups) >= 1) && (($grpRemove - $grpAdd) >= count($parentGroups))) {
340 $errors['parents'] = ts('Make sure at least one parent group is set.');
341 }
342 }
343
344 // do check for both name and title uniqueness
345 if (!empty($fields['title'])) {
346 $title = trim($fields['title']);
347 $query = "
348 SELECT count(*)
349 FROM civicrm_group
350 WHERE title = %1
351 ";
352 $params = array(1 => array($title, 'String'));
353
354 if ($self->_id) {
355 $query .= "AND id <> %2";
356 $params[2] = array($self->_id, 'Integer');
357 }
358
359 $grpCnt = CRM_Core_DAO::singleValueQuery($query, $params);
360 if ($grpCnt) {
361 $errors['title'] = ts('Group \'%1\' already exists.', array(1 => $fields['title']));
362 }
363 }
364
365 return empty($errors) ? TRUE : $errors;
366 }
367
368 /**
369 * Process the form when submitted.
370 *
371 * @return void
372 */
373 public function postProcess() {
374 CRM_Utils_System::flushCache('CRM_Core_DAO_Group');
375
376 $updateNestingCache = FALSE;
377 if ($this->_action & CRM_Core_Action::DELETE) {
378 CRM_Contact_BAO_Group::discard($this->_id);
379 CRM_Core_Session::setStatus(ts("The Group '%1' has been deleted.", array(1 => $this->_title)), ts('Group Deleted'), 'success');
380 $updateNestingCache = TRUE;
381 }
382 else {
383 // store the submitted values in an array
384 $params = $this->controller->exportValues($this->_name);
385
386 $params['is_active'] = CRM_Utils_Array::value('is_active', $this->_groupValues, 1);
387
388 if ($this->_action & CRM_Core_Action::UPDATE) {
389 $params['id'] = $this->_id;
390 }
391
392 if ($this->_action & CRM_Core_Action::UPDATE && isset($this->_groupOrganizationID)) {
393 $params['group_organization'] = $this->_groupOrganizationID;
394 }
395
396 $params['is_reserved'] = CRM_Utils_Array::value('is_reserved', $params, FALSE);
397
398 $customFields = CRM_Core_BAO_CustomField::getFields('Group');
399 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
400 $customFields,
401 $this->_id,
402 'Group'
403 );
404
405 $group = CRM_Contact_BAO_Group::create($params);
406
407 //Remove any parent groups requested to be removed
408 if (!empty($this->_groupValues['parents'])) {
409 $parentGroupIds = explode(',', $this->_groupValues['parents']);
410 foreach ($parentGroupIds as $parentGroupId) {
411 if (isset($params["remove_parent_group_$parentGroupId"])) {
412 CRM_Contact_BAO_GroupNesting::remove($parentGroupId, $group->id);
413 $updateNestingCache = TRUE;
414 }
415 }
416 }
417
418 CRM_Core_Session::setStatus(ts('The Group \'%1\' has been saved.', array(1 => $group->title)), ts('Group Saved'), 'success');
419
420 // Add context to the session, in case we are adding members to the group
421 if ($this->_action & CRM_Core_Action::ADD) {
422 $this->set('context', 'amtg');
423 $this->set('amtgID', $group->id);
424
425 $session = CRM_Core_Session::singleton();
426 $session->pushUserContext(CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $group->id));
427 }
428 }
429
430 // update the nesting cache
431 if ($updateNestingCache) {
432 CRM_Contact_BAO_GroupNestingCache::update();
433 }
434 }
435
436 /**
437 * Build parent groups form elements.
438 *
439 * @param CRM_Core_Form $form
440 *
441 * @return array
442 * parent groups
443 */
444 public static function buildParentGroups(&$form) {
445 $groupNames = CRM_Core_PseudoConstant::group();
446 $parentGroups = $parentGroupElements = array();
447 if (isset($form->_id) && !empty($form->_groupValues['parents'])) {
448 $parentGroupIds = explode(',', $form->_groupValues['parents']);
449 foreach ($parentGroupIds as $parentGroupId) {
450 $parentGroups[$parentGroupId] = $groupNames[$parentGroupId];
451 if (array_key_exists($parentGroupId, $groupNames)) {
452 $parentGroupElements[$parentGroupId] = $groupNames[$parentGroupId];
453 $form->addElement('checkbox', "remove_parent_group_$parentGroupId",
454 $groupNames[$parentGroupId]
455 );
456 }
457 }
458 }
459 $form->assign_by_ref('parent_groups', $parentGroupElements);
460
461 if (isset($form->_id)) {
462 $potentialParentGroupIds = CRM_Contact_BAO_GroupNestingCache::getPotentialCandidates($form->_id, $groupNames);
463 }
464 else {
465 $potentialParentGroupIds = array_keys($groupNames);
466 }
467
468 $parentGroupSelectValues = array('' => '- ' . ts('select group') . ' -');
469 foreach ($potentialParentGroupIds as $potentialParentGroupId) {
470 if (array_key_exists($potentialParentGroupId, $groupNames)) {
471 $parentGroupSelectValues[$potentialParentGroupId] = $groupNames[$potentialParentGroupId];
472 }
473 }
474
475 if (count($parentGroupSelectValues) > 1) {
476 if (CRM_Core_Permission::isMultisiteEnabled()) {
477 $required = !isset($form->_id) || ($form->_id && CRM_Core_BAO_Domain::isDomainGroup($form->_id)) ? FALSE : empty($parentGroups);
478 }
479 else {
480 $required = FALSE;
481 }
482 $form->add('select', 'parents', ts('Add Parent'), $parentGroupSelectValues, $required, array('class' => 'crm-select2'));
483 }
484
485 return $parentGroups;
486 }
487
488 }