SettingsBag::setDb() - Merge in CRM_Core_BAO_Setting::_setItem and ::dao()
[civicrm-core.git] / CRM / Core / BAO / Setting.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
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
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
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
TO
66 * @param string $group
67 * (required) The group name of the item.
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);
93 if (TRUE) {
94 if ($name === NULL) {
95 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name should be provided.\n");
bf83df95 96 }
3a84c0ab
TO
97 if ($componentID !== NULL) {
98 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name='$name'. Component should be omitted\n");
6a488035 99 }
3a84c0ab
TO
100 if ($defaultValue !== NULL) {
101 CRM_Core_Error::debug_log_message("Deprecated: Group='$group'. Name='$name'. Defaults should come from metadata\n");
bf83df95 102 }
6a488035 103 }
3a84c0ab 104 return $name ? $settings->get($name) : $settings->all();
6a488035
TO
105 }
106
107 /**
35823763 108 * Store multiple items in the setting table.
6a488035 109 *
6a0b768e
TO
110 * @param array $params
111 * (required) An api formatted array of keys and values.
35823763 112 * @param array $domains Array of domains to get settings for. Default is the current domain
dd244018
EM
113 * @param $settingsToReturn
114 *
35823763 115 * @return array
6a488035 116 */
00be9182 117 public static function getItems(&$params, $domains = NULL, $settingsToReturn) {
0e04f44e 118 $originalDomain = CRM_Core_Config::domainID();
6a488035 119 if (empty($domains)) {
0e04f44e 120 $domains[] = $originalDomain;
6a488035
TO
121 }
122 if (!empty($settingsToReturn) && !is_array($settingsToReturn)) {
123 $settingsToReturn = array($settingsToReturn);
124 }
0e04f44e 125 $reloadConfig = FALSE;
126
6a488035
TO
127 $fields = $result = array();
128 $fieldsToGet = self::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
7583c3f3 129 foreach ($domains as $domainID) {
9b873358 130 if ($domainID != CRM_Core_Config::domainID()) {
0e04f44e 131 $reloadConfig = TRUE;
7583c3f3 132 CRM_Core_BAO_Domain::setDomain($domainID);
0e04f44e 133 }
134 $config = CRM_Core_Config::singleton($reloadConfig, $reloadConfig);
7583c3f3 135 $result[$domainID] = array();
6a488035 136 foreach ($fieldsToGet as $name => $value) {
52baaadf
TO
137 $setting = CRM_Core_BAO_Setting::getItem(
138 $fields['values'][$name]['group_name'],
139 $name,
140 CRM_Utils_Array::value('component_id', $params),
141 NULL,
142 CRM_Utils_Array::value('contact_id', $params),
143 $domainID
144 );
6a488035
TO
145 if (!is_null($setting)) {
146 // we won't return if not set - helps in return all scenario - otherwise we can't indentify the missing ones
147 // e.g for revert of fill actions
7583c3f3 148 $result[$domainID][$name] = $setting;
6a488035
TO
149 }
150 }
7583c3f3 151 CRM_Core_BAO_Domain::resetDomain();
6a488035
TO
152 }
153 return $result;
154 }
155
156 /**
fe482240 157 * Store an item in the setting table.
6a488035 158 *
a57707d3
TO
159 * _setItem() is the common logic shared by setItem() and setItems().
160 *
6a0b768e
TO
161 * @param object $value
162 * (required) The value that will be serialized and stored.
163 * @param string $group
164 * (required) The group name of the item.
165 * @param string $name
166 * (required) The name of the setting.
167 * @param int $componentID
168 * The optional component ID (so componenets can share the same name space).
100fef9d 169 * @param int $contactID
6a0b768e
TO
170 * @param int $createdID
171 * An optional ID to assign the creator to. If not set, retrieved from session.
fd31fa4c 172 *
100fef9d 173 * @param int $domainID
6a488035 174 */
2da40d21 175 public static function setItem(
6a488035
TO
176 $value,
177 $group,
178 $name,
179 $componentID = NULL,
242bd179
TO
180 $contactID = NULL,
181 $createdID = NULL,
182 $domainID = NULL
a57707d3 183 ) {
3a84c0ab
TO
184 /** @var \Civi\Core\SettingsManager $manager */
185 $manager = \Civi::service('settings_manager');
186 $settings = ($contactID === NULL) ? $manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
187 $settings->set($name, $value);
a57707d3
TO
188 }
189
6a488035
TO
190 /**
191 * Store multiple items in the setting table. Note that this will also store config keys
192 * the storage is determined by the metdata and is affected by
193 * 'name' setting's name
6a488035
TO
194 * 'config_key' = the config key is different to the settings key - e.g. debug where there was a conflict
195 * 'legacy_key' = rename from config or setting with this name
196 *
a57707d3
TO
197 * _setItem() is the common logic shared by setItem() and setItems().
198 *
6a0b768e
TO
199 * @param array $params
200 * (required) An api formatted array of keys and values.
2a6da8d7
EM
201 * @param null $domains
202 *
203 * @throws api_Exception
6a488035 204 * @domains array an array of domains to get settings for. Default is the current domain
3d0d359e 205 * @return array
6a488035 206 */
00be9182 207 public static function setItems(&$params, $domains = NULL) {
3a84c0ab
TO
208 $domains = empty($domains) ? array(CRM_Core_Config::domainID()) : $domains;
209
210 // FIXME: redundant validation
211 // FIXME: this whole thing should just be a loop to call $settings->add() on each domain.
212
23bb9c85 213 $fields = array();
6a488035
TO
214 $fieldsToSet = self::validateSettingsInput($params, $fields);
215
216 foreach ($fieldsToSet as $settingField => &$settingValue) {
217 self::validateSetting($settingValue, $fields['values'][$settingField]);
218 }
219
7583c3f3 220 foreach ($domains as $domainID) {
23bb9c85
TO
221 Civi::settings($domainID)->add($fieldsToSet);
222 $result[$domainID] = $fieldsToSet;
6a488035
TO
223 }
224
225 return $result;
226 }
227
228 /**
100fef9d 229 * Gets metadata about the settings fields (from getfields) based on the fields being passed in
6a488035
TO
230 *
231 * This function filters on the fields like 'version' & 'debug' that are not settings
77b97be7 232 *
6a0b768e
TO
233 * @param array $params
234 * Parameters as passed into API.
235 * @param array $fields
236 * Empty array to be populated with fields metadata.
6a488035
TO
237 * @param bool $createMode
238 *
77b97be7 239 * @throws api_Exception
a6c01b45
CW
240 * @return array
241 * name => value array of the fields to be set (with extraneous removed)
6a488035 242 */
00be9182 243 public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
6a488035
TO
244 $group = CRM_Utils_Array::value('group', $params);
245
246 $ignoredParams = array(
247 'version',
248 'id',
249 'domain_id',
250 'debug',
251 'created_id',
252 'component_id',
253 'contact_id',
254 'filters',
255 'entity_id',
256 'entity_table',
257 'sequential',
258 'api.has_parent',
f704dce7 259 'IDS_request_uri',
260 'IDS_user_agent',
261 'check_permissions',
80fbde47 262 'options',
e56fd67f 263 'prettyprint',
6a488035
TO
264 );
265 $settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
266 $getFieldsParams = array('version' => 3);
d3e86119 267 if (count($settingParams) == 1) {
6a488035
TO
268 // ie we are only setting one field - we'll pass it into getfields for efficiency
269 list($name) = array_keys($settingParams);
270 $getFieldsParams['name'] = $name;
271 }
353ffa53 272 $fields = civicrm_api3('setting', 'getfields', $getFieldsParams);
6a488035
TO
273 $invalidParams = (array_diff_key($settingParams, $fields['values']));
274 if (!empty($invalidParams)) {
e56fd67f 275 throw new api_Exception(implode(',', array_keys($invalidParams)) . " not valid settings");
6a488035
TO
276 }
277 if (!empty($settingParams)) {
278 $filteredFields = array_intersect_key($settingParams, $fields['values']);
279 }
280 else {
281 // no filters so we are interested in all for get mode. In create mode this means nothing to set
282 $filteredFields = $createMode ? array() : $fields['values'];
283 }
284 return $filteredFields;
285 }
286
287 /**
288 * Validate & convert settings input
289 *
290 * @value mixed value of the setting to be set
291 * @fieldSpec array Metadata for given field (drawn from the xml)
292 */
00be9182 293 public static function validateSetting(&$value, $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 /**
309 * Validate & convert settings input - translate True False to 0 or 1
310 *
311 * @value mixed value of the setting to be set
312 * @fieldSpec array Metadata for given field (drawn from the xml)
313 */
00be9182 314 public static function validateBoolSetting(&$value, $fieldSpec) {
6a488035 315 if (!CRM_Utils_Rule::boolean($value)) {
ee7b49c4 316 throw new api_Exception("Boolean value required for {$fieldSpec['name']}");
6a488035
TO
317 }
318 if (!$value) {
319 $value = 0;
320 }
321 else {
322 $value = 1;
323 }
324 return TRUE;
325 }
326
6a488035
TO
327 /**
328 * This provides information about the setting - similar to the fields concept for DAO information.
329 * As the setting is serialized code creating validation setting input needs to know the data type
330 * This also helps move information out of the form layer into the data layer where people can interact with
331 * it via the API or other mechanisms. In order to keep this consistent it is important the form layer
332 * also leverages it.
333 *
334 * Note that this function should never be called when using the runtime getvalue function. Caching works
335 * around the expectation it will be called during setting administration
336 *
337 * Function is intended for configuration rather than runtime access to settings
338 *
339 * The following params will filter the result. If none are passed all settings will be returns
340 *
6a0b768e
TO
341 * @param int $componentID
342 * Id of relevant component.
2a6da8d7 343 * @param array $filters
c490a46a 344 * @param int $domainID
2a6da8d7
EM
345 * @param null $profile
346 *
a6c01b45
CW
347 * @return array
348 * the following information as appropriate for each setting
5c766a0b
TO
349 * - name
350 * - type
351 * - default
352 * - add (CiviCRM version added)
353 * - is_domain
354 * - is_contact
355 * - description
356 * - help_text
6a488035 357 */
2da40d21 358 public static function getSettingSpecification(
607cb45e 359 $componentID = NULL,
b597d0b1 360 $filters = array(),
607cb45e
TO
361 $domainID = NULL,
362 $profile = NULL
b597d0b1 363 ) {
e1d39824 364 return \Civi\Core\SettingsMetadata::getMetadata($filters, $domainID);
6a488035
TO
365 }
366
367 /**
0880a9d0 368 * Look for any missing settings and convert them from config or load default as appropriate.
6a488035
TO
369 * This should be run from GenCode & also from upgrades to add any new defaults.
370 *
371 * Multisites have often been overlooked in upgrade scripts so can be expected to be missing
372 * a number of settings
373 */
00be9182 374 public static function updateSettingsFromMetaData() {
6a488035
TO
375 $apiParams = array(
376 'version' => 3,
377 'domain_id' => 'all',
eb40b5a4 378 'filters' => array('prefetch' => 0),
6a488035
TO
379 );
380 $existing = civicrm_api('setting', 'get', $apiParams);
eb40b5a4 381
6a488035
TO
382 if (!empty($existing['values'])) {
383 $allSettings = civicrm_api('setting', 'getfields', array('version' => 3));
384 foreach ($existing['values'] as $domainID => $domainSettings) {
385 CRM_Core_BAO_Domain::setDomain($domainID);
386 $missing = array_diff_key($allSettings['values'], $domainSettings);
387 foreach ($missing as $name => $settings) {
388 self::convertConfigToSetting($name, $domainID);
389 }
390 CRM_Core_BAO_Domain::resetDomain();
391 }
392 }
393 }
394
395 /**
100fef9d 396 * Move an item from being in the config array to being stored as a setting
6a488035
TO
397 * remove from config - as appropriate based on metadata
398 *
399 * Note that where the key name is being changed the 'legacy_key' will give us the old name
400 */
00be9182 401 public static function convertConfigToSetting($name, $domainID = NULL) {
eb40b5a4 402 // we have to force this here in case more than one domain is in play.
403 // whenever there is a possibility of more than one domain we must force it
6a488035
TO
404 $config = CRM_Core_Config::singleton();
405 if (empty($domainID)) {
d3e86119 406 $domainID = CRM_Core_Config::domainID();
6a488035
TO
407 }
408 $domain = new CRM_Core_DAO_Domain();
409 $domain->id = $domainID;
410 $domain->find(TRUE);
411 if ($domain->config_backend) {
412 $values = unserialize($domain->config_backend);
0db6c3e1
TO
413 }
414 else {
6a488035
TO
415 $values = array();
416 }
607cb45e 417 $spec = self::getSettingSpecification(NULL, array('name' => $name), $domainID);
6a488035 418 $configKey = CRM_Utils_Array::value('config_key', $spec[$name], CRM_Utils_Array::value('legacy_key', $spec[$name], $name));
52baaadf
TO
419 if (!empty($values[$configKey])) {
420 civicrm_api('setting', 'create', array('version' => 3, $name => $values[$configKey], 'domain_id' => $domainID));
421 }
422 else {
423 civicrm_api('setting', 'fill', array('version' => 3, 'name' => $name, 'domain_id' => $domainID));
424 }
6a488035 425
52baaadf
TO
426 if (!empty($values[$configKey])) {
427 unset($values[$configKey]);
428 $domain->config_backend = serialize($values);
429 $domain->save();
6a488035
TO
430 }
431 }
432
b5c2afd0
EM
433 /**
434 * @param $group
100fef9d 435 * @param string $name
b5c2afd0 436 * @param bool $system
100fef9d 437 * @param int $userID
b5c2afd0
EM
438 * @param bool $localize
439 * @param string $returnField
440 * @param bool $returnNameANDLabels
441 * @param null $condition
442 *
443 * @return array
444 */
2da40d21 445 public static function valueOptions(
f9f40af3 446 $group,
6a488035 447 $name,
242bd179
TO
448 $system = TRUE,
449 $userID = NULL,
450 $localize = FALSE,
451 $returnField = 'name',
6a488035 452 $returnNameANDLabels = FALSE,
242bd179 453 $condition = NULL
6a488035
TO
454 ) {
455 $optionValue = self::getItem($group, $name);
456
457 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, $returnField);
458
459 //enabled name => label require for new contact edit form, CRM-4605
460 if ($returnNameANDLabels) {
461 $names = $labels = $nameAndLabels = array();
462 if ($returnField == 'name') {
463 $names = $groupValues;
464 $labels = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'label');
465 }
466 else {
467 $labels = $groupValues;
468 $names = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'name');
469 }
470 }
471
472 $returnValues = array();
473 foreach ($groupValues as $gn => $gv) {
474 $returnValues[$gv] = 0;
475 }
476
477 if ($optionValue && !empty($groupValues)) {
478 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
479 substr($optionValue, 1, -1)
480 );
481
482 if (!empty($dbValues)) {
483 foreach ($groupValues as $key => $val) {
484 if (in_array($key, $dbValues)) {
485 $returnValues[$val] = 1;
486 if ($returnNameANDLabels) {
487 $nameAndLabels[$names[$key]] = $labels[$key];
488 }
489 }
490 }
491 }
492 }
493 return ($returnNameANDLabels) ? $nameAndLabels : $returnValues;
494 }
495
b5c2afd0
EM
496 /**
497 * @param $group
100fef9d 498 * @param string $name
b5c2afd0
EM
499 * @param $value
500 * @param bool $system
100fef9d 501 * @param int $userID
b5c2afd0
EM
502 * @param string $keyField
503 */
2da40d21 504 public static function setValueOption(
f9f40af3 505 $group,
6a488035
TO
506 $name,
507 $value,
242bd179
TO
508 $system = TRUE,
509 $userID = NULL,
6a488035
TO
510 $keyField = 'name'
511 ) {
512 if (empty($value)) {
513 $optionValue = NULL;
514 }
515 elseif (is_array($value)) {
516 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
517
518 $cbValues = array();
519 foreach ($groupValues as $key => $val) {
a7488080 520 if (!empty($value[$val])) {
6a488035
TO
521 $cbValues[$key] = 1;
522 }
523 }
524
525 if (!empty($cbValues)) {
526 $optionValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
353ffa53
TO
527 array_keys($cbValues)
528 ) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
529 }
530 else {
531 $optionValue = NULL;
532 }
533 }
534 else {
535 $optionValue = $value;
536 }
537
538 self::setItem($optionValue, $group, $name);
539 }
540
2c7039ef 541 /**
100fef9d 542 * Civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
2c7039ef 543 *
5c766a0b 544 * @return bool
2c7039ef 545 */
00be9182 546 public static function isUpgradeFromPreFourOneAlpha1() {
2c7039ef
DS
547 if (CRM_Core_Config::isUpgradeMode()) {
548 $currentVer = CRM_Core_BAO_Domain::version();
549 if (version_compare($currentVer, '4.1.alpha1') < 0) {
550 return TRUE;
551 }
552 }
553 return FALSE;
554 }
96025800 555
2c7039ef 556}