3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2020
35 * BAO object for civicrm_setting table. This table is used to store civicrm settings that are not used
36 * very frequently (i.e. not on every page load)
38 * The group column is used for grouping together all settings that logically belong to the same set.
39 * Thus all settings in the same group are retrieved with one DB call and then cached for future needs.
41 class CRM_Core_BAO_Setting
extends CRM_Core_DAO_Setting
{
44 * Various predefined settings that have been migrated to the setting table.
47 ADDRESS_STANDARDIZATION_PREFERENCES_NAME
= 'Address Standardization Preferences',
48 CAMPAIGN_PREFERENCES_NAME
= 'Campaign Preferences',
49 DEVELOPER_PREFERENCES_NAME
= 'Developer Preferences',
50 DIRECTORY_PREFERENCES_NAME
= 'Directory Preferences',
51 EVENT_PREFERENCES_NAME
= 'Event Preferences',
52 MAILING_PREFERENCES_NAME
= 'Mailing Preferences',
53 MAP_PREFERENCES_NAME
= 'Map Preferences',
54 CONTRIBUTE_PREFERENCES_NAME
= 'Contribute Preferences',
55 MEMBER_PREFERENCES_NAME
= 'Member Preferences',
56 MULTISITE_PREFERENCES_NAME
= 'Multi Site Preferences',
57 PERSONAL_PREFERENCES_NAME
= 'Personal Preferences',
58 SYSTEM_PREFERENCES_NAME
= 'CiviCRM Preferences',
59 URL_PREFERENCES_NAME
= 'URL Preferences',
60 LOCALIZATION_PREFERENCES_NAME
= 'Localization Preferences',
61 SEARCH_PREFERENCES_NAME
= 'Search Preferences';
64 * Retrieve the value of a setting from the DB table.
66 * @param string $group
67 * The group name of the item (deprecated).
69 * (required) The name under which this item is stored.
70 * @param int $componentID
71 * The optional component ID (so componenets can share the same name space).
72 * @param string $defaultValue
73 * The default value to return for this setting if not present in DB.
74 * @param int $contactID
75 * If set, this is a contactID specific setting, else its a global setting.
77 * @param int $domainID
80 * The data if present in the setting table, else null
82 public static function getItem(
90 /** @var \Civi\Core\SettingsManager $manager */
91 $manager = \Civi
::service('settings_manager');
92 $settings = ($contactID === NULL) ?
$manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
94 CRM_Core_Error
::debug_log_message("Deprecated: Group='$group'. Name should be provided.\n");
96 if ($componentID !== NULL) {
97 CRM_Core_Error
::debug_log_message("Deprecated: Group='$group'. Name='$name'. Component should be omitted\n");
99 if ($defaultValue !== NULL) {
100 CRM_Core_Error
::debug_log_message("Deprecated: Group='$group'. Name='$name'. Defaults should come from metadata\n");
102 return $name ?
$settings->get($name) : $settings->all();
106 * Get multiple items from the setting table.
108 * @param array $params
109 * (required) An api formatted array of keys and values.
110 * @param array $domains Array of domains to get settings for. Default is the current domain
111 * @param $settingsToReturn
115 public static function getItems(&$params, $domains = NULL, $settingsToReturn) {
116 $originalDomain = CRM_Core_Config
::domainID();
117 if (empty($domains)) {
118 $domains[] = $originalDomain;
120 if (!empty($settingsToReturn) && !is_array($settingsToReturn)) {
121 $settingsToReturn = [$settingsToReturn];
124 $fields = $result = [];
125 $fieldsToGet = self
::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
126 foreach ($domains as $domainID) {
127 $result[$domainID] = [];
128 foreach ($fieldsToGet as $name => $value) {
129 $contactID = CRM_Utils_Array
::value('contact_id', $params);
130 $setting = CRM_Core_BAO_Setting
::getItem(NULL, $name, NULL, NULL, $contactID, $domainID);
131 if (!is_null($setting)) {
132 // we won't return if not set - helps in return all scenario - otherwise we can't indentify the missing ones
133 // e.g for revert of fill actions
134 $result[$domainID][$name] = $setting;
142 * Store an item in the setting table.
144 * _setItem() is the common logic shared by setItem() and setItems().
146 * @param object $value
147 * (required) The value that will be serialized and stored.
148 * @param string $group
149 * The group name of the item (deprecated).
150 * @param string $name
151 * (required) The name of the setting.
152 * @param int $componentID
153 * The optional component ID (so componenets can share the same name space).
154 * @param int $contactID
155 * @param int $createdID
156 * An optional ID to assign the creator to. If not set, retrieved from session.
158 * @param int $domainID
160 public static function setItem(
169 /** @var \Civi\Core\SettingsManager $manager */
170 $manager = \Civi
::service('settings_manager');
171 $settings = ($contactID === NULL) ?
$manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
172 $settings->set($name, $value);
176 * Store multiple items in the setting table. Note that this will also store config keys
177 * the storage is determined by the metdata and is affected by
178 * 'name' setting's name
179 * 'config_key' = the config key is different to the settings key - e.g. debug where there was a conflict
180 * 'legacy_key' = rename from config or setting with this name
182 * _setItem() is the common logic shared by setItem() and setItems().
184 * @param array $params
185 * (required) An api formatted array of keys and values.
186 * @param null $domains
188 * @throws api_Exception
189 * @domains array an array of domains to get settings for. Default is the current domain
192 public static function setItems(&$params, $domains = NULL) {
193 $domains = empty($domains) ?
[CRM_Core_Config
::domainID()] : $domains;
195 // FIXME: redundant validation
196 // FIXME: this whole thing should just be a loop to call $settings->add() on each domain.
199 $fieldsToSet = self
::validateSettingsInput($params, $fields);
201 foreach ($fieldsToSet as $settingField => &$settingValue) {
202 if (empty($fields['values'][$settingField])) {
203 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']);
204 $fields['values'][$settingField] = [];
206 self
::validateSetting($settingValue, $fields['values'][$settingField]);
209 foreach ($domains as $domainID) {
210 Civi
::settings($domainID)->add($fieldsToSet);
211 $result[$domainID] = $fieldsToSet;
218 * Gets metadata about the settings fields (from getfields) based on the fields being passed in
220 * This function filters on the fields like 'version' & 'debug' that are not settings
222 * @param array $params
223 * Parameters as passed into API.
224 * @param array $fields
225 * Empty array to be populated with fields metadata.
226 * @param bool $createMode
228 * @throws api_Exception
230 * name => value array of the fields to be set (with extraneous removed)
232 public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
251 // CRM-18347: ignore params unintentionally passed by API explorer on WP
254 // CRM-18347: ignore params unintentionally passed by wp CLI tool
256 // CRM-19877: ignore params extraneously passed by Joomla
260 $settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
261 $getFieldsParams = ['version' => 3];
262 if (count($settingParams) == 1) {
263 // ie we are only setting one field - we'll pass it into getfields for efficiency
264 list($name) = array_keys($settingParams);
265 $getFieldsParams['name'] = $name;
267 $fields = civicrm_api3('setting', 'getfields', $getFieldsParams);
268 $invalidParams = (array_diff_key($settingParams, $fields['values']));
269 if (!empty($invalidParams)) {
270 throw new api_Exception(implode(',', array_keys($invalidParams)) . " not valid settings");
272 if (!empty($settingParams)) {
273 $filteredFields = array_intersect_key($settingParams, $fields['values']);
276 // no filters so we are interested in all for get mode. In create mode this means nothing to set
277 $filteredFields = $createMode ?
[] : $fields['values'];
279 return $filteredFields;
283 * Validate & convert settings input.
285 * @param mixed $value
286 * value of the setting to be set
287 * @param array $fieldSpec
288 * Metadata for given field (drawn from the xml)
291 * @throws \api_Exception
293 public static function validateSetting(&$value, array $fieldSpec) {
294 if ($fieldSpec['type'] == 'String' && is_array($value)) {
295 $value = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value) . CRM_Core_DAO
::VALUE_SEPARATOR
;
297 if (empty($fieldSpec['validate_callback'])) {
301 $cb = Civi\Core\Resolver
::singleton()->get($fieldSpec['validate_callback']);
302 if (!call_user_func_array($cb, array(&$value, $fieldSpec))) {
303 throw new api_Exception("validation failed for {$fieldSpec['name']} = $value based on callback {$fieldSpec['validate_callback']}");
309 * Validate & convert settings input - translate True False to 0 or 1.
311 * @param mixed $value value of the setting to be set
312 * @param array $fieldSpec Metadata for given field (drawn from the xml)
315 * @throws \api_Exception
317 public static function validateBoolSetting(&$value, $fieldSpec) {
318 if (!CRM_Utils_Rule
::boolean($value)) {
319 throw new api_Exception("Boolean value required for {$fieldSpec['name']}");
331 * This provides information about the setting - similar to the fields concept for DAO information.
332 * As the setting is serialized code creating validation setting input needs to know the data type
333 * This also helps move information out of the form layer into the data layer where people can interact with
334 * it via the API or other mechanisms. In order to keep this consistent it is important the form layer
337 * Note that this function should never be called when using the runtime getvalue function. Caching works
338 * around the expectation it will be called during setting administration
340 * Function is intended for configuration rather than runtime access to settings
342 * The following params will filter the result. If none are passed all settings will be returns
344 * @param int $componentID
345 * Id of relevant component.
346 * @param array $filters
347 * @param int $domainID
348 * @param null $profile
351 * the following information as appropriate for each setting
355 * - add (CiviCRM version added)
361 public static function getSettingSpecification(
367 return \Civi\Core\SettingsMetadata
::getMetadata($filters, $domainID);
372 * @param string $name
373 * @param bool $system
375 * @param bool $localize
376 * @param string $returnField
377 * @param bool $returnNameANDLabels
378 * @param null $condition
382 public static function valueOptions(
388 $returnField = 'name',
389 $returnNameANDLabels = FALSE,
392 $optionValue = self
::getItem($group, $name);
394 $groupValues = CRM_Core_OptionGroup
::values($name, FALSE, FALSE, $localize, $condition, $returnField);
396 //enabled name => label require for new contact edit form, CRM-4605
397 if ($returnNameANDLabels) {
398 $names = $labels = $nameAndLabels = [];
399 if ($returnField == 'name') {
400 $names = $groupValues;
401 $labels = CRM_Core_OptionGroup
::values($name, FALSE, FALSE, $localize, $condition, 'label');
404 $labels = $groupValues;
405 $names = CRM_Core_OptionGroup
::values($name, FALSE, FALSE, $localize, $condition, 'name');
410 foreach ($groupValues as $gn => $gv) {
411 $returnValues[$gv] = 0;
414 if ($optionValue && !empty($groupValues)) {
415 $dbValues = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
416 substr($optionValue, 1, -1)
419 if (!empty($dbValues)) {
420 foreach ($groupValues as $key => $val) {
421 if (in_array($key, $dbValues)) {
422 $returnValues[$val] = 1;
423 if ($returnNameANDLabels) {
424 $nameAndLabels[$names[$key]] = $labels[$key];
430 return ($returnNameANDLabels) ?
$nameAndLabels : $returnValues;
434 * @param $group (deprecated)
435 * @param string $name
437 * @param bool $system
439 * @param string $keyField
441 public static function setValueOption(
452 elseif (is_array($value)) {
453 $groupValues = CRM_Core_OptionGroup
::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
456 foreach ($groupValues as $key => $val) {
457 if (!empty($value[$val])) {
462 if (!empty($cbValues)) {
463 $optionValue = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
464 array_keys($cbValues)
465 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
472 $optionValue = $value;
475 self
::setItem($optionValue, $group, $name);
479 * Check if environment is explicitly set.
483 public static function isEnvironmentSet($setting, $value = NULL) {
484 $environment = CRM_Core_Config
::environment();
485 if ($setting == 'environment' && $environment) {
492 * Check if job is able to be executed by API.
494 * @throws API_Exception
496 public static function isAPIJobAllowedToRun($params) {
497 $environment = CRM_Core_Config
::environment(NULL, TRUE);
498 if ($environment != 'Production') {
499 if (!empty($params['runInNonProductionEnvironment'])) {
500 $mailing = Civi
::settings()->get('mailing_backend_store');
502 Civi
::settings()->set('mailing_backend', $mailing);
506 throw new Exception(ts("Job has not been executed as it is a %1 (non-production) environment.", [1 => $environment]));
512 * Setting Callback - On Change.
514 * Respond to changes in the "environment" setting.
516 * @param array $oldValue
517 * Value of old environment mode.
518 * @param array $newValue
519 * Value of new environment mode.
520 * @param array $metadata
521 * Specification of the setting (per *.settings.php).
523 public static function onChangeEnvironmentSetting($oldValue, $newValue, $metadata) {
524 if ($newValue != 'Production') {
525 $mailing = Civi
::settings()->get('mailing_backend');
526 if ($mailing['outBound_option'] != 2) {
527 Civi
::settings()->set('mailing_backend_store', $mailing);
529 Civi
::settings()->set('mailing_backend', ['outBound_option' => CRM_Mailing_Config
::OUTBOUND_OPTION_DISABLED
]);
530 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");
533 $mailing = Civi
::settings()->get('mailing_backend_store');
535 Civi
::settings()->set('mailing_backend', $mailing);