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