Merge pull request #9599 from colemanw/CRM-19812
[civicrm-core.git] / CRM / Core / BAO / Setting.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
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 /**
35823763 106 * Store multiple items in 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)) {
121 $settingsToReturn = array($settingsToReturn);
122 }
0e04f44e 123 $reloadConfig = FALSE;
124
6a488035
TO
125 $fields = $result = array();
126 $fieldsToGet = self::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
7583c3f3 127 foreach ($domains as $domainID) {
9b873358 128 if ($domainID != CRM_Core_Config::domainID()) {
0e04f44e 129 $reloadConfig = TRUE;
7583c3f3 130 CRM_Core_BAO_Domain::setDomain($domainID);
0e04f44e 131 }
132 $config = CRM_Core_Config::singleton($reloadConfig, $reloadConfig);
7583c3f3 133 $result[$domainID] = array();
6a488035 134 foreach ($fieldsToGet as $name => $value) {
76bd16ab
TO
135 $contactID = CRM_Utils_Array::value('contact_id', $params);
136 $setting = CRM_Core_BAO_Setting::getItem(NULL, $name, NULL, NULL, $contactID, $domainID);
6a488035
TO
137 if (!is_null($setting)) {
138 // we won't return if not set - helps in return all scenario - otherwise we can't indentify the missing ones
139 // e.g for revert of fill actions
7583c3f3 140 $result[$domainID][$name] = $setting;
6a488035
TO
141 }
142 }
7583c3f3 143 CRM_Core_BAO_Domain::resetDomain();
6a488035
TO
144 }
145 return $result;
146 }
147
148 /**
fe482240 149 * Store an item in the setting table.
6a488035 150 *
a57707d3
TO
151 * _setItem() is the common logic shared by setItem() and setItems().
152 *
6a0b768e
TO
153 * @param object $value
154 * (required) The value that will be serialized and stored.
155 * @param string $group
73152f09 156 * The group name of the item (deprecated).
6a0b768e
TO
157 * @param string $name
158 * (required) The name of the setting.
159 * @param int $componentID
160 * The optional component ID (so componenets can share the same name space).
100fef9d 161 * @param int $contactID
6a0b768e
TO
162 * @param int $createdID
163 * An optional ID to assign the creator to. If not set, retrieved from session.
fd31fa4c 164 *
100fef9d 165 * @param int $domainID
6a488035 166 */
2da40d21 167 public static function setItem(
6a488035
TO
168 $value,
169 $group,
170 $name,
171 $componentID = NULL,
242bd179
TO
172 $contactID = NULL,
173 $createdID = NULL,
174 $domainID = NULL
a57707d3 175 ) {
3a84c0ab
TO
176 /** @var \Civi\Core\SettingsManager $manager */
177 $manager = \Civi::service('settings_manager');
178 $settings = ($contactID === NULL) ? $manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
179 $settings->set($name, $value);
a57707d3
TO
180 }
181
6a488035
TO
182 /**
183 * Store multiple items in the setting table. Note that this will also store config keys
184 * the storage is determined by the metdata and is affected by
185 * 'name' setting's name
6a488035
TO
186 * 'config_key' = the config key is different to the settings key - e.g. debug where there was a conflict
187 * 'legacy_key' = rename from config or setting with this name
188 *
a57707d3
TO
189 * _setItem() is the common logic shared by setItem() and setItems().
190 *
6a0b768e
TO
191 * @param array $params
192 * (required) An api formatted array of keys and values.
2a6da8d7
EM
193 * @param null $domains
194 *
195 * @throws api_Exception
6a488035 196 * @domains array an array of domains to get settings for. Default is the current domain
3d0d359e 197 * @return array
6a488035 198 */
00be9182 199 public static function setItems(&$params, $domains = NULL) {
3a84c0ab
TO
200 $domains = empty($domains) ? array(CRM_Core_Config::domainID()) : $domains;
201
202 // FIXME: redundant validation
203 // FIXME: this whole thing should just be a loop to call $settings->add() on each domain.
204
23bb9c85 205 $fields = array();
6a488035
TO
206 $fieldsToSet = self::validateSettingsInput($params, $fields);
207
208 foreach ($fieldsToSet as $settingField => &$settingValue) {
209 self::validateSetting($settingValue, $fields['values'][$settingField]);
210 }
211
7583c3f3 212 foreach ($domains as $domainID) {
23bb9c85
TO
213 Civi::settings($domainID)->add($fieldsToSet);
214 $result[$domainID] = $fieldsToSet;
6a488035
TO
215 }
216
217 return $result;
218 }
219
220 /**
100fef9d 221 * Gets metadata about the settings fields (from getfields) based on the fields being passed in
6a488035
TO
222 *
223 * This function filters on the fields like 'version' & 'debug' that are not settings
77b97be7 224 *
6a0b768e
TO
225 * @param array $params
226 * Parameters as passed into API.
227 * @param array $fields
228 * Empty array to be populated with fields metadata.
6a488035
TO
229 * @param bool $createMode
230 *
77b97be7 231 * @throws api_Exception
a6c01b45
CW
232 * @return array
233 * name => value array of the fields to be set (with extraneous removed)
6a488035 234 */
00be9182 235 public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
6a488035
TO
236 $ignoredParams = array(
237 'version',
238 'id',
239 'domain_id',
240 'debug',
241 'created_id',
242 'component_id',
243 'contact_id',
244 'filters',
245 'entity_id',
246 'entity_table',
247 'sequential',
248 'api.has_parent',
f704dce7 249 'IDS_request_uri',
250 'IDS_user_agent',
251 'check_permissions',
80fbde47 252 'options',
e56fd67f 253 'prettyprint',
2ed80443
FG
254 // CRM-18347: ignore params unintentionally passed by API explorer on WP
255 'page',
256 'noheader',
257 // CRM-18347: ignore params unintentionally passed by wp CLI tool
258 '',
6a488035
TO
259 );
260 $settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
261 $getFieldsParams = array('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
277 $filteredFields = $createMode ? array() : $fields['values'];
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 */
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 /**
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,
b597d0b1 363 $filters = array(),
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) {
398 $names = $labels = $nameAndLabels = array();
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
409 $returnValues = array();
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
455 $cbValues = array();
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
2c7039ef 478 /**
100fef9d 479 * Civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
2c7039ef 480 *
5c766a0b 481 * @return bool
2c7039ef 482 */
00be9182 483 public static function isUpgradeFromPreFourOneAlpha1() {
2c7039ef
DS
484 if (CRM_Core_Config::isUpgradeMode()) {
485 $currentVer = CRM_Core_BAO_Domain::version();
486 if (version_compare($currentVer, '4.1.alpha1') < 0) {
487 return TRUE;
488 }
489 }
490 return FALSE;
491 }
96025800 492
2c7039ef 493}