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 * BAO object for civicrm_setting table. This table is used to store civicrm settings that are not used
20 * very frequently (i.e. not on every page load)
22 * The group column is used for grouping together all settings that logically belong to the same set.
23 * Thus all settings in the same group are retrieved with one DB call and then cached for future needs.
25 class CRM_Core_BAO_Setting
extends CRM_Core_DAO_Setting
{
28 * Various predefined settings that have been migrated to the setting table.
31 ADDRESS_STANDARDIZATION_PREFERENCES_NAME
= 'Address Standardization Preferences',
32 CAMPAIGN_PREFERENCES_NAME
= 'Campaign Preferences',
33 DEVELOPER_PREFERENCES_NAME
= 'Developer Preferences',
34 DIRECTORY_PREFERENCES_NAME
= 'Directory Preferences',
35 EVENT_PREFERENCES_NAME
= 'Event Preferences',
36 MAILING_PREFERENCES_NAME
= 'Mailing Preferences',
37 MAP_PREFERENCES_NAME
= 'Map Preferences',
38 CONTRIBUTE_PREFERENCES_NAME
= 'Contribute Preferences',
39 MEMBER_PREFERENCES_NAME
= 'Member Preferences',
40 MULTISITE_PREFERENCES_NAME
= 'Multi Site Preferences',
41 PERSONAL_PREFERENCES_NAME
= 'Personal Preferences',
42 SYSTEM_PREFERENCES_NAME
= 'CiviCRM Preferences',
43 URL_PREFERENCES_NAME
= 'URL Preferences',
44 LOCALIZATION_PREFERENCES_NAME
= 'Localization Preferences',
45 SEARCH_PREFERENCES_NAME
= 'Search Preferences';
48 * Retrieve the value of a setting from the DB table.
50 * @param string $group
51 * The group name of the item (deprecated).
53 * (required) The name under which this item is stored.
54 * @param int $componentID
55 * The optional component ID (so componenets can share the same name space).
56 * @param string $defaultValue
57 * The default value to return for this setting if not present in DB.
58 * @param int $contactID
59 * If set, this is a contactID specific setting, else its a global setting.
61 * @param int $domainID
64 * The data if present in the setting table, else null
66 public static function getItem(
74 /** @var \Civi\Core\SettingsManager $manager */
75 $manager = \Civi
::service('settings_manager');
76 $settings = ($contactID === NULL) ?
$manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
78 CRM_Core_Error
::debug_log_message("Deprecated: Group='$group'. Name should be provided.\n");
80 if ($componentID !== NULL) {
81 CRM_Core_Error
::debug_log_message("Deprecated: Group='$group'. Name='$name'. Component should be omitted\n");
83 if ($defaultValue !== NULL) {
84 CRM_Core_Error
::debug_log_message("Deprecated: Group='$group'. Name='$name'. Defaults should come from metadata\n");
86 return $name ?
$settings->get($name) : $settings->all();
90 * Get multiple items from the setting table.
92 * @param array $params
93 * (required) An api formatted array of keys and values.
94 * @param array $domains Array of domains to get settings for. Default is the current domain
95 * @param $settingsToReturn
99 public static function getItems(&$params, $domains = NULL, $settingsToReturn) {
100 $originalDomain = CRM_Core_Config
::domainID();
101 if (empty($domains)) {
102 $domains[] = $originalDomain;
104 if (!empty($settingsToReturn) && !is_array($settingsToReturn)) {
105 $settingsToReturn = [$settingsToReturn];
108 $fields = $result = [];
109 $fieldsToGet = self
::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
110 foreach ($domains as $domainID) {
111 $result[$domainID] = [];
112 foreach ($fieldsToGet as $name => $value) {
113 $contactID = $params['contact_id'] ??
NULL;
114 $setting = CRM_Core_BAO_Setting
::getItem(NULL, $name, NULL, NULL, $contactID, $domainID);
115 if (!is_null($setting)) {
116 // we won't return if not set - helps in return all scenario - otherwise we can't indentify the missing ones
117 // e.g for revert of fill actions
118 $result[$domainID][$name] = $setting;
126 * Store an item in the setting table.
129 * (required) The value that will be serialized and stored.
130 * @param string $group
131 * The group name of the item (deprecated).
132 * @param string $name
133 * (required) The name of the setting.
134 * @param int $componentID
135 * The optional component ID (so componenets can share the same name space).
136 * @param int $contactID
137 * @param int $createdID
138 * An optional ID to assign the creator to. If not set, retrieved from session.
140 * @param int $domainID
142 * @throws \CRM_Core_Exception
144 * @deprecated - refer docs https://docs.civicrm.org/dev/en/latest/framework/setting/
146 public static function setItem(
155 CRM_Core_Error
::deprecatedFunctionWarning('refer docs for correct methods https://docs.civicrm.org/dev/en/latest/framework/setting/');
157 /** @var \Civi\Core\SettingsManager $manager */
158 $manager = \Civi
::service('settings_manager');
159 $settings = ($contactID === NULL) ?
$manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
160 $settings->set($name, $value);
164 * Store multiple items in the setting table. Note that this will also store config keys
165 * the storage is determined by the metdata and is affected by
166 * 'name' setting's name
167 * 'config_key' = the config key is different to the settings key - e.g. debug where there was a conflict
168 * 'legacy_key' = rename from config or setting with this name
170 * @param array $params
171 * (required) An api formatted array of keys and values.
172 * @param null $domains
174 * @throws API_Exception
175 * @domains array an array of domains to get settings for. Default is the current domain
178 public static function setItems(&$params, $domains = NULL) {
179 $domains = empty($domains) ?
[CRM_Core_Config
::domainID()] : $domains;
181 // FIXME: redundant validation
182 // FIXME: this whole thing should just be a loop to call $settings->add() on each domain.
185 $fieldsToSet = self
::validateSettingsInput($params, $fields);
187 foreach ($fieldsToSet as $settingField => &$settingValue) {
188 if (empty($fields['values'][$settingField])) {
189 Civi
::log()->warning('Deprecated Path: There is a setting (' . $settingField . ') not correctly defined. You may see unpredictability due to this. CRM_Core_Setting::setItems', ['civi.tag' => 'deprecated']);
190 $fields['values'][$settingField] = [];
192 self
::validateSetting($settingValue, $fields['values'][$settingField]);
195 foreach ($domains as $domainID) {
196 Civi
::settings($domainID)->add($fieldsToSet);
197 $result[$domainID] = $fieldsToSet;
204 * Gets metadata about the settings fields (from getfields) based on the fields being passed in
206 * This function filters on the fields like 'version' & 'debug' that are not settings
208 * @param array $params
209 * Parameters as passed into API.
210 * @param array $fields
211 * Empty array to be populated with fields metadata.
212 * @param bool $createMode
214 * @throws API_Exception
216 * name => value array of the fields to be set (with extraneous removed)
218 public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
237 // CRM-18347: ignore params unintentionally passed by API explorer on WP
240 // CRM-18347: ignore params unintentionally passed by wp CLI tool
242 // CRM-19877: ignore params extraneously passed by Joomla
246 $settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
247 $getFieldsParams = ['version' => 3];
248 if (count($settingParams) == 1) {
249 // ie we are only setting one field - we'll pass it into getfields for efficiency
250 list($name) = array_keys($settingParams);
251 $getFieldsParams['name'] = $name;
253 $fields = civicrm_api3('setting', 'getfields', $getFieldsParams);
254 $invalidParams = (array_diff_key($settingParams, $fields['values']));
255 if (!empty($invalidParams)) {
256 throw new API_Exception(implode(',', array_keys($invalidParams)) . " not valid settings");
258 if (!empty($settingParams)) {
259 $filteredFields = array_intersect_key($settingParams, $fields['values']);
262 // no filters so we are interested in all for get mode. In create mode this means nothing to set
263 $filteredFields = $createMode ?
[] : $fields['values'];
265 return $filteredFields;
269 * Validate & convert settings input.
271 * @param mixed $value
272 * value of the setting to be set
273 * @param array $fieldSpec
274 * Metadata for given field (drawn from the xml)
277 * @throws \API_Exception
279 public static function validateSetting(&$value, array $fieldSpec) {
280 // Deprecated guesswork - should use $fieldSpec['serialize']
281 if ($fieldSpec['type'] == 'String' && is_array($value)) {
282 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
284 if (empty($fieldSpec['validate_callback'])) {
288 $cb = Civi\Core\Resolver
::singleton()->get($fieldSpec['validate_callback']);
289 if (!call_user_func_array($cb, array(&$value, $fieldSpec))) {
290 throw new API_Exception("validation failed for {$fieldSpec['name']} = $value based on callback {$fieldSpec['validate_callback']}");
296 * Validate & convert settings input - translate True False to 0 or 1.
298 * @param mixed $value value of the setting to be set
299 * @param array $fieldSpec Metadata for given field (drawn from the xml)
302 * @throws \API_Exception
304 public static function validateBoolSetting(&$value, $fieldSpec) {
305 if (!CRM_Utils_Rule
::boolean($value)) {
306 throw new API_Exception("Boolean value required for {$fieldSpec['name']}");
318 * This provides information about the setting - similar to the fields concept for DAO information.
319 * As the setting is serialized code creating validation setting input needs to know the data type
320 * This also helps move information out of the form layer into the data layer where people can interact with
321 * it via the API or other mechanisms. In order to keep this consistent it is important the form layer
324 * Note that this function should never be called when using the runtime getvalue function. Caching works
325 * around the expectation it will be called during setting administration
327 * Function is intended for configuration rather than runtime access to settings
329 * The following params will filter the result. If none are passed all settings will be returns
331 * @param int $componentID
332 * Id of relevant component.
333 * @param array $filters
334 * @param int $domainID
335 * @param null $profile
338 * the following information as appropriate for each setting
342 * - add (CiviCRM version added)
348 public static function getSettingSpecification(
354 return \Civi\Core\SettingsMetadata
::getMetadata($filters, $domainID);
359 * @param string $name
360 * @param bool $system
362 * @param bool $localize
363 * @param string $returnField
364 * @param bool $returnNameANDLabels
365 * @param null $condition
369 public static function valueOptions(
375 $returnField = 'name',
376 $returnNameANDLabels = FALSE,
379 $optionValue = self
::getItem($group, $name);
381 $groupValues = CRM_Core_OptionGroup
::values($name, FALSE, FALSE, $localize, $condition, $returnField);
383 //enabled name => label require for new contact edit form, CRM-4605
384 if ($returnNameANDLabels) {
385 $names = $labels = $nameAndLabels = [];
386 if ($returnField == 'name') {
387 $names = $groupValues;
388 $labels = CRM_Core_OptionGroup
::values($name, FALSE, FALSE, $localize, $condition, 'label');
391 $labels = $groupValues;
392 $names = CRM_Core_OptionGroup
::values($name, FALSE, FALSE, $localize, $condition, 'name');
397 foreach ($groupValues as $gn => $gv) {
398 $returnValues[$gv] = 0;
401 if ($optionValue && !empty($groupValues)) {
402 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
403 substr($optionValue, 1, -1)
406 if (!empty($dbValues)) {
407 foreach ($groupValues as $key => $val) {
408 if (in_array($key, $dbValues)) {
409 $returnValues[$val] = 1;
410 if ($returnNameANDLabels) {
411 $nameAndLabels[$names[$key]] = $labels[$key];
417 return ($returnNameANDLabels) ?
$nameAndLabels : $returnValues;
421 * @param $group (deprecated)
422 * @param string $name
424 * @param bool $system
426 * @param string $keyField
428 * @throws \CRM_Core_Exception
432 public static function setValueOption(
440 CRM_Core_Error
::deprecatedFunctionWarning('refer docs for correct methods https://docs.civicrm.org/dev/en/latest/framework/setting/');
444 elseif (is_array($value)) {
445 $groupValues = CRM_Core_OptionGroup
::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
448 foreach ($groupValues as $key => $val) {
449 if (!empty($value[$val])) {
454 if (!empty($cbValues)) {
455 $optionValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
456 array_keys($cbValues)
457 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
464 $optionValue = $value;
467 self
::setItem($optionValue, $group, $name);
471 * Check if environment is explicitly set.
475 public static function isEnvironmentSet($setting, $value = NULL) {
476 $environment = CRM_Core_Config
::environment();
477 if ($setting == 'environment' && $environment) {
484 * Check if job is able to be executed by API.
486 * @throws API_Exception
488 public static function isAPIJobAllowedToRun($params) {
489 $environment = CRM_Core_Config
::environment(NULL, TRUE);
490 if ($environment != 'Production') {
491 if (!empty($params['runInNonProductionEnvironment'])) {
492 $mailing = Civi
::settings()->get('mailing_backend_store');
494 Civi
::settings()->set('mailing_backend', $mailing);
498 throw new Exception(ts("Job has not been executed as it is a %1 (non-production) environment.", [1 => $environment]));
504 * Setting Callback - On Change.
506 * Respond to changes in the "environment" setting.
508 * @param array $oldValue
509 * Value of old environment mode.
510 * @param array $newValue
511 * Value of new environment mode.
512 * @param array $metadata
513 * Specification of the setting (per *.settings.php).
515 public static function onChangeEnvironmentSetting($oldValue, $newValue, $metadata) {
516 if ($newValue != 'Production') {
517 $mailing = Civi
::settings()->get('mailing_backend');
518 if ($mailing['outBound_option'] != CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
) {
519 Civi
::settings()->set('mailing_backend_store', $mailing);
521 Civi
::settings()->set('mailing_backend', ['outBound_option' => CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
]);
522 CRM_Core_Session
::setStatus(ts('Outbound emails have been disabled. Scheduled jobs will not run unless runInNonProductionEnvironment=TRUE is added as a parameter for a specific job'), ts("Non-production environment set"), "success");
525 $mailing = Civi
::settings()->get('mailing_backend_store');
527 Civi
::settings()->set('mailing_backend', $mailing);