3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This trait allows us to consolidate Preferences & Settings forms.
21 * It is intended mostly as part of a refactoring process to get rid of having 2.
23 trait CRM_Admin_Form_SettingTrait
{
26 * The setting page filter.
35 protected $settingsMetadata;
42 public function getDefaultEntity() {
47 * Fields defined as read only.
51 protected $readOnlyFields = [];
54 * Have read only fields been defined on the form.
58 protected function hasReadOnlyFields(): bool {
59 return !empty($this->readOnlyFields
);
63 * Get the metadata relating to the settings on the form, ordered by the keys in $this->_settings.
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
);
73 return $this->settingsMetadata
;
77 * Get the settings which can be stored based on metadata.
79 * @param array $params
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];
92 elseif ($quickFormType === 'CheckBoxes') {
93 $setValues[$key] = [];
102 protected function filterParamsSetByMetadata(&$params) {
103 foreach ($this->getSettingsToSetByMetadata($params) as $setting => $settingGroup) {
104 //@todo array_diff this
105 unset($params[$setting]);
110 * Get the metadata for a particular field.
115 protected function getSettingMetadata($setting) {
116 return $this->getSettingsMetaData()[$setting];
120 * Get the metadata for a particular field for a particular item.
122 * e.g get 'serialize' key, if exists, for a field.
128 protected function getSettingMetadataItem($setting, $item) {
129 return CRM_Utils_Array
::value($item, $this->getSettingsMetaData()[$setting]);
133 * This is public so we can retrieve the filter name via hooks etc. and apply conditional logic (eg. loading javascript conditionals).
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);
143 return $this->_filter
;
147 * Returns a re-keyed copy of the settings, ordered by weight.
151 protected function getSettingsOrderedByWeight() {
152 $settingMetaData = $this->getSettingsMetaData();
153 $filter = $this->getSettingPageFilter();
155 usort($settingMetaData, function ($a, $b) use ($filter) {
156 // Handle cases in which a comparison is impossible. Such will be considered ties.
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']
166 return $a['settings_pages'][$filter]['weight'] > $b['settings_pages'][$filter]['weight'] ?
1 : -1;
169 return $settingMetaData;
173 * Add fields in the metadata to the template.
175 * @throws \CRM_Core_Exception
176 * @throws \CiviCRM_API3_Exception
178 protected function addFieldsDefinedInSettingsMetadata() {
179 $this->addSettingsToFormFromMetadata();
180 $settingMetaData = $this->getSettingsMetaData();
182 foreach ($settingMetaData as $setting => $props) {
183 $quickFormType = $this->getQuickFormType($props);
184 if (isset($quickFormType)) {
185 $options = $props['options'] ??
NULL;
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
191 $options = ['' => ts('None')] +
$options;
194 if ($props['type'] === 'Boolean') {
195 $options = [$props['title'] => $props['name']];
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;
204 $add = 'add' . $quickFormType;
205 if ($add === 'addElement') {
210 ($options !== NULL) ?
$options : CRM_Utils_Array
::value('html_attributes', $props, []),
211 ($options !== NULL) ? CRM_Utils_Array
::value('html_attributes', $props, []) : NULL
214 elseif ($add === 'addSelect') {
215 $this->addElement('select', $setting, $props['title'], $options, CRM_Utils_Array
::value('html_attributes', $props));
217 elseif ($add === 'addCheckBox') {
218 $this->addCheckBox($setting, '', $options, NULL, CRM_Utils_Array
::value('html_attributes', $props), NULL, NULL, [' ']);
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));
227 $settingMetaData[$setting]['wrapper_element'] = ['<ul class="' . $classes . '"><li>', '</li></ul>'];
228 $this->addCheckBox($setting,
231 NULL, NULL, NULL, NULL,
235 elseif ($add === 'addChainSelect') {
236 $this->addChainSelect($setting, ['label' => $props['title']] +
$props['chain_select_settings']);
238 elseif ($add === 'addMonthDay') {
239 $this->add('date', $setting, $props['title'], CRM_Core_SelectValues
::date(NULL, 'M d'));
241 elseif ($add === 'addEntityRef') {
242 $this->$add($setting, $props['title'], $props['entity_reference_options']);
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), ' ');
247 elseif ($add === 'add') {
248 $this->add($props['html_type'], $setting, $props['title'], $options, FALSE, $props['html_extra'] ??
NULL);
251 $this->$add($setting, $props['title'], $options);
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');
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');
265 if ($setting === 'maxFileSize') {
267 $this->addRule('maxFileSize', ts('Value should be a positive number'), 'positiveInteger');
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]);
284 * Get the quickform type for the given html type.
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'];
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']);
306 'checkboxes' => 'CheckBoxes',
307 'checkbox' => 'CheckBox',
309 'select' => 'Select',
310 'textarea' => 'Element',
312 'entity_reference' => 'EntityRef',
313 'advmultiselect' => 'Element',
314 'chainselect' => 'ChainSelect',
316 $mapping +
= array_fill_keys(CRM_Core_Form
::$html5Types, '');
317 return $mapping[$htmlType] ??
'';
321 * Get the defaults for all fields defined in the metadata.
323 * All others are pending conversion.
325 * @throws \CiviCRM_API3_Exception
326 * @throws \CRM_Core_Exception
328 protected function setDefaultsForMetadataDefinedFields() {
329 CRM_Core_BAO_ConfigSetting
::retrieve($this->_defaults
);
330 foreach (array_keys($this->_settings
) as $setting) {
331 $this->_defaults
[$setting] = civicrm_api3('setting', 'getvalue', ['name' => $setting]);
332 $spec = $this->getSettingsMetaData()[$setting];
333 if (!empty($spec['serialize']) && !is_array($this->_defaults
[$setting])) {
334 $this->_defaults
[$setting] = CRM_Core_DAO
::unSerializeField((string) $this->_defaults
[$setting], $spec['serialize']);
336 if ($this->getQuickFormType($spec) === 'CheckBoxes') {
337 $this->_defaults
[$setting] = array_fill_keys($this->_defaults
[$setting], 1);
339 if ($this->getQuickFormType($spec) === 'CheckBox') {
340 $this->_defaults
[$setting] = [$setting => $this->_defaults
[$setting]];
346 * Save any fields which have been defined via metadata.
348 * (Other fields are hack-handled... sadly.
350 * @param array $params
353 * @throws \CiviCRM_API3_Exception
355 protected function saveMetadataDefinedSettings($params) {
356 $settings = $this->getSettingsToSetByMetadata($params);
357 foreach ($settings as $setting => $settingValue) {
358 $settingMetaData = $this->getSettingMetadata($setting);
359 if (!empty($settingMetaData['sortable'])) {
360 $settings[$setting] = $this->getReorderedSettingData($setting, $settingValue);
362 elseif ($this->getQuickFormType($settingMetaData) === 'CheckBoxes') {
363 $settings[$setting] = array_keys($settingValue);
365 elseif ($this->getQuickFormType($settingMetaData) === 'CheckBox') {
366 // This will be an array with one value.
367 $settings[$setting] = (bool) reset($settings[$setting]);
370 civicrm_api3('setting', 'create', $settings);
374 * Display options in correct order on the form
380 public static function reorderSortableOptions($setting, $options) {
381 return array_merge(array_flip(Civi
::settings()->get($setting)), $options);
385 * @param string $setting
386 * @param array $settingValue
390 * @throws \CRM_Core_Exception
392 private function getReorderedSettingData($setting, $settingValue) {
393 // Get order from $_POST as $_POST maintains the order the sorted setting
394 // options were sent. You can simply assign data from $_POST directly to
395 // $settings[] but preference has to be given to data from Quickform.
396 $order = array_keys(\CRM_Utils_Request
::retrieve($setting, 'String'));
397 $settingValueKeys = array_keys($settingValue);
398 return array_intersect($order, $settingValueKeys);
402 * Add settings to form if the metadata designates they should be on the page.
404 * @throws \CiviCRM_API3_Exception
406 protected function addSettingsToFormFromMetadata() {
407 $filter = $this->getSettingPageFilter();
408 $settings = civicrm_api3('Setting', 'getfields', [])['values'];
409 foreach ($settings as $key => $setting) {
410 if (isset($setting['settings_pages'][$filter])) {
411 $this->_settings
[$key] = $setting;