Merge pull request #5554 from eileenmcnaughton/CRM-16255
[civicrm-core.git] / CRM / Admin / Form / Options.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 generates form components for Options
38 *
39 */
40 class CRM_Admin_Form_Options extends CRM_Admin_Form {
41
42 /**
43 * The option group name.
44 *
45 * @var array
46 */
47 protected $_gName;
48
49 /**
50 * The option group name in display format (capitalized, without underscores...etc)
51 *
52 * @var array
53 */
54 protected $_gLabel;
55
56 /**
57 * Pre-process
58 *
59 * @return void
60 */
61 public function preProcess() {
62 parent::preProcess();
63 $session = CRM_Core_Session::singleton();
64 if (!$this->_gName && !empty($this->urlPath[3])) {
65 $this->_gName = $this->urlPath[3];
66 }
67 if (!$this->_gName && !empty($_GET['gid'])) {
68 $this->_gName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', (int) $_GET['gid'], 'name');
69 }
70 if ($this->_gName) {
71 $this->set('gName', $this->_gName);
72 }
73 else {
74 $this->_gName = $this->get('gName');
75 }
76 $this->_gid = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup',
77 $this->_gName,
78 'id',
79 'name'
80 );
81 $this->_gLabel = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $this->_gid, 'title');
82 $url = "civicrm/admin/options/{$this->_gName}";
83 $params = "reset=1";
84
85 if (($this->_action & CRM_Core_Action::DELETE) &&
86 in_array($this->_gName, array('email_greeting', 'postal_greeting', 'addressee'))
87 ) {
88 // Don't allow delete if the option value belongs to addressee, postal or email greetings and is in use.
89 $findValue = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'value');
90 $queryParam = array(1 => array($findValue, 'Integer'));
91 $columnName = $this->_gName . "_id";
92 $sql = "SELECT count(id) FROM civicrm_contact WHERE " . $columnName . " = %1";
93 $isInUse = CRM_Core_DAO::singleValueQuery($sql, $queryParam);
94 if ($isInUse) {
95 $scriptURL = "<a href='" . CRM_Utils_System::docURL2('Update Greetings and Address Data for Contacts', TRUE, NULL, NULL, NULL, "wiki") . "'>" . ts('Learn more about a script that can automatically update contact addressee and greeting options.') . "</a>";
96 CRM_Core_Session::setStatus(ts('The selected %1 option has <strong>not been deleted</strong> because it is currently in use. Please update these contacts to use a different format before deleting this option. %2', array(
97 1 => $this->_gLabel,
98 2 => $scriptURL,
99 )), ts('Sorry'), 'error');
100 $redirect = CRM_Utils_System::url($url, $params);
101 CRM_Utils_System::redirect($redirect);
102 }
103 }
104
105 $session->pushUserContext(CRM_Utils_System::url($url, $params));
106 $this->assign('id', $this->_id);
107
108 if ($this->_id && in_array($this->_gName, CRM_Core_OptionGroup::$_domainIDGroups)) {
109 $domainID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'domain_id', 'id');
110 if (CRM_Core_Config::domainID() != $domainID) {
111 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
112 }
113 }
114 }
115
116 /**
117 * Set default values for the form.
118 *
119 * @return void
120 */
121 public function setDefaultValues() {
122 $defaults = parent::setDefaultValues();
123
124 // Default weight & value
125 $fieldValues = array('option_group_id' => $this->_gid);
126 foreach (array('weight', 'value') as $field) {
127 if (empty($defaults[$field])) {
128 $defaults[$field] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues, $field);
129 }
130 }
131
132 //setDefault of contact types for email greeting, postal greeting, addressee, CRM-4575
133 if (in_array($this->_gName, array(
134 'email_greeting',
135 'postal_greeting',
136 'addressee',
137 ))) {
138 $defaults['contactOptions'] = (CRM_Utils_Array::value('filter', $defaults)) ? $defaults['filter'] : NULL;
139 }
140 // CRM-11516
141 if ($this->_gName == 'payment_instrument' && $this->_id) {
142 $defaults['financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($this->_id, 'civicrm_option_value', 'financial_account_id');
143 }
144 return $defaults;
145 }
146
147 /**
148 * Build the form object.
149 *
150 * @return void
151 */
152 public function buildQuickForm() {
153 parent::buildQuickForm();
154 $this->setPageTitle(ts('%1 Option', array(1 => $this->_gLabel)));
155
156 if ($this->_action & CRM_Core_Action::DELETE) {
157 return;
158 }
159
160 $this->applyFilter('__ALL__', 'trim');
161
162 $isReserved = FALSE;
163 if ($this->_id) {
164 $isReserved = (bool) CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'is_reserved');
165 }
166
167 $this->add('text',
168 'label',
169 ts('Label'),
170 CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'),
171 TRUE
172 );
173
174 $this->add('text',
175 'value',
176 ts('Value'),
177 CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'),
178 TRUE
179 );
180 if (!in_array($this->_gName, array(
181 'email_greeting',
182 'postal_greeting',
183 'addressee',
184 )) && !$isReserved
185 ) {
186 $this->addRule('label',
187 ts('This Label already exists in the database for this option group. Please select a different Value.'),
188 'optionExists',
189 array('CRM_Core_DAO_OptionValue', $this->_id, $this->_gid, 'label')
190 );
191 }
192
193 if ($this->_gName == 'case_status') {
194 $classes = array(
195 'Opened' => ts('Opened'),
196 'Closed' => ts('Closed'),
197 );
198
199 $grouping = $this->add('select',
200 'grouping',
201 ts('Status Class'),
202 $classes
203 );
204 if ($isReserved) {
205 $grouping->freeze();
206 }
207 }
208 // CRM-11516
209 if ($this->_gName == 'payment_instrument') {
210 $accountType = CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name = 'Asset' ");
211 $financialAccount = CRM_Contribute_PseudoConstant::financialAccount(NULL, key($accountType));
212
213 $this->add('select', 'financial_account_id', ts('Financial Account'),
214 array('' => ts('- select -')) + $financialAccount,
215 TRUE
216 );
217 }
218
219 $required = FALSE;
220 if ($this->_gName == 'custom_search') {
221 $required = TRUE;
222 }
223 elseif ($this->_gName == 'redaction_rule' || $this->_gName == 'engagement_index') {
224 $this->add('text',
225 'value',
226 ts('Value'),
227 CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'),
228 TRUE
229 );
230 if ($this->_gName == 'redaction_rule') {
231 $this->add('checkbox',
232 'filter',
233 ts('Regular Expression?')
234 );
235 }
236 }
237 if ($this->_gName == 'participant_listing') {
238 $this->add('text',
239 'description',
240 ts('Description'),
241 CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'description')
242 );
243 }
244 else {
245 // Hard-coding attributes here since description is still stored as varchar and not text in the schema. dgg
246 $this->addWysiwyg('description',
247 ts('Description'),
248 array('rows' => 4, 'cols' => 80),
249 $required
250 );
251 }
252
253 if ($this->_gName == 'event_badge') {
254 $this->add('text',
255 'name',
256 ts('Class Name'),
257 CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'name')
258 );
259 }
260
261 $this->add('text',
262 'weight',
263 ts('Order'),
264 CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'weight'),
265 TRUE
266 );
267 $this->addRule('weight', ts('is a numeric field'), 'numeric');
268
269 // If CiviCase enabled AND "Add" mode OR "edit" mode for non-reserved activities, only allow user to pick Core or CiviCase component.
270 // FIXME: Each component should define whether adding new activity types is allowed.
271 $config = CRM_Core_Config::singleton();
272 if ($this->_gName == 'activity_type' && in_array("CiviCase", $config->enableComponents) &&
273 (($this->_action & CRM_Core_Action::ADD) || !$isReserved)
274 ) {
275 $caseID = CRM_Core_Component::getComponentID('CiviCase');
276 $components = array('' => ts('Contacts AND Cases'), $caseID => ts('Cases Only'));
277 $this->add('select',
278 'component_id',
279 ts('Component'),
280 $components, FALSE
281 );
282 }
283
284 $enabled = $this->add('checkbox', 'is_active', ts('Enabled?'));
285
286 if ($isReserved) {
287 $enabled->freeze();
288 }
289
290 //fix for CRM-3552, CRM-4575
291 $showIsDefaultGroups = array(
292 'email_greeting',
293 'postal_greeting',
294 'addressee',
295 'from_email_address',
296 'case_status',
297 'encounter_medium',
298 'case_type',
299 'payment_instrument',
300 'communication_style',
301 'soft_credit_type',
302 'website_type',
303 );
304
305 if (in_array($this->_gName, $showIsDefaultGroups)) {
306 $this->assign('showDefault', TRUE);
307 $this->add('checkbox', 'is_default', ts('Default Option?'));
308 }
309
310 //get contact type for which user want to create a new greeting/addressee type, CRM-4575
311 if (in_array($this->_gName, array(
312 'email_greeting',
313 'postal_greeting',
314 'addressee',
315 )) && !$isReserved
316 ) {
317 $values = array(
318 1 => ts('Individual'),
319 2 => ts('Household'),
320 3 => ts('Organization'),
321 4 => ts('Multiple Contact Merge'),
322 );
323 $this->add('select', 'contactOptions', ts('Contact Type'), array('' => '-select-') + $values, TRUE);
324 $this->assign('showContactFilter', TRUE);
325 }
326
327 if ($this->_gName == 'participant_status') {
328 // For Participant Status options, expose the 'filter' field to track which statuses are "Counted", and the Visibility field
329 $element = $this->add('checkbox', 'filter', ts('Counted?'));
330 $this->add('select', 'visibility_id', ts('Visibility'), CRM_Core_PseudoConstant::visibility());
331 }
332 if ($this->_gName == 'participant_role') {
333 // For Participant Role options, expose the 'filter' field to track which statuses are "Counted"
334 $this->add('checkbox', 'filter', ts('Counted?'));
335 }
336
337 $this->addFormRule(array('CRM_Admin_Form_Options', 'formRule'), $this);
338 }
339
340 /**
341 * Global form rule.
342 *
343 * @param array $fields
344 * The input form values.
345 * @param array $files
346 * The uploaded files if any.
347 * @param array $self
348 * Current form object.
349 *
350 * @return array
351 * array of errors / empty array.
352 */
353 public static function formRule($fields, $files, $self) {
354 $errors = array();
355 if ($self->_gName == 'case_status' && empty($fields['grouping'])) {
356 $errors['grouping'] = ts('Status class is a required field');
357 }
358
359 if (in_array($self->_gName, array(
360 'email_greeting',
361 'postal_greeting',
362 'addressee',
363 )) && empty($self->_defaultValues['is_reserved'])
364 ) {
365 $label = $fields['label'];
366 $condition = " AND v.label = '{$label}' ";
367 $values = CRM_Core_OptionGroup::values($self->_gName, FALSE, FALSE, FALSE, $condition, 'filter');
368 $checkContactOptions = TRUE;
369
370 if ($self->_id && ($self->_defaultValues['contactOptions'] == $fields['contactOptions'])) {
371 $checkContactOptions = FALSE;
372 }
373
374 if ($checkContactOptions && in_array($fields['contactOptions'], $values)) {
375 $errors['label'] = ts('This Label already exists in the database for the selected contact type.');
376 }
377 }
378
379 if ($self->_gName == 'from_email_address') {
380 $formEmail = CRM_Utils_Mail::pluckEmailFromHeader($fields['label']);
381 if (!CRM_Utils_Rule::email($formEmail)) {
382 $errors['label'] = ts('Please enter a valid email address.');
383 }
384
385 $formName = explode('"', $fields['label']);
386 if (empty($formName[1]) || count($formName) != 3) {
387 $errors['label'] = ts('Please follow the proper format for From Email Address');
388 }
389 }
390
391 return $errors;
392 }
393
394 /**
395 * Process the form submission.
396 *
397 *
398 * @return void
399 */
400 public function postProcess() {
401 if ($this->_action & CRM_Core_Action::DELETE) {
402 $fieldValues = array('option_group_id' => $this->_gid);
403 $wt = CRM_Utils_Weight::delWeight('CRM_Core_DAO_OptionValue', $this->_id, $fieldValues);
404
405 if (CRM_Core_BAO_OptionValue::del($this->_id)) {
406 if ($this->_gName == 'phone_type') {
407 CRM_Core_BAO_Phone::setOptionToNull(CRM_Utils_Array::value('value', $this->_defaultValues));
408 }
409
410 CRM_Core_Session::setStatus(ts('Selected %1 type has been deleted.', array(1 => $this->_gLabel)), ts('Record Deleted'), 'success');
411 }
412 else {
413 CRM_Core_Session::setStatus(ts('Selected %1 type has not been deleted.', array(1 => $this->_gLabel)), ts('Sorry'), 'error');
414 CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_OptionValue', $fieldValues);
415 }
416 }
417 else {
418 $params = $ids = array();
419 $params = $this->exportValues();
420
421 // allow multiple defaults within group.
422 $allowMultiDefaults = array('email_greeting', 'postal_greeting', 'addressee', 'from_email_address');
423 if (in_array($this->_gName, $allowMultiDefaults)) {
424 if ($this->_gName == 'from_email_address') {
425 $params['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID());
426 }
427 elseif ($filter = CRM_Utils_Array::value('contactOptions', $params)) {
428 $params['filter'] = $filter;
429 $params['reset_default_for'] = array('filter' => "0, " . $params['filter']);
430 }
431
432 //make sure we should has to have space, CRM-6977
433 if ($this->_gName == 'from_email_address') {
434 $params['label'] = str_replace('"<', '" <', $params['label']);
435 }
436 }
437
438 // set value of filter if not present in params
439 if ($this->_id && !array_key_exists('filter', $params)) {
440 if ($this->_gName == 'participant_role') {
441 $params['filter'] = 0;
442 }
443 else {
444 $params['filter'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_id, 'filter', 'id');
445 }
446 }
447
448 $groupParams = array('name' => ($this->_gName));
449 $optionValue = CRM_Core_OptionValue::addOptionValue($params, $groupParams, $this->_action, $this->_id);
450
451 // CRM-11516
452 if (!empty($params['financial_account_id'])) {
453 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
454 $params = array(
455 'entity_table' => 'civicrm_option_value',
456 'entity_id' => $optionValue->id,
457 'account_relationship' => $relationTypeId,
458 'financial_account_id' => $params['financial_account_id'],
459 );
460 CRM_Financial_BAO_FinancialTypeAccount::add($params);
461 }
462
463 CRM_Core_Session::setStatus(ts('The %1 \'%2\' has been saved.', array(
464 1 => $this->_gLabel,
465 2 => $optionValue->label,
466 )), ts('Saved'), 'success');
467 }
468 }
469
470 }