Merge pull request #14793 from eileenmcnaughton/update_test
[civicrm-core.git] / CRM / Core / BAO / Setting.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
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)
37 *
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.
6a488035
TO
40 */
41class CRM_Core_BAO_Setting extends CRM_Core_DAO_Setting {
42
43 /**
fe482240 44 * Various predefined settings that have been migrated to the setting table.
6a488035 45 */
7da04cde 46 const
6a488035
TO
47 ADDRESS_STANDARDIZATION_PREFERENCES_NAME = 'Address Standardization Preferences',
48 CAMPAIGN_PREFERENCES_NAME = 'Campaign Preferences',
5d0140d9 49 DEVELOPER_PREFERENCES_NAME = 'Developer Preferences',
6a488035
TO
50 DIRECTORY_PREFERENCES_NAME = 'Directory Preferences',
51 EVENT_PREFERENCES_NAME = 'Event Preferences',
52 MAILING_PREFERENCES_NAME = 'Mailing Preferences',
1ec598f3 53 MAP_PREFERENCES_NAME = 'Map Preferences',
6a488035
TO
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';
6a488035 62
6a488035 63 /**
fe482240 64 * Retrieve the value of a setting from the DB table.
6a488035 65 *
6a0b768e 66 * @param string $group
73152f09 67 * The group name of the item (deprecated).
6a0b768e
TO
68 * @param string $name
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.
da6b46f4 76 *
100fef9d 77 * @param int $domainID
6a488035 78 *
72b3a70c
CW
79 * @return mixed
80 * The data if present in the setting table, else null
6a488035 81 */
2da40d21 82 public static function getItem(
56cb3188 83 $group,
242bd179
TO
84 $name = NULL,
85 $componentID = NULL,
6a488035 86 $defaultValue = NULL,
242bd179
TO
87 $contactID = NULL,
88 $domainID = NULL
6a488035 89 ) {
3a84c0ab
TO
90 /** @var \Civi\Core\SettingsManager $manager */
91 $manager = \Civi::service('settings_manager');
92 $settings = ($contactID === NULL) ? $manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
73152f09
JK
93 if ($name === NULL) {
94 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name should be provided.\n");
95 }
96 if ($componentID !== NULL) {
97 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name='$name'. Component should be omitted\n");
98 }
99 if ($defaultValue !== NULL) {
100 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name='$name'. Defaults should come from metadata\n");
6a488035 101 }
3a84c0ab 102 return $name ? $settings->get($name) : $settings->all();
6a488035
TO
103 }
104
105 /**
299cd62a 106 * Get multiple items from the setting table.
6a488035 107 *
6a0b768e
TO
108 * @param array $params
109 * (required) An api formatted array of keys and values.
35823763 110 * @param array $domains Array of domains to get settings for. Default is the current domain
dd244018
EM
111 * @param $settingsToReturn
112 *
35823763 113 * @return array
6a488035 114 */
00be9182 115 public static function getItems(&$params, $domains = NULL, $settingsToReturn) {
0e04f44e 116 $originalDomain = CRM_Core_Config::domainID();
6a488035 117 if (empty($domains)) {
0e04f44e 118 $domains[] = $originalDomain;
6a488035
TO
119 }
120 if (!empty($settingsToReturn) && !is_array($settingsToReturn)) {
be2fb01f 121 $settingsToReturn = [$settingsToReturn];
6a488035 122 }
0e04f44e 123
be2fb01f 124 $fields = $result = [];
6a488035 125 $fieldsToGet = self::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
7583c3f3 126 foreach ($domains as $domainID) {
be2fb01f 127 $result[$domainID] = [];
6a488035 128 foreach ($fieldsToGet as $name => $value) {
76bd16ab
TO
129 $contactID = CRM_Utils_Array::value('contact_id', $params);
130 $setting = CRM_Core_BAO_Setting::getItem(NULL, $name, NULL, NULL, $contactID, $domainID);
6a488035
TO
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
7583c3f3 134 $result[$domainID][$name] = $setting;
6a488035
TO
135 }
136 }
137 }
138 return $result;
139 }
140
141 /**
fe482240 142 * Store an item in the setting table.
6a488035 143 *
a57707d3
TO
144 * _setItem() is the common logic shared by setItem() and setItems().
145 *
6a0b768e
TO
146 * @param object $value
147 * (required) The value that will be serialized and stored.
148 * @param string $group
73152f09 149 * The group name of the item (deprecated).
6a0b768e
TO
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).
100fef9d 154 * @param int $contactID
6a0b768e
TO
155 * @param int $createdID
156 * An optional ID to assign the creator to. If not set, retrieved from session.
fd31fa4c 157 *
100fef9d 158 * @param int $domainID
6a488035 159 */
2da40d21 160 public static function setItem(
6a488035
TO
161 $value,
162 $group,
163 $name,
164 $componentID = NULL,
242bd179
TO
165 $contactID = NULL,
166 $createdID = NULL,
167 $domainID = NULL
a57707d3 168 ) {
3a84c0ab
TO
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);
a57707d3
TO
173 }
174
6a488035
TO
175 /**
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
6a488035
TO
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
181 *
a57707d3
TO
182 * _setItem() is the common logic shared by setItem() and setItems().
183 *
6a0b768e
TO
184 * @param array $params
185 * (required) An api formatted array of keys and values.
2a6da8d7
EM
186 * @param null $domains
187 *
188 * @throws api_Exception
6a488035 189 * @domains array an array of domains to get settings for. Default is the current domain
3d0d359e 190 * @return array
6a488035 191 */
00be9182 192 public static function setItems(&$params, $domains = NULL) {
be2fb01f 193 $domains = empty($domains) ? [CRM_Core_Config::domainID()] : $domains;
3a84c0ab
TO
194
195 // FIXME: redundant validation
196 // FIXME: this whole thing should just be a loop to call $settings->add() on each domain.
197
be2fb01f 198 $fields = [];
6a488035
TO
199 $fieldsToSet = self::validateSettingsInput($params, $fields);
200
201 foreach ($fieldsToSet as $settingField => &$settingValue) {
4cf5500c 202 if (empty($fields['values'][$settingField])) {
be2fb01f
CW
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] = [];
4cf5500c 205 }
6a488035
TO
206 self::validateSetting($settingValue, $fields['values'][$settingField]);
207 }
208
7583c3f3 209 foreach ($domains as $domainID) {
23bb9c85
TO
210 Civi::settings($domainID)->add($fieldsToSet);
211 $result[$domainID] = $fieldsToSet;
6a488035
TO
212 }
213
214 return $result;
215 }
216
217 /**
100fef9d 218 * Gets metadata about the settings fields (from getfields) based on the fields being passed in
6a488035
TO
219 *
220 * This function filters on the fields like 'version' & 'debug' that are not settings
77b97be7 221 *
6a0b768e
TO
222 * @param array $params
223 * Parameters as passed into API.
224 * @param array $fields
225 * Empty array to be populated with fields metadata.
6a488035
TO
226 * @param bool $createMode
227 *
77b97be7 228 * @throws api_Exception
a6c01b45
CW
229 * @return array
230 * name => value array of the fields to be set (with extraneous removed)
6a488035 231 */
00be9182 232 public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
be2fb01f 233 $ignoredParams = [
6a488035
TO
234 'version',
235 'id',
236 'domain_id',
237 'debug',
238 'created_id',
239 'component_id',
240 'contact_id',
241 'filters',
242 'entity_id',
243 'entity_table',
244 'sequential',
245 'api.has_parent',
f704dce7 246 'IDS_request_uri',
247 'IDS_user_agent',
248 'check_permissions',
80fbde47 249 'options',
e56fd67f 250 'prettyprint',
2ed80443
FG
251 // CRM-18347: ignore params unintentionally passed by API explorer on WP
252 'page',
253 'noheader',
254 // CRM-18347: ignore params unintentionally passed by wp CLI tool
255 '',
a3396545
FG
256 // CRM-19877: ignore params extraneously passed by Joomla
257 'option',
258 'task',
be2fb01f 259 ];
6a488035 260 $settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
be2fb01f 261 $getFieldsParams = ['version' => 3];
d3e86119 262 if (count($settingParams) == 1) {
6a488035
TO
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;
266 }
353ffa53 267 $fields = civicrm_api3('setting', 'getfields', $getFieldsParams);
6a488035
TO
268 $invalidParams = (array_diff_key($settingParams, $fields['values']));
269 if (!empty($invalidParams)) {
e56fd67f 270 throw new api_Exception(implode(',', array_keys($invalidParams)) . " not valid settings");
6a488035
TO
271 }
272 if (!empty($settingParams)) {
273 $filteredFields = array_intersect_key($settingParams, $fields['values']);
274 }
275 else {
276 // no filters so we are interested in all for get mode. In create mode this means nothing to set
be2fb01f 277 $filteredFields = $createMode ? [] : $fields['values'];
6a488035
TO
278 }
279 return $filteredFields;
280 }
281
282 /**
3bdf1f3a 283 * Validate & convert settings input.
6a488035 284 *
3bdf1f3a 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)
289 *
290 * @return bool
291 * @throws \api_Exception
6a488035 292 */
e566ea47 293 public static function validateSetting(&$value, array $fieldSpec) {
9b873358 294 if ($fieldSpec['type'] == 'String' && is_array($value)) {
353ffa53 295 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
296 }
297 if (empty($fieldSpec['validate_callback'])) {
607cb45e 298 return TRUE;
6a488035
TO
299 }
300 else {
c8074a93
TO
301 $cb = Civi\Core\Resolver::singleton()->get($fieldSpec['validate_callback']);
302 if (!call_user_func_array($cb, array(&$value, $fieldSpec))) {
ee7b49c4 303 throw new api_Exception("validation failed for {$fieldSpec['name']} = $value based on callback {$fieldSpec['validate_callback']}");
6a488035
TO
304 }
305 }
306 }
307
308 /**
ea3ddccf 309 * Validate & convert settings input - translate True False to 0 or 1.
6a488035 310 *
ea3ddccf 311 * @param mixed $value value of the setting to be set
312 * @param array $fieldSpec Metadata for given field (drawn from the xml)
313 *
314 * @return bool
315 * @throws \api_Exception
6a488035 316 */
00be9182 317 public static function validateBoolSetting(&$value, $fieldSpec) {
6a488035 318 if (!CRM_Utils_Rule::boolean($value)) {
ee7b49c4 319 throw new api_Exception("Boolean value required for {$fieldSpec['name']}");
6a488035
TO
320 }
321 if (!$value) {
322 $value = 0;
323 }
324 else {
325 $value = 1;
326 }
327 return TRUE;
328 }
329
6a488035
TO
330 /**
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
335 * also leverages it.
336 *
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
339 *
340 * Function is intended for configuration rather than runtime access to settings
341 *
342 * The following params will filter the result. If none are passed all settings will be returns
343 *
6a0b768e
TO
344 * @param int $componentID
345 * Id of relevant component.
2a6da8d7 346 * @param array $filters
c490a46a 347 * @param int $domainID
2a6da8d7
EM
348 * @param null $profile
349 *
a6c01b45
CW
350 * @return array
351 * the following information as appropriate for each setting
5c766a0b
TO
352 * - name
353 * - type
354 * - default
355 * - add (CiviCRM version added)
356 * - is_domain
357 * - is_contact
358 * - description
359 * - help_text
6a488035 360 */
2da40d21 361 public static function getSettingSpecification(
607cb45e 362 $componentID = NULL,
be2fb01f 363 $filters = [],
607cb45e
TO
364 $domainID = NULL,
365 $profile = NULL
b597d0b1 366 ) {
e1d39824 367 return \Civi\Core\SettingsMetadata::getMetadata($filters, $domainID);
6a488035
TO
368 }
369
b5c2afd0
EM
370 /**
371 * @param $group
100fef9d 372 * @param string $name
b5c2afd0 373 * @param bool $system
100fef9d 374 * @param int $userID
b5c2afd0
EM
375 * @param bool $localize
376 * @param string $returnField
377 * @param bool $returnNameANDLabels
378 * @param null $condition
379 *
380 * @return array
381 */
2da40d21 382 public static function valueOptions(
f9f40af3 383 $group,
6a488035 384 $name,
242bd179
TO
385 $system = TRUE,
386 $userID = NULL,
387 $localize = FALSE,
388 $returnField = 'name',
6a488035 389 $returnNameANDLabels = FALSE,
242bd179 390 $condition = NULL
6a488035
TO
391 ) {
392 $optionValue = self::getItem($group, $name);
393
394 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, $returnField);
395
396 //enabled name => label require for new contact edit form, CRM-4605
397 if ($returnNameANDLabels) {
be2fb01f 398 $names = $labels = $nameAndLabels = [];
6a488035
TO
399 if ($returnField == 'name') {
400 $names = $groupValues;
401 $labels = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'label');
402 }
403 else {
404 $labels = $groupValues;
405 $names = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'name');
406 }
407 }
408
be2fb01f 409 $returnValues = [];
6a488035
TO
410 foreach ($groupValues as $gn => $gv) {
411 $returnValues[$gv] = 0;
412 }
413
414 if ($optionValue && !empty($groupValues)) {
415 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
416 substr($optionValue, 1, -1)
417 );
418
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];
425 }
426 }
427 }
428 }
429 }
430 return ($returnNameANDLabels) ? $nameAndLabels : $returnValues;
431 }
432
b5c2afd0 433 /**
73152f09 434 * @param $group (deprecated)
100fef9d 435 * @param string $name
b5c2afd0
EM
436 * @param $value
437 * @param bool $system
100fef9d 438 * @param int $userID
b5c2afd0
EM
439 * @param string $keyField
440 */
2da40d21 441 public static function setValueOption(
f9f40af3 442 $group,
6a488035
TO
443 $name,
444 $value,
242bd179
TO
445 $system = TRUE,
446 $userID = NULL,
6a488035
TO
447 $keyField = 'name'
448 ) {
449 if (empty($value)) {
450 $optionValue = NULL;
451 }
452 elseif (is_array($value)) {
453 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
454
be2fb01f 455 $cbValues = [];
6a488035 456 foreach ($groupValues as $key => $val) {
a7488080 457 if (!empty($value[$val])) {
6a488035
TO
458 $cbValues[$key] = 1;
459 }
460 }
461
462 if (!empty($cbValues)) {
463 $optionValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
353ffa53
TO
464 array_keys($cbValues)
465 ) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
466 }
467 else {
468 $optionValue = NULL;
469 }
470 }
471 else {
472 $optionValue = $value;
473 }
474
475 self::setItem($optionValue, $group, $name);
476 }
477
f008885c
E
478 /**
479 * Check if environment is explicitly set.
480 *
481 * @return bool
482 */
483 public static function isEnvironmentSet($setting, $value = NULL) {
484 $environment = CRM_Core_Config::environment();
485 if ($setting == 'environment' && $environment) {
486 return TRUE;
487 }
488 return FALSE;
489 }
490
491 /**
492 * Check if job is able to be executed by API.
493 *
494 * @throws API_Exception
495 */
496 public static function isAPIJobAllowedToRun($params) {
03c5ceba 497 $environment = CRM_Core_Config::environment(NULL, TRUE);
498 if ($environment != 'Production') {
499 if (CRM_Utils_Array::value('runInNonProductionEnvironment', $params)) {
500 $mailing = Civi::settings()->get('mailing_backend_store');
501 if ($mailing) {
502 Civi::settings()->set('mailing_backend', $mailing);
503 }
504 }
505 else {
be2fb01f 506 throw new Exception(ts("Job has not been executed as it is a %1 (non-production) environment.", [1 => $environment]));
03c5ceba 507 }
508 }
509 }
510
511 /**
512 * Setting Callback - On Change.
513 *
514 * Respond to changes in the "environment" setting.
515 *
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).
522 */
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);
528 }
be2fb01f 529 Civi::settings()->set('mailing_backend', ['outBound_option' => CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED]);
03c5ceba 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");
531 }
532 else {
533 $mailing = Civi::settings()->get('mailing_backend_store');
534 if ($mailing) {
535 Civi::settings()->set('mailing_backend', $mailing);
536 }
f008885c
E
537 }
538 }
539
2c7039ef 540}