Merge pull request #23751 from eileenmcnaughton/test_member
[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 * Fields defined as read only.
48 *
49 * @var array
50 */
51 protected $readOnlyFields = [];
52
53 /**
54 * Have read only fields been defined on the form.
55 *
56 * @return bool
57 */
58 protected function hasReadOnlyFields(): bool {
59 return !empty($this->readOnlyFields);
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(): array {
68 if (empty($this->settingsMetadata)) {
69 $this->settingsMetadata = \Civi\Core\SettingsMetadata::getMetadata(['name' => array_keys($this->_settings)], NULL, TRUE);
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) {
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 $quickFormType = $this->getQuickFormType($this->getSettingMetadata($key));
89 if ($quickFormType === 'CheckBox') {
90 $setValues[$key] = [$key => 0];
91 }
92 elseif ($quickFormType === 'CheckBoxes') {
93 $setValues[$key] = [];
94 }
95 }
96 return $setValues;
97 }
98
99 /**
100 * @param $params
101 */
102 protected function filterParamsSetByMetadata(&$params) {
103 foreach ($this->getSettingsToSetByMetadata($params) as $setting => $settingGroup) {
104 //@todo array_diff this
105 unset($params[$setting]);
106 }
107 }
108
109 /**
110 * Get the metadata for a particular field.
111 *
112 * @param $setting
113 * @return mixed
114 */
115 protected function getSettingMetadata($setting) {
116 return $this->getSettingsMetaData()[$setting];
117 }
118
119 /**
120 * Get the metadata for a particular field for a particular item.
121 *
122 * e.g get 'serialize' key, if exists, for a field.
123 *
124 * @param $setting
125 * @param $item
126 * @return mixed
127 */
128 protected function getSettingMetadataItem($setting, $item) {
129 return CRM_Utils_Array::value($item, $this->getSettingsMetaData()[$setting]);
130 }
131
132 /**
133 * This is public so we can retrieve the filter name via hooks etc. and apply conditional logic (eg. loading javascript conditionals).
134 *
135 * @return string
136 */
137 public function getSettingPageFilter() {
138 if (!isset($this->_filter)) {
139 // Get the last URL component without modifying the urlPath property.
140 $urlPath = array_values($this->urlPath);
141 $this->_filter = end($urlPath);
142 }
143 return $this->_filter;
144 }
145
146 /**
147 * Returns a re-keyed copy of the settings, ordered by weight.
148 *
149 * @return array
150 */
151 protected function getSettingsOrderedByWeight() {
152 $settingMetaData = $this->getSettingsMetaData();
153 $filter = $this->getSettingPageFilter();
154
155 usort($settingMetaData, function ($a, $b) use ($filter) {
156 // Handle cases in which a comparison is impossible. Such will be considered ties.
157 if (
158 // A comparison can't be made unless both setting weights are declared.
159 !isset($a['settings_pages'][$filter]['weight'], $b['settings_pages'][$filter]['weight'])
160 // A pair of settings might actually have the same weight.
161 || $a['settings_pages'][$filter]['weight'] === $b['settings_pages'][$filter]['weight']
162 ) {
163 return 0;
164 }
165
166 return $a['settings_pages'][$filter]['weight'] > $b['settings_pages'][$filter]['weight'] ? 1 : -1;
167 });
168
169 return $settingMetaData;
170 }
171
172 /**
173 * Add fields in the metadata to the template.
174 *
175 * @throws \CRM_Core_Exception
176 * @throws \CiviCRM_API3_Exception
177 */
178 protected function addFieldsDefinedInSettingsMetadata() {
179 $this->addSettingsToFormFromMetadata();
180 $settingMetaData = $this->getSettingsMetaData();
181 $descriptions = [];
182 foreach ($settingMetaData as $setting => $props) {
183 $quickFormType = $this->getQuickFormType($props);
184 if (isset($quickFormType)) {
185 $options = $props['options'] ?? NULL;
186 if ($options) {
187 if ($quickFormType === 'Select' && isset($props['is_required']) && $props['is_required'] === FALSE && !isset($options[''])) {
188 // If the spec specifies the field is not required add a null option.
189 // Why not if empty($props['is_required']) - basically this has been added to the spec & might not be set to TRUE
190 // when it is true.
191 $options = ['' => ts('None')] + $options;
192 }
193 }
194 if ($props['type'] === 'Boolean') {
195 $options = [$props['title'] => $props['name']];
196 }
197
198 //Load input as readonly whose values are overridden in civicrm.settings.php.
199 if (Civi::settings()->getMandatory($setting) !== NULL) {
200 $props['html_attributes']['readonly'] = TRUE;
201 $this->readOnlyFields[] = $setting;
202 }
203
204 $add = 'add' . $quickFormType;
205 if ($add === 'addElement') {
206 $this->$add(
207 $props['html_type'],
208 $setting,
209 $props['title'],
210 ($options !== NULL) ? $options : CRM_Utils_Array::value('html_attributes', $props, []),
211 ($options !== NULL) ? CRM_Utils_Array::value('html_attributes', $props, []) : NULL
212 );
213 }
214 elseif ($add === 'addSelect') {
215 $this->addElement('select', $setting, $props['title'], $options, CRM_Utils_Array::value('html_attributes', $props));
216 }
217 elseif ($add === 'addCheckBox') {
218 $this->addCheckBox($setting, '', $options, NULL, CRM_Utils_Array::value('html_attributes', $props), NULL, NULL, ['&nbsp;&nbsp;']);
219 }
220 elseif ($add === 'addCheckBoxes') {
221 $newOptions = array_flip($options);
222 $classes = 'crm-checkbox-list';
223 if (!empty($props['sortable'])) {
224 $classes .= ' crm-sortable-list';
225 $newOptions = array_flip(self::reorderSortableOptions($setting, $options));
226 }
227 $settingMetaData[$setting]['wrapper_element'] = ['<ul class="' . $classes . '"><li>', '</li></ul>'];
228 $this->addCheckBox($setting,
229 $props['title'],
230 $newOptions,
231 NULL, NULL, NULL, NULL,
232 '</li><li>'
233 );
234 }
235 elseif ($add === 'addChainSelect') {
236 $this->addChainSelect($setting, ['label' => $props['title']] + $props['chain_select_settings']);
237 }
238 elseif ($add === 'addMonthDay') {
239 $this->add('date', $setting, $props['title'], CRM_Core_SelectValues::date(NULL, 'M d'));
240 }
241 elseif ($add === 'addEntityRef') {
242 $this->$add($setting, $props['title'], $props['entity_reference_options']);
243 }
244 elseif ($add === 'addYesNo' && ($props['type'] === 'Boolean')) {
245 $this->addRadio($setting, $props['title'], [1 => ts('Yes'), 0 => ts('No')], CRM_Utils_Array::value('html_attributes', $props), '&nbsp;&nbsp;');
246 }
247 elseif ($add === 'add') {
248 $this->add($props['html_type'], $setting, $props['title'], $options, FALSE, $props['html_extra'] ?? NULL);
249 }
250 else {
251 $this->$add($setting, $props['title'], $options);
252 }
253 // Migrate to using an array as easier in smart...
254 $description = $props['description'] ?? NULL;
255 $descriptions[$setting] = $description;
256 $this->assign("{$setting}_description", $description);
257 if ($setting === 'max_attachments') {
258 //temp hack @todo fix to get from metadata
259 $this->addRule('max_attachments', ts('Value should be a positive number'), 'positiveInteger');
260 }
261 if ($setting === 'max_attachments_backend') {
262 //temp hack @todo fix to get from metadata
263 $this->addRule('max_attachments_backend', ts('Value should be a positive number'), 'positiveInteger');
264 }
265 if ($setting === 'maxFileSize') {
266 //temp hack
267 $this->addRule('maxFileSize', ts('Value should be a positive number'), 'positiveInteger');
268 }
269
270 }
271 }
272 // setting_description should be deprecated - see Mail.tpl for metadata based tpl.
273 $this->assign('setting_descriptions', $descriptions);
274 $this->assign('settings_fields', $settingMetaData);
275 $this->assign('fields', $this->getSettingsOrderedByWeight());
276 // @todo look at sharing the code below in the settings trait.
277 if ($this->hasReadOnlyFields()) {
278 $this->freeze($this->readOnlyFields);
279 CRM_Core_Session::setStatus(ts("Some fields are loaded as 'readonly' as they have been set (overridden) in civicrm.settings.php."), '', 'info', ['expires' => 0]);
280 }
281 }
282
283 /**
284 * Get the quickform type for the given html type.
285 *
286 * @param array $spec
287 *
288 * @return string
289 */
290 protected function getQuickFormType($spec) {
291 if (isset($spec['quick_form_type']) &&
292 !($spec['quick_form_type'] === 'Element' && !empty($spec['html_type']))) {
293 // This is kinda transitional
294 return $spec['quick_form_type'];
295 }
296
297 // The spec for settings has been updated for consistency - we provide deprecation notices for sites that have
298 // not made this change.
299 $htmlType = $spec['html_type'];
300 if ($htmlType !== strtolower($htmlType)) {
301 // Avoiding 'ts' for obscure strings.
302 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']);
303 $htmlType = strtolower($spec['html_type']);
304 }
305 $mapping = [
306 'checkboxes' => 'CheckBoxes',
307 'checkbox' => 'CheckBox',
308 'radio' => 'Radio',
309 'select' => 'Select',
310 'textarea' => 'Element',
311 'text' => 'Element',
312 'entity_reference' => 'EntityRef',
313 'advmultiselect' => 'Element',
314 'chainselect' => 'ChainSelect',
315 'yesno' => 'YesNo',
316 ];
317 $mapping += array_fill_keys(CRM_Core_Form::$html5Types, '');
318 return $mapping[$htmlType] ?? '';
319 }
320
321 /**
322 * Get the defaults for all fields defined in the metadata.
323 *
324 * All others are pending conversion.
325 *
326 * @throws \CiviCRM_API3_Exception
327 * @throws \CRM_Core_Exception
328 */
329 protected function setDefaultsForMetadataDefinedFields() {
330 CRM_Core_BAO_ConfigSetting::retrieve($this->_defaults);
331 foreach (array_keys($this->_settings) as $setting) {
332 $this->_defaults[$setting] = civicrm_api3('setting', 'getvalue', ['name' => $setting]);
333 $spec = $this->getSettingsMetaData()[$setting];
334 if (!empty($spec['serialize']) && !is_array($this->_defaults[$setting])) {
335 $this->_defaults[$setting] = CRM_Core_DAO::unSerializeField((string) $this->_defaults[$setting], $spec['serialize']);
336 }
337 if ($this->getQuickFormType($spec) === 'CheckBoxes') {
338 $this->_defaults[$setting] = array_fill_keys($this->_defaults[$setting], 1);
339 }
340 if ($this->getQuickFormType($spec) === 'CheckBox') {
341 $this->_defaults[$setting] = [$setting => $this->_defaults[$setting]];
342 }
343 }
344 }
345
346 /**
347 * Save any fields which have been defined via metadata.
348 *
349 * (Other fields are hack-handled... sadly.
350 *
351 * @param array $params
352 * Form input.
353 *
354 * @throws \CiviCRM_API3_Exception
355 */
356 protected function saveMetadataDefinedSettings($params) {
357 $settings = $this->getSettingsToSetByMetadata($params);
358 foreach ($settings as $setting => $settingValue) {
359 $settingMetaData = $this->getSettingMetadata($setting);
360 if (!empty($settingMetaData['sortable'])) {
361 $settings[$setting] = $this->getReorderedSettingData($setting, $settingValue);
362 }
363 elseif ($this->getQuickFormType($settingMetaData) === 'CheckBoxes') {
364 $settings[$setting] = array_keys($settingValue);
365 }
366 elseif ($this->getQuickFormType($settingMetaData) === 'CheckBox') {
367 // This will be an array with one value.
368 $settings[$setting] = (bool) reset($settings[$setting]);
369 }
370 }
371 civicrm_api3('setting', 'create', $settings);
372 }
373
374 /**
375 * Display options in correct order on the form
376 *
377 * @param $setting
378 * @param $options
379 * @return array
380 */
381 public static function reorderSortableOptions($setting, $options) {
382 return array_merge(array_flip(Civi::settings()->get($setting)), $options);
383 }
384
385 /**
386 * @param string $setting
387 * @param array $settingValue
388 *
389 * @return array
390 *
391 * @throws \CRM_Core_Exception
392 */
393 private function getReorderedSettingData($setting, $settingValue) {
394 // Get order from $_POST as $_POST maintains the order the sorted setting
395 // options were sent. You can simply assign data from $_POST directly to
396 // $settings[] but preference has to be given to data from Quickform.
397 $order = array_keys(\CRM_Utils_Request::retrieve($setting, 'String'));
398 $settingValueKeys = array_keys($settingValue);
399 return array_intersect($order, $settingValueKeys);
400 }
401
402 /**
403 * Add settings to form if the metadata designates they should be on the page.
404 *
405 * @throws \CiviCRM_API3_Exception
406 */
407 protected function addSettingsToFormFromMetadata() {
408 $filter = $this->getSettingPageFilter();
409 $settings = civicrm_api3('Setting', 'getfields', [])['values'];
410 foreach ($settings as $key => $setting) {
411 if (isset($setting['settings_pages'][$filter])) {
412 $this->_settings[$key] = $setting;
413 }
414 }
415 }
416
417 }