Merge pull request #15584 from civicrm/5.19
[civicrm-core.git] / CRM / Admin / Form / SettingTrait.php
CommitLineData
946389fb 1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
946389fb 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
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
946389fb 32 */
33
34/**
35 * This trait allows us to consolidate Preferences & Settings forms.
36 *
37 * It is intended mostly as part of a refactoring process to get rid of having 2.
38 */
39trait CRM_Admin_Form_SettingTrait {
40
51f35276
FG
41 /**
42 * The setting page filter.
43 *
44 * @var string
45 */
46 private $_filter;
47
946389fb 48 /**
49 * @var array
50 */
51 protected $settingsMetadata;
52
53 /**
54 * Get default entity.
55 *
56 * @return string
57 */
58 public function getDefaultEntity() {
59 return 'Setting';
60 }
61
62 /**
63 * Get the metadata relating to the settings on the form, ordered by the keys in $this->_settings.
64 *
65 * @return array
66 */
67 protected function getSettingsMetaData() {
68 if (empty($this->settingsMetadata)) {
4cc9fbc2 69 $this->settingsMetadata = \Civi\Core\SettingsMetadata::getMetadata(['name' => array_keys($this->_settings)], NULL, TRUE);
946389fb 70 // This array_merge re-orders to the key order of $this->_settings.
71 $this->settingsMetadata = array_merge($this->_settings, $this->settingsMetadata);
72 }
73 return $this->settingsMetadata;
74 }
75
76 /**
77 * Get the settings which can be stored based on metadata.
78 *
79 * @param array $params
80 * @return array
81 */
82 protected function getSettingsToSetByMetadata($params) {
74f89a9f 83 $setValues = array_intersect_key($params, $this->_settings);
84 // Checkboxes will be unset rather than empty so we need to add them back in.
85 // Handle quickform hateability just once, right here right now.
86 $unsetValues = array_diff_key($this->_settings, $params);
87 foreach ($unsetValues as $key => $unsetValue) {
88 if ($this->getQuickFormType($this->getSettingMetadata($key)) === 'CheckBox') {
89 $setValues[$key] = [$key => 0];
90 }
91 }
92 return $setValues;
946389fb 93 }
94
95 /**
96 * @param $params
97 */
98 protected function filterParamsSetByMetadata(&$params) {
99 foreach ($this->getSettingsToSetByMetadata($params) as $setting => $settingGroup) {
100 //@todo array_diff this
101 unset($params[$setting]);
102 }
103 }
104
6821aa1d 105 /**
106 * Get the metadata for a particular field.
107 *
108 * @param $setting
109 * @return mixed
110 */
111 protected function getSettingMetadata($setting) {
112 return $this->getSettingsMetaData()[$setting];
113 }
114
115 /**
116 * Get the metadata for a particular field for a particular item.
117 *
118 * e.g get 'serialize' key, if exists, for a field.
119 *
120 * @param $setting
62d3ee27 121 * @param $item
6821aa1d 122 * @return mixed
123 */
124 protected function getSettingMetadataItem($setting, $item) {
125 return CRM_Utils_Array::value($item, $this->getSettingsMetaData()[$setting]);
126 }
127
51f35276
FG
128 /**
129 * @return string
130 */
131 protected function getSettingPageFilter() {
132 if (!isset($this->_filter)) {
133 // Get the last URL component without modifying the urlPath property.
134 $urlPath = array_values($this->urlPath);
135 $this->_filter = end($urlPath);
136 }
137 return $this->_filter;
138 }
139
140 /**
141 * Returns a re-keyed copy of the settings, ordered by weight.
142 *
143 * @return array
144 */
145 protected function getSettingsOrderedByWeight() {
146 $settingMetaData = $this->getSettingsMetaData();
147 $filter = $this->getSettingPageFilter();
148
149 usort($settingMetaData, function ($a, $b) use ($filter) {
150 // Handle cases in which a comparison is impossible. Such will be considered ties.
151 if (
152 // A comparison can't be made unless both setting weights are declared.
153 !isset($a['settings_pages'][$filter]['weight'], $b['settings_pages'][$filter]['weight'])
154 // A pair of settings might actually have the same weight.
155 || $a['settings_pages'][$filter]['weight'] === $b['settings_pages'][$filter]['weight']
156 ) {
157 return 0;
158 }
159
160 return $a['settings_pages'][$filter]['weight'] > $b['settings_pages'][$filter]['weight'] ? 1 : -1;
161 });
162
163 return $settingMetaData;
164 }
165
e894ae15 166 /**
167 * Add fields in the metadata to the template.
168 */
169 protected function addFieldsDefinedInSettingsMetadata() {
170 $settingMetaData = $this->getSettingsMetaData();
171 $descriptions = [];
172 foreach ($settingMetaData as $setting => $props) {
c5af8245 173 $quickFormType = $this->getQuickFormType($props);
174 if (isset($quickFormType)) {
719eda4a 175 $options = CRM_Utils_Array::value('options', $props);
4cc9fbc2 176 if ($options) {
1c8738dd 177 if ($props['html_type'] === 'Select' && isset($props['is_required']) && $props['is_required'] === FALSE && !isset($options[''])) {
178 // If the spec specifies the field is not required add a null option.
179 // Why not if empty($props['is_required']) - basically this has been added to the spec & might not be set to TRUE
180 // when it is true.
181 $options = ['' => ts('None')] + $options;
182 }
e894ae15 183 }
c89a43b3 184 if ($props['type'] === 'Boolean') {
185 $options = [$props['title'] => $props['name']];
e894ae15 186 }
c89a43b3 187
e894ae15 188 //Load input as readonly whose values are overridden in civicrm.settings.php.
189 if (Civi::settings()->getMandatory($setting)) {
190 $props['html_attributes']['readonly'] = TRUE;
191 $this->includesReadOnlyFields = TRUE;
192 }
193
c5af8245 194 $add = 'add' . $quickFormType;
e894ae15 195 if ($add == 'addElement') {
196 $this->$add(
197 $props['html_type'],
198 $setting,
6dabf459 199 $props['title'],
c89a43b3 200 ($options !== NULL) ? $options : CRM_Utils_Array::value('html_attributes', $props, []),
e894ae15 201 ($options !== NULL) ? CRM_Utils_Array::value('html_attributes', $props, []) : NULL
202 );
203 }
204 elseif ($add == 'addSelect') {
6dabf459 205 $this->addElement('select', $setting, $props['title'], $options, CRM_Utils_Array::value('html_attributes', $props));
e894ae15 206 }
207 elseif ($add == 'addCheckBox') {
969afb18 208 $this->addCheckBox($setting, '', $options, NULL, CRM_Utils_Array::value('html_attributes', $props), NULL, NULL, ['&nbsp;&nbsp;']);
e894ae15 209 }
a55c9b35 210 elseif ($add == 'addCheckBoxes') {
4e086328
CW
211 $newOptions = array_flip($options);
212 $classes = 'crm-checkbox-list';
213 if (!empty($props['sortable'])) {
214 $classes .= ' crm-sortable-list';
215 $newOptions = array_flip(self::reorderSortableOptions($setting, $options));
a55c9b35 216 }
4e086328 217 $settingMetaData[$setting]['wrapper_element'] = ['<ul class="' . $classes . '"><li>', '</li></ul>'];
a55c9b35 218 $this->addCheckBox($setting,
219 $props['title'],
220 $newOptions,
221 NULL, NULL, NULL, NULL,
bfd9c358 222 '</li><li>'
a55c9b35 223 );
224 }
e894ae15 225 elseif ($add == 'addChainSelect') {
226 $this->addChainSelect($setting, [
6dabf459 227 'label' => $props['title'],
e894ae15 228 ]);
229 }
230 elseif ($add == 'addMonthDay') {
6dabf459 231 $this->add('date', $setting, $props['title'], CRM_Core_SelectValues::date(NULL, 'M d'));
e894ae15 232 }
eba92929 233 elseif ($add === 'addEntityRef') {
6dabf459 234 $this->$add($setting, $props['title'], $props['entity_reference_options']);
eba92929 235 }
c7cd4e2c 236 elseif ($add === 'addYesNo' && ($props['type'] === 'Boolean')) {
6dabf459 237 $this->addRadio($setting, $props['title'], [1 => 'Yes', 0 => 'No'], NULL, '&nbsp;&nbsp;');
c7cd4e2c 238 }
8a52ae34 239 elseif ($add === 'add') {
6dabf459 240 $this->add($props['html_type'], $setting, $props['title'], $options);
8a52ae34 241 }
e894ae15 242 else {
6dabf459 243 $this->$add($setting, $props['title'], $options);
e894ae15 244 }
245 // Migrate to using an array as easier in smart...
f8857611 246 $description = CRM_Utils_Array::value('description', $props);
247 $descriptions[$setting] = $description;
248 $this->assign("{$setting}_description", $description);
e894ae15 249 if ($setting == 'max_attachments') {
250 //temp hack @todo fix to get from metadata
251 $this->addRule('max_attachments', ts('Value should be a positive number'), 'positiveInteger');
252 }
8913e915
D
253 if ($setting == 'max_attachments_backend') {
254 //temp hack @todo fix to get from metadata
255 $this->addRule('max_attachments_backend', ts('Value should be a positive number'), 'positiveInteger');
256 }
e894ae15 257 if ($setting == 'maxFileSize') {
258 //temp hack
259 $this->addRule('maxFileSize', ts('Value should be a positive number'), 'positiveInteger');
260 }
261
262 }
263 }
264 // setting_description should be deprecated - see Mail.tpl for metadata based tpl.
265 $this->assign('setting_descriptions', $descriptions);
266 $this->assign('settings_fields', $settingMetaData);
51f35276 267 $this->assign('fields', $this->getSettingsOrderedByWeight());
e894ae15 268 }
269
c5af8245 270 /**
271 * Get the quickform type for the given html type.
272 *
273 * @param array $spec
274 *
275 * @return string
276 */
277 protected function getQuickFormType($spec) {
0e700ee7 278 if (isset($spec['quick_form_type']) &&
279 !($spec['quick_form_type'] === 'Element' && !empty($spec['html_type']))) {
5c33bd6b 280 // This is kinda transitional
c5af8245 281 return $spec['quick_form_type'];
282 }
5c33bd6b 283
284 // The spec for settings has been updated for consistency - we provide deprecation notices for sites that have
285 // not made this change.
286 $htmlType = $spec['html_type'];
287 if ($htmlType !== strtolower($htmlType)) {
6dabf459
ML
288 // Avoiding 'ts' for obscure strings.
289 CRM_Core_Error::deprecatedFunctionWarning('Settings fields html_type should be lower case - see https://docs.civicrm.org/dev/en/latest/framework/setting/ - this needs to be fixed for ' . $spec['name']);
5c33bd6b 290 $htmlType = strtolower($spec['html_type']);
291 }
c5af8245 292 $mapping = [
293 'checkboxes' => 'CheckBoxes',
c89a43b3 294 'checkbox' => 'CheckBox',
c5af8245 295 'radio' => 'Radio',
b70c6629 296 'select' => 'Select',
7399a0a6 297 'textarea' => 'Element',
a7e15692 298 'text' => 'Element',
eba92929 299 'entity_reference' => 'EntityRef',
5c33bd6b 300 'advmultiselect' => 'Element',
c5af8245 301 ];
8a52ae34 302 $mapping += array_fill_keys(CRM_Core_Form::$html5Types, '');
5c33bd6b 303 return $mapping[$htmlType];
c5af8245 304 }
62d3ee27 305
601361a3 306 /**
307 * Get the defaults for all fields defined in the metadata.
308 *
309 * All others are pending conversion.
310 */
311 protected function setDefaultsForMetadataDefinedFields() {
312 CRM_Core_BAO_ConfigSetting::retrieve($this->_defaults);
6821aa1d 313 foreach (array_keys($this->_settings) as $setting) {
601361a3 314 $this->_defaults[$setting] = civicrm_api3('setting', 'getvalue', ['name' => $setting]);
6821aa1d 315 $spec = $this->getSettingsMetadata()[$setting];
316 if (!empty($spec['serialize'])) {
317 $this->_defaults[$setting] = CRM_Core_DAO::unSerializeField($this->_defaults[$setting], $spec['serialize']);
318 }
c5af8245 319 if ($this->getQuickFormType($spec) === 'CheckBoxes') {
6821aa1d 320 $this->_defaults[$setting] = array_fill_keys($this->_defaults[$setting], 1);
321 }
74f89a9f 322 if ($this->getQuickFormType($spec) === 'CheckBox') {
323 $this->_defaults[$setting] = [$setting => $this->_defaults[$setting]];
324 }
6821aa1d 325 }
326 }
327
328 /**
281db812 329 * Save any fields which have been defined via metadata.
330 *
331 * (Other fields are hack-handled... sadly.
332 *
333 * @param array $params
334 * Form input.
6821aa1d 335 *
281db812 336 * @throws \CiviCRM_API3_Exception
6821aa1d 337 */
338 protected function saveMetadataDefinedSettings($params) {
339 $settings = $this->getSettingsToSetByMetadata($params);
340 foreach ($settings as $setting => $settingValue) {
4e086328
CW
341 $settingMetaData = $this->getSettingMetadata($setting);
342 if (!empty($settingMetaData['sortable'])) {
343 $settings[$setting] = $this->getReorderedSettingData($setting, $settingValue);
344 }
345 elseif ($this->getQuickFormType($settingMetaData) === 'CheckBoxes') {
6821aa1d 346 $settings[$setting] = array_keys($settingValue);
347 }
4e086328 348 elseif ($this->getQuickFormType($settingMetaData) === 'CheckBox') {
74f89a9f 349 // This will be an array with one value.
350 $settings[$setting] = (int) reset($settings[$setting]);
351 }
601361a3 352 }
6821aa1d 353 civicrm_api3('setting', 'create', $settings);
601361a3 354 }
355
4e086328
CW
356 /**
357 * Display options in correct order on the form
358 *
359 * @param $setting
360 * @param $options
361 * @return array
362 */
363 public static function reorderSortableOptions($setting, $options) {
364 return array_merge(array_flip(Civi::settings()->get($setting)), $options);
365 }
366
367 /**
368 * @param string $setting
369 * @param array $settingValue
370 *
371 * @return array
372 */
373 private function getReorderedSettingData($setting, $settingValue) {
374 // Get order from $_POST as $_POST maintains the order the sorted setting
375 // options were sent. You can simply assign data from $_POST directly to
376 // $settings[] but preference has to be given to data from Quickform.
377 $order = array_keys(\CRM_Utils_Request::retrieve($setting, 'String'));
378 $settingValueKeys = array_keys($settingValue);
379 return array_intersect($order, $settingValueKeys);
380 }
381
946389fb 382}