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