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