INFRA-132 comments to end with full stops
[civicrm-core.git] / CRM / Core / BAO / Setting.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * BAO object for civicrm_setting table. This table is used to store civicrm settings that are not used
38 * very frequently (i.e. not on every page load)
39 *
40 * The group column is used for grouping together all settings that logically belong to the same set.
41 * Thus all settings in the same group are retrieved with one DB call and then cached for future needs.
42 *
43 */
44class CRM_Core_BAO_Setting extends CRM_Core_DAO_Setting {
45
46 /**
fe482240 47 * Various predefined settings that have been migrated to the setting table.
6a488035 48 */
7da04cde 49 const
6a488035
TO
50 ADDRESS_STANDARDIZATION_PREFERENCES_NAME = 'Address Standardization Preferences',
51 CAMPAIGN_PREFERENCES_NAME = 'Campaign Preferences',
5d0140d9 52 DEVELOPER_PREFERENCES_NAME = 'Developer Preferences',
6a488035
TO
53 DIRECTORY_PREFERENCES_NAME = 'Directory Preferences',
54 EVENT_PREFERENCES_NAME = 'Event Preferences',
55 MAILING_PREFERENCES_NAME = 'Mailing Preferences',
56 CONTRIBUTE_PREFERENCES_NAME = 'Contribute Preferences',
57 MEMBER_PREFERENCES_NAME = 'Member Preferences',
58 MULTISITE_PREFERENCES_NAME = 'Multi Site Preferences',
59 PERSONAL_PREFERENCES_NAME = 'Personal Preferences',
60 SYSTEM_PREFERENCES_NAME = 'CiviCRM Preferences',
61 URL_PREFERENCES_NAME = 'URL Preferences',
62 LOCALIZATION_PREFERENCES_NAME = 'Localization Preferences',
63 SEARCH_PREFERENCES_NAME = 'Search Preferences';
64 static $_cache = NULL;
65
66 /**
67 * Checks whether an item is present in the in-memory cache table
68 *
6a0b768e
TO
69 * @param string $group
70 * (required) The group name of the item.
71 * @param string $name
72 * (required) The name of the setting.
73 * @param int $componentID
74 * The optional component ID (so components can share the same name space).
75 * @param int $contactID
76 * If set, this is a contactID specific setting, else its a global setting.
77b97be7
EM
77 * @param bool|int $load if true, load from local cache (typically memcache)
78 *
100fef9d 79 * @param int $domainID
77b97be7 80 * @param bool $force
6a488035 81 *
5c766a0b 82 * @return bool
a6c01b45 83 * true if item is already in cache
6a488035 84 */
2da40d21 85 public static function inCache(
eb40b5a4 86 $group,
6a488035
TO
87 $name,
88 $componentID = NULL,
242bd179
TO
89 $contactID = NULL,
90 $load = FALSE,
eb40b5a4 91 $domainID = NULL,
92 $force = FALSE
6a488035
TO
93 ) {
94 if (!isset(self::$_cache)) {
95 self::$_cache = array();
96 }
97
98 $cacheKey = "CRM_Setting_{$group}_{$componentID}_{$contactID}_{$domainID}";
eb40b5a4 99
56cb3188
DL
100 if (
101 $load &&
eb40b5a4 102 ($force || !isset(self::$_cache[$cacheKey]))
6a488035 103 ) {
eb40b5a4 104
6a488035
TO
105 // check in civi cache if present (typically memcache)
106 $globalCache = CRM_Utils_Cache::singleton();
107 $result = $globalCache->get($cacheKey);
108 if ($result) {
eb40b5a4 109
6a488035
TO
110 self::$_cache[$cacheKey] = $result;
111 }
112 }
113
114 return isset(self::$_cache[$cacheKey]) ? $cacheKey : NULL;
115 }
353ffa53 116
eb40b5a4 117 /**
fe482240 118 * Allow key o be cleared.
353ffa53
TO
119 * @param string $cacheKey
120 */
9b873358 121 public static function flushCache($cacheKey) {
eb40b5a4 122 unset(self::$_cache[$cacheKey]);
123 $globalCache = CRM_Utils_Cache::singleton();
124 $globalCache->delete($cacheKey);
125 }
6a488035 126
b5c2afd0
EM
127 /**
128 * @param $values
129 * @param $group
100fef9d
CW
130 * @param int $componentID
131 * @param int $contactID
132 * @param int $domainID
b5c2afd0
EM
133 *
134 * @return string
135 */
2da40d21 136 public static function setCache(
f9f40af3 137 $values,
6a488035
TO
138 $group,
139 $componentID = NULL,
140 $contactID = NULL,
141 $domainID = NULL
142 ) {
143 if (!isset(self::$_cache)) {
144 self::$_cache = array();
145 }
146
147 $cacheKey = "CRM_Setting_{$group}_{$componentID}_{$contactID}_{$domainID}";
148
149 self::$_cache[$cacheKey] = $values;
150
151 $globalCache = CRM_Utils_Cache::singleton();
152 $result = $globalCache->set($cacheKey, $values);
153
154 return $cacheKey;
155 }
156
b5c2afd0
EM
157 /**
158 * @param $group
159 * @param null $name
100fef9d
CW
160 * @param int $componentID
161 * @param int $contactID
162 * @param int $domainID
b5c2afd0
EM
163 *
164 * @return CRM_Core_DAO_Domain|CRM_Core_DAO_Setting
165 */
2da40d21 166 public static function dao(
f9f40af3 167 $group,
242bd179 168 $name = NULL,
6a488035 169 $componentID = NULL,
242bd179 170 $contactID = NULL,
6a488035
TO
171 $domainID = NULL
172 ) {
2c7039ef 173 if (self::isUpgradeFromPreFourOneAlpha1()) {
03d8f8f3 174 // civicrm_setting table is not going to be present. For now we'll just
2c7039ef
DS
175 // return a dummy object
176 $dao = new CRM_Core_DAO_Domain();
177 $dao->id = -1; // so ->find() doesn't fetch any data later on
178 return $dao;
179 }
6a488035
TO
180 $dao = new CRM_Core_DAO_Setting();
181
242bd179
TO
182 $dao->group_name = $group;
183 $dao->name = $name;
6a488035
TO
184 $dao->component_id = $componentID;
185 if (empty($domainID)) {
353ffa53 186 $dao->domain_id = CRM_Core_Config::domainID();
6a488035
TO
187 }
188 else {
189 $dao->domain_id = $domainID;
190 }
191
192 if ($contactID) {
193 $dao->contact_id = $contactID;
194 $dao->is_domain = 0;
195 }
196 else {
197 $dao->is_domain = 1;
198 }
199
200 return $dao;
201 }
202
203 /**
fe482240 204 * Retrieve the value of a setting from the DB table.
6a488035 205 *
6a0b768e
TO
206 * @param string $group
207 * (required) The group name of the item.
208 * @param string $name
209 * (required) The name under which this item is stored.
210 * @param int $componentID
211 * The optional component ID (so componenets can share the same name space).
212 * @param string $defaultValue
213 * The default value to return for this setting if not present in DB.
214 * @param int $contactID
215 * If set, this is a contactID specific setting, else its a global setting.
da6b46f4 216 *
100fef9d 217 * @param int $domainID
6a488035 218 *
72b3a70c
CW
219 * @return mixed
220 * The data if present in the setting table, else null
6a488035 221 */
2da40d21 222 public static function getItem(
56cb3188 223 $group,
242bd179
TO
224 $name = NULL,
225 $componentID = NULL,
6a488035 226 $defaultValue = NULL,
242bd179
TO
227 $contactID = NULL,
228 $domainID = NULL
6a488035
TO
229 ) {
230
231 if (NULL !== ($override = self::getOverride($group, $name, NULL))) {
232 return $override;
233 }
234
235 if (empty($domainID)) {
236 $domainID = CRM_Core_Config::domainID();
237 }
238 $cacheKey = self::inCache($group, $name, $componentID, $contactID, TRUE, $domainID);
239 if (!$cacheKey) {
240 $dao = self::dao($group, NULL, $componentID, $contactID, $domainID);
241 $dao->find();
242
243 $values = array();
244 while ($dao->fetch()) {
245 if (NULL !== ($override = self::getOverride($group, $dao->name, NULL))) {
246 $values[$dao->name] = $override;
247 }
248 elseif ($dao->value) {
249 $values[$dao->name] = unserialize($dao->value);
250 }
251 else {
252 $values[$dao->name] = NULL;
253 }
254 }
255 $dao->free();
256
257 $cacheKey = self::setCache($values, $group, $componentID, $contactID, $domainID);
258 }
6a488035
TO
259 return $name ? CRM_Utils_Array::value($name, self::$_cache[$cacheKey], $defaultValue) : self::$_cache[$cacheKey];
260 }
261
262 /**
35823763 263 * Store multiple items in the setting table.
6a488035 264 *
6a0b768e
TO
265 * @param array $params
266 * (required) An api formatted array of keys and values.
35823763 267 * @param array $domains Array of domains to get settings for. Default is the current domain
dd244018
EM
268 * @param $settingsToReturn
269 *
35823763 270 * @return array
6a488035 271 */
00be9182 272 public static function getItems(&$params, $domains = NULL, $settingsToReturn) {
0e04f44e 273 $originalDomain = CRM_Core_Config::domainID();
6a488035 274 if (empty($domains)) {
0e04f44e 275 $domains[] = $originalDomain;
6a488035
TO
276 }
277 if (!empty($settingsToReturn) && !is_array($settingsToReturn)) {
278 $settingsToReturn = array($settingsToReturn);
279 }
0e04f44e 280 $reloadConfig = FALSE;
281
6a488035
TO
282 $fields = $result = array();
283 $fieldsToGet = self::validateSettingsInput(array_flip($settingsToReturn), $fields, FALSE);
7583c3f3 284 foreach ($domains as $domainID) {
9b873358 285 if ($domainID != CRM_Core_Config::domainID()) {
0e04f44e 286 $reloadConfig = TRUE;
7583c3f3 287 CRM_Core_BAO_Domain::setDomain($domainID);
0e04f44e 288 }
289 $config = CRM_Core_Config::singleton($reloadConfig, $reloadConfig);
7583c3f3 290 $result[$domainID] = array();
6a488035 291 foreach ($fieldsToGet as $name => $value) {
9b873358 292 if (!empty($fields['values'][$name]['prefetch'])) {
22e263ad 293 if (isset($params['filters']) && isset($params['filters']['prefetch'])
353ffa53
TO
294 && $params['filters']['prefetch'] == 0
295 ) {
eb40b5a4 296 // we are filtering out the prefetches from the return array
297 // so we will skip
298 continue;
299 }
353ffa53 300 $configKey = CRM_Utils_Array::value('config_key', $fields['values'][$name], $name);
9b873358 301 if (isset($config->$configKey)) {
6a488035
TO
302 $setting = $config->$configKey;
303 }
304 }
305 else {
6c552737
TO
306 $setting = CRM_Core_BAO_Setting::getItem(
307 $fields['values'][$name]['group_name'],
308 $name,
309 CRM_Utils_Array::value('component_id', $params),
310 NULL,
311 CRM_Utils_Array::value('contact_id', $params),
312 $domainID
313 );
6a488035
TO
314 }
315 if (!is_null($setting)) {
316 // we won't return if not set - helps in return all scenario - otherwise we can't indentify the missing ones
317 // e.g for revert of fill actions
7583c3f3 318 $result[$domainID][$name] = $setting;
6a488035
TO
319 }
320 }
7583c3f3 321 CRM_Core_BAO_Domain::resetDomain();
6a488035
TO
322 }
323 return $result;
324 }
325
326 /**
fe482240 327 * Store an item in the setting table.
6a488035 328 *
a57707d3
TO
329 * _setItem() is the common logic shared by setItem() and setItems().
330 *
6a0b768e
TO
331 * @param object $value
332 * (required) The value that will be serialized and stored.
333 * @param string $group
334 * (required) The group name of the item.
335 * @param string $name
336 * (required) The name of the setting.
337 * @param int $componentID
338 * The optional component ID (so componenets can share the same name space).
100fef9d 339 * @param int $contactID
6a0b768e
TO
340 * @param int $createdID
341 * An optional ID to assign the creator to. If not set, retrieved from session.
fd31fa4c 342 *
100fef9d 343 * @param int $domainID
6a488035
TO
344 *
345 * @return void
6a488035 346 */
2da40d21 347 public static function setItem(
6a488035
TO
348 $value,
349 $group,
350 $name,
351 $componentID = NULL,
242bd179
TO
352 $contactID = NULL,
353 $createdID = NULL,
354 $domainID = NULL
a57707d3
TO
355 ) {
356 $fields = array();
357 $fieldsToSet = self::validateSettingsInput(array($name => $value), $fields);
358 //We haven't traditionally validated inputs to setItem, so this breaks things.
359 //foreach ($fieldsToSet as $settingField => &$settingValue) {
360 // self::validateSetting($settingValue, $fields['values'][$settingField]);
361 //}
362
363 return self::_setItem($fields['values'][$name], $value, $group, $name, $componentID, $contactID, $createdID, $domainID);
364 }
365
366 /**
fe482240 367 * Store an item in a setting table.
a57707d3
TO
368 *
369 * _setItem() is the common logic shared by setItem() and setItems().
370 *
6a0b768e
TO
371 * @param array $metadata
372 * Metadata describing this field.
a57707d3
TO
373 * @param $value
374 * @param $group
100fef9d
CW
375 * @param string $name
376 * @param int $componentID
377 * @param int $contactID
378 * @param int $createdID
379 * @param int $domainID
a57707d3 380 */
2da40d21 381 public static function _setItem(
a57707d3
TO
382 $metadata,
383 $value,
384 $group,
385 $name,
386 $componentID = NULL,
242bd179
TO
387 $contactID = NULL,
388 $createdID = NULL,
389 $domainID = NULL
6a488035 390 ) {
6a488035
TO
391 if (empty($domainID)) {
392 $domainID = CRM_Core_Config::domainID();
393 }
394
395 $dao = self::dao($group, $name, $componentID, $contactID, $domainID);
396 $dao->find(TRUE);
397
a57707d3
TO
398 if (isset($metadata['on_change'])) {
399 foreach ($metadata['on_change'] as $callback) {
400 call_user_func($callback, unserialize($dao->value), $value, $metadata);
401 }
402 }
403
6a488035
TO
404 if (CRM_Utils_System::isNull($value)) {
405 $dao->value = 'null';
406 }
407 else {
408 $dao->value = serialize($value);
409 }
410
411 $dao->created_date = date('Ymdhis');
412
413 if ($createdID) {
414 $dao->created_id = $createdID;
415 }
416 else {
417 $session = CRM_Core_Session::singleton();
418 $createdID = $session->get('userID');
419
420 if ($createdID) {
421 // ensure that this is a valid contact id (for session inconsistency rules)
422 $cid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
423 $createdID,
424 'id',
425 'id'
426 );
427 if ($cid) {
428 $dao->created_id = $session->get('userID');
429 }
430 }
431 }
432
433 $dao->save();
434 $dao->free();
435
436 // also save in cache if needed
437 $cacheKey = self::inCache($group, $name, $componentID, $contactID, FALSE, $domainID);
438 if ($cacheKey) {
439 self::$_cache[$cacheKey][$name] = $value;
440 }
441 }
442
443 /**
444 * Store multiple items in the setting table. Note that this will also store config keys
445 * the storage is determined by the metdata and is affected by
446 * 'name' setting's name
447 * 'prefetch' = store in config
448 * 'config_only' = don't store in settings
449 * 'config_key' = the config key is different to the settings key - e.g. debug where there was a conflict
450 * 'legacy_key' = rename from config or setting with this name
451 *
a57707d3
TO
452 * _setItem() is the common logic shared by setItem() and setItems().
453 *
6a0b768e
TO
454 * @param array $params
455 * (required) An api formatted array of keys and values.
2a6da8d7
EM
456 * @param null $domains
457 *
458 * @throws api_Exception
6a488035 459 * @domains array an array of domains to get settings for. Default is the current domain
3d0d359e 460 * @return array
6a488035 461 */
00be9182 462 public static function setItems(&$params, $domains = NULL) {
7583c3f3 463 $originalDomain = CRM_Core_Config::domainID();
6a488035 464 if (empty($domains)) {
7583c3f3 465 $domains[] = $originalDomain;
6a488035 466 }
7583c3f3 467 $reloadConfig = FALSE;
6a488035
TO
468 $fields = $config_keys = array();
469 $fieldsToSet = self::validateSettingsInput($params, $fields);
470
471 foreach ($fieldsToSet as $settingField => &$settingValue) {
472 self::validateSetting($settingValue, $fields['values'][$settingField]);
473 }
474
7583c3f3 475 foreach ($domains as $domainID) {
9b873358 476 if ($domainID != CRM_Core_Config::domainID()) {
7583c3f3 477 $reloadConfig = TRUE;
478 CRM_Core_BAO_Domain::setDomain($domainID);
479 }
480 $result[$domainID] = array();
6a488035 481 foreach ($fieldsToSet as $name => $value) {
9b873358 482 if (empty($fields['values'][$name]['config_only'])) {
a57707d3
TO
483 CRM_Core_BAO_Setting::_setItem(
484 $fields['values'][$name],
56cb3188
DL
485 $value,
486 $fields['values'][$name]['group_name'],
487 $name,
488 CRM_Utils_Array::value('component_id', $params),
489 CRM_Utils_Array::value('contact_id', $params),
490 CRM_Utils_Array::value('created_id', $params),
491 $domainID
492 );
6a488035 493 }
9b873358
TO
494 if (!empty($fields['values'][$name]['prefetch'])) {
495 if (!empty($fields['values'][$name]['config_key'])) {
6a488035
TO
496 $name = $fields['values'][$name]['config_key'];
497 }
498 $config_keys[$name] = $value;
499 }
7583c3f3 500 $result[$domainID][$name] = $value;
501 }
9b873358 502 if ($reloadConfig) {
7583c3f3 503 CRM_Core_Config::singleton($reloadConfig, $reloadConfig);
504 }
505
9b873358 506 if (!empty($config_keys)) {
7583c3f3 507 CRM_Core_BAO_ConfigSetting::create($config_keys);
508 }
9b873358 509 if ($reloadConfig) {
7583c3f3 510 CRM_Core_BAO_Domain::resetDomain();
6a488035 511 }
6a488035
TO
512 }
513
514 return $result;
515 }
516
517 /**
100fef9d 518 * Gets metadata about the settings fields (from getfields) based on the fields being passed in
6a488035
TO
519 *
520 * This function filters on the fields like 'version' & 'debug' that are not settings
77b97be7 521 *
6a0b768e
TO
522 * @param array $params
523 * Parameters as passed into API.
524 * @param array $fields
525 * Empty array to be populated with fields metadata.
6a488035
TO
526 * @param bool $createMode
527 *
77b97be7 528 * @throws api_Exception
a6c01b45
CW
529 * @return array
530 * name => value array of the fields to be set (with extraneous removed)
6a488035 531 */
00be9182 532 public static function validateSettingsInput($params, &$fields, $createMode = TRUE) {
6a488035
TO
533 $group = CRM_Utils_Array::value('group', $params);
534
535 $ignoredParams = array(
536 'version',
537 'id',
538 'domain_id',
539 'debug',
540 'created_id',
541 'component_id',
542 'contact_id',
543 'filters',
544 'entity_id',
545 'entity_table',
546 'sequential',
547 'api.has_parent',
f704dce7 548 'IDS_request_uri',
549 'IDS_user_agent',
550 'check_permissions',
80fbde47 551 'options',
e56fd67f 552 'prettyprint',
6a488035
TO
553 );
554 $settingParams = array_diff_key($params, array_fill_keys($ignoredParams, TRUE));
555 $getFieldsParams = array('version' => 3);
d3e86119 556 if (count($settingParams) == 1) {
6a488035
TO
557 // ie we are only setting one field - we'll pass it into getfields for efficiency
558 list($name) = array_keys($settingParams);
559 $getFieldsParams['name'] = $name;
560 }
353ffa53 561 $fields = civicrm_api3('setting', 'getfields', $getFieldsParams);
6a488035
TO
562 $invalidParams = (array_diff_key($settingParams, $fields['values']));
563 if (!empty($invalidParams)) {
e56fd67f 564 throw new api_Exception(implode(',', array_keys($invalidParams)) . " not valid settings");
6a488035
TO
565 }
566 if (!empty($settingParams)) {
567 $filteredFields = array_intersect_key($settingParams, $fields['values']);
568 }
569 else {
570 // no filters so we are interested in all for get mode. In create mode this means nothing to set
571 $filteredFields = $createMode ? array() : $fields['values'];
572 }
573 return $filteredFields;
574 }
575
576 /**
577 * Validate & convert settings input
578 *
579 * @value mixed value of the setting to be set
580 * @fieldSpec array Metadata for given field (drawn from the xml)
581 */
00be9182 582 public static function validateSetting(&$value, $fieldSpec) {
9b873358 583 if ($fieldSpec['type'] == 'String' && is_array($value)) {
353ffa53 584 $value = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $value) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
585 }
586 if (empty($fieldSpec['validate_callback'])) {
607cb45e 587 return TRUE;
6a488035
TO
588 }
589 else {
353ffa53
TO
590 list($class, $fn) = explode('::', $fieldSpec['validate_callback']);
591 if (!$class::$fn($value, $fieldSpec)) {
ee7b49c4 592 throw new api_Exception("validation failed for {$fieldSpec['name']} = $value based on callback {$fieldSpec['validate_callback']}");
6a488035
TO
593 }
594 }
595 }
596
597 /**
598 * Validate & convert settings input - translate True False to 0 or 1
599 *
600 * @value mixed value of the setting to be set
601 * @fieldSpec array Metadata for given field (drawn from the xml)
602 */
00be9182 603 public static function validateBoolSetting(&$value, $fieldSpec) {
6a488035 604 if (!CRM_Utils_Rule::boolean($value)) {
ee7b49c4 605 throw new api_Exception("Boolean value required for {$fieldSpec['name']}");
6a488035
TO
606 }
607 if (!$value) {
608 $value = 0;
609 }
610 else {
611 $value = 1;
612 }
613 return TRUE;
614 }
615
6a488035
TO
616 /**
617 * This provides information about the setting - similar to the fields concept for DAO information.
618 * As the setting is serialized code creating validation setting input needs to know the data type
619 * This also helps move information out of the form layer into the data layer where people can interact with
620 * it via the API or other mechanisms. In order to keep this consistent it is important the form layer
621 * also leverages it.
622 *
623 * Note that this function should never be called when using the runtime getvalue function. Caching works
624 * around the expectation it will be called during setting administration
625 *
626 * Function is intended for configuration rather than runtime access to settings
627 *
628 * The following params will filter the result. If none are passed all settings will be returns
629 *
6a0b768e
TO
630 * @param int $componentID
631 * Id of relevant component.
2a6da8d7 632 * @param array $filters
c490a46a 633 * @param int $domainID
2a6da8d7
EM
634 * @param null $profile
635 *
a6c01b45
CW
636 * @return array
637 * the following information as appropriate for each setting
5c766a0b
TO
638 * - name
639 * - type
640 * - default
641 * - add (CiviCRM version added)
642 * - is_domain
643 * - is_contact
644 * - description
645 * - help_text
6a488035 646 */
2da40d21 647 public static function getSettingSpecification(
607cb45e 648 $componentID = NULL,
b597d0b1 649 $filters = array(),
607cb45e
TO
650 $domainID = NULL,
651 $profile = NULL
b597d0b1 652 ) {
6a488035
TO
653 $cacheString = 'settingsMetadata_' . $domainID . '_' . $profile;
654 foreach ($filters as $filterField => $filterString) {
655 $cacheString .= "_{$filterField}_{$filterString}";
656 }
657 $cached = 1;
ee7b49c4
E
658 // the caching into 'All' seems to be a duplicate of caching to
659 // settingsMetadata__ - I think the reason was to cache all settings as defined & then those altered by a hook
6a488035
TO
660 $settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Specs', $cacheString, $componentID);
661 if ($settingsMetadata === NULL) {
662 $settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Spec', 'All', $componentID);
663 if (empty($settingsMetadata)) {
6a488035 664 global $civicrm_root;
86bfa4f6 665 $metaDataFolders = array($civicrm_root . '/settings');
6a488035 666 CRM_Utils_Hook::alterSettingsFolders($metaDataFolders);
3b998fcc 667 $settingsMetadata = self::loadSettingsMetaDataFolders($metaDataFolders);
353ffa53 668 CRM_Core_BAO_Cache::setItem($settingsMetadata, 'CiviCRM setting Spec', 'All', $componentID);
6a488035
TO
669 }
670 $cached = 0;
671 }
672
03d8f8f3 673 CRM_Utils_Hook::alterSettingsMetaData($settingsMetadata, $domainID, $profile);
6a488035 674 self::_filterSettingsSpecification($filters, $settingsMetadata);
03d8f8f3
DL
675
676 if (!$cached) {
677 // this is a bit 'heavy' if you are using hooks but this function
678 // is expected to only be called during setting administration
6a488035 679 // it should not be called by 'getvalue' or 'getitem
03d8f8f3
DL
680 CRM_Core_BAO_Cache::setItem(
681 $settingsMetadata,
682 'CiviCRM setting Specs',
683 $cacheString,
684 $componentID
685 );
6a488035
TO
686 }
687 return $settingsMetadata;
688
689 }
690
3b998fcc 691 /**
fe482240 692 * Load the settings files defined in a series of folders.
6a0b768e
TO
693 * @param array $metaDataFolders
694 * List of folder paths.
3b998fcc
TO
695 * @return array
696 */
697 public static function loadSettingsMetaDataFolders($metaDataFolders) {
698 $settingsMetadata = array();
699 $loadedFolders = array();
700 foreach ($metaDataFolders as $metaDataFolder) {
701 $realFolder = realpath($metaDataFolder);
702 if (is_dir($realFolder) && !isset($loadedFolders[$realFolder])) {
703 $loadedFolders[$realFolder] = TRUE;
704 $settingsMetadata = $settingsMetadata + self::loadSettingsMetaData($metaDataFolder);
705 }
706 }
707 return $settingsMetadata;
708 }
709
6a488035 710 /**
fe482240 711 * Load up settings metadata from files.
6a488035 712 */
00be9182 713 public static function loadSettingsMetadata($metaDataFolder) {
6a488035
TO
714 $settingMetaData = array();
715 $settingsFiles = CRM_Utils_File::findFiles($metaDataFolder, '*.setting.php');
716 foreach ($settingsFiles as $file) {
717 $settings = include $file;
718 $settingMetaData = array_merge($settingMetaData, $settings);
719 }
353ffa53 720 CRM_Core_BAO_Cache::setItem($settingMetaData, 'CiviCRM setting Spec', 'All');
6a488035
TO
721 return $settingMetaData;
722 }
723
724 /**
725 * Filter the settings metadata according to filters passed in. This is a convenience filter
726 * and allows selective reverting / filling of settings
727 *
6a0b768e
TO
728 * @param array $filters
729 * Filters to match against data.
730 * @param array $settingSpec
731 * Metadata to filter.
6a488035 732 */
00be9182 733 public static function _filterSettingsSpecification($filters, &$settingSpec) {
6a488035
TO
734 if (empty($filters)) {
735 return;
736 }
4c9b6178 737 elseif (array_keys($filters) == array('name')) {
9caace17 738 $settingSpec = array($filters['name'] => CRM_Utils_Array::value($filters['name'], $settingSpec, ''));
6a488035
TO
739 return;
740 }
741 else {
742 foreach ($settingSpec as $field => $fieldValues) {
743 if (array_intersect_assoc($fieldValues, $filters) != $filters) {
744 unset($settingSpec[$field]);
745 }
746 }
747 return;
748 }
749 }
750
751 /**
0880a9d0 752 * Look for any missing settings and convert them from config or load default as appropriate.
6a488035
TO
753 * This should be run from GenCode & also from upgrades to add any new defaults.
754 *
755 * Multisites have often been overlooked in upgrade scripts so can be expected to be missing
756 * a number of settings
757 */
00be9182 758 public static function updateSettingsFromMetaData() {
6a488035
TO
759 $apiParams = array(
760 'version' => 3,
761 'domain_id' => 'all',
eb40b5a4 762 'filters' => array('prefetch' => 0),
6a488035
TO
763 );
764 $existing = civicrm_api('setting', 'get', $apiParams);
eb40b5a4 765
6a488035
TO
766 if (!empty($existing['values'])) {
767 $allSettings = civicrm_api('setting', 'getfields', array('version' => 3));
768 foreach ($existing['values'] as $domainID => $domainSettings) {
769 CRM_Core_BAO_Domain::setDomain($domainID);
770 $missing = array_diff_key($allSettings['values'], $domainSettings);
771 foreach ($missing as $name => $settings) {
772 self::convertConfigToSetting($name, $domainID);
773 }
774 CRM_Core_BAO_Domain::resetDomain();
775 }
776 }
777 }
778
779 /**
100fef9d 780 * Move an item from being in the config array to being stored as a setting
6a488035
TO
781 * remove from config - as appropriate based on metadata
782 *
783 * Note that where the key name is being changed the 'legacy_key' will give us the old name
784 */
00be9182 785 public static function convertConfigToSetting($name, $domainID = NULL) {
eb40b5a4 786 // we have to force this here in case more than one domain is in play.
787 // whenever there is a possibility of more than one domain we must force it
6a488035
TO
788 $config = CRM_Core_Config::singleton();
789 if (empty($domainID)) {
d3e86119 790 $domainID = CRM_Core_Config::domainID();
6a488035
TO
791 }
792 $domain = new CRM_Core_DAO_Domain();
793 $domain->id = $domainID;
794 $domain->find(TRUE);
795 if ($domain->config_backend) {
796 $values = unserialize($domain->config_backend);
0db6c3e1
TO
797 }
798 else {
6a488035
TO
799 $values = array();
800 }
607cb45e 801 $spec = self::getSettingSpecification(NULL, array('name' => $name), $domainID);
6a488035
TO
802 $configKey = CRM_Utils_Array::value('config_key', $spec[$name], CRM_Utils_Array::value('legacy_key', $spec[$name], $name));
803 //if the key is set to config_only we don't need to do anything
9b873358 804 if (empty($spec[$name]['config_only'])) {
6a488035
TO
805 if (!empty($values[$configKey])) {
806 civicrm_api('setting', 'create', array('version' => 3, $name => $values[$configKey], 'domain_id' => $domainID));
807 }
808 else {
809 civicrm_api('setting', 'fill', array('version' => 3, 'name' => $name, 'domain_id' => $domainID));
810 }
811
812 if (empty($spec[$name]['prefetch']) && !empty($values[$configKey])) {
813 unset($values[$configKey]);
814 $domain->config_backend = serialize($values);
815 $domain->save();
816 unset($config->$configKey);
817 }
818 }
819 }
820
b5c2afd0
EM
821 /**
822 * @param $group
100fef9d 823 * @param string $name
b5c2afd0 824 * @param bool $system
100fef9d 825 * @param int $userID
b5c2afd0
EM
826 * @param bool $localize
827 * @param string $returnField
828 * @param bool $returnNameANDLabels
829 * @param null $condition
830 *
831 * @return array
832 */
2da40d21 833 public static function valueOptions(
f9f40af3 834 $group,
6a488035 835 $name,
242bd179
TO
836 $system = TRUE,
837 $userID = NULL,
838 $localize = FALSE,
839 $returnField = 'name',
6a488035 840 $returnNameANDLabels = FALSE,
242bd179 841 $condition = NULL
6a488035
TO
842 ) {
843 $optionValue = self::getItem($group, $name);
844
845 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, $returnField);
846
847 //enabled name => label require for new contact edit form, CRM-4605
848 if ($returnNameANDLabels) {
849 $names = $labels = $nameAndLabels = array();
850 if ($returnField == 'name') {
851 $names = $groupValues;
852 $labels = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'label');
853 }
854 else {
855 $labels = $groupValues;
856 $names = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'name');
857 }
858 }
859
860 $returnValues = array();
861 foreach ($groupValues as $gn => $gv) {
862 $returnValues[$gv] = 0;
863 }
864
865 if ($optionValue && !empty($groupValues)) {
866 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
867 substr($optionValue, 1, -1)
868 );
869
870 if (!empty($dbValues)) {
871 foreach ($groupValues as $key => $val) {
872 if (in_array($key, $dbValues)) {
873 $returnValues[$val] = 1;
874 if ($returnNameANDLabels) {
875 $nameAndLabels[$names[$key]] = $labels[$key];
876 }
877 }
878 }
879 }
880 }
881 return ($returnNameANDLabels) ? $nameAndLabels : $returnValues;
882 }
883
b5c2afd0
EM
884 /**
885 * @param $group
100fef9d 886 * @param string $name
b5c2afd0
EM
887 * @param $value
888 * @param bool $system
100fef9d 889 * @param int $userID
b5c2afd0
EM
890 * @param string $keyField
891 */
2da40d21 892 public static function setValueOption(
f9f40af3 893 $group,
6a488035
TO
894 $name,
895 $value,
242bd179
TO
896 $system = TRUE,
897 $userID = NULL,
6a488035
TO
898 $keyField = 'name'
899 ) {
900 if (empty($value)) {
901 $optionValue = NULL;
902 }
903 elseif (is_array($value)) {
904 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
905
906 $cbValues = array();
907 foreach ($groupValues as $key => $val) {
a7488080 908 if (!empty($value[$val])) {
6a488035
TO
909 $cbValues[$key] = 1;
910 }
911 }
912
913 if (!empty($cbValues)) {
914 $optionValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
353ffa53
TO
915 array_keys($cbValues)
916 ) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
917 }
918 else {
919 $optionValue = NULL;
920 }
921 }
922 else {
923 $optionValue = $value;
924 }
925
926 self::setItem($optionValue, $group, $name);
927 }
928
b5c2afd0 929 /**
c490a46a 930 * @param array $params
100fef9d 931 * @param int $domainID
b5c2afd0 932 */
00be9182 933 public static function fixAndStoreDirAndURL(&$params, $domainID = NULL) {
2c7039ef
DS
934 if (self::isUpgradeFromPreFourOneAlpha1()) {
935 return;
936 }
937
6a488035
TO
938 if (empty($domainID)) {
939 $domainID = CRM_Core_Config::domainID();
940 }
941 $sql = "
942 SELECT name, group_name
943 FROM civicrm_setting
944 WHERE domain_id = %1
945 AND ( group_name = %2
946 OR group_name = %3 )
947";
948 $sqlParams = array(
949 1 => array($domainID, 'Integer'),
950 2 => array(self::DIRECTORY_PREFERENCES_NAME, 'String'),
951 3 => array(self::URL_PREFERENCES_NAME, 'String'),
952 );
953
954 $dirParams = array();
955 $urlParams = array();
956
957 $dao = CRM_Core_DAO::executeQuery($sql,
958 $sqlParams,
959 TRUE,
960 NULL,
961 FALSE,
962 TRUE,
963 // trap exceptions as error
964 TRUE
965 );
966
967 if (is_a($dao, 'DB_Error')) {
968 if (CRM_Core_Config::isUpgradeMode()) {
969 // seems like this is a 4.0 -> 4.1 upgrade, so we suppress this error and continue
970 return;
971 }
972 else {
973 echo "Fatal DB error, exiting, seems like your schema does not have civicrm_setting table\n";
974 exit();
975 }
976 }
977
978 while ($dao->fetch()) {
979 if (!isset($params[$dao->name])) {
980 continue;
981 }
982 if ($dao->group_name == self::DIRECTORY_PREFERENCES_NAME) {
983 $dirParams[$dao->name] = CRM_Utils_Array::value($dao->name, $params, '');
984 }
985 else {
986 $urlParams[$dao->name] = CRM_Utils_Array::value($dao->name, $params, '');
987 }
988 unset($params[$dao->name]);
989 }
990
991 if (!empty($dirParams)) {
992 self::storeDirectoryOrURLPreferences($dirParams,
993 self::DIRECTORY_PREFERENCES_NAME
994 );
995 }
996
997 if (!empty($urlParams)) {
998 self::storeDirectoryOrURLPreferences($urlParams,
999 self::URL_PREFERENCES_NAME
1000 );
1001 }
1002 }
1003
b5c2afd0 1004 /**
c490a46a 1005 * @param array $params
b5c2afd0
EM
1006 * @param $group
1007 */
00be9182 1008 public static function storeDirectoryOrURLPreferences(&$params, $group) {
6a488035
TO
1009 foreach ($params as $name => $value) {
1010 // always try to store relative directory or url from CMS root
1011 $value = ($group == self::DIRECTORY_PREFERENCES_NAME) ? CRM_Utils_File::relativeDirectory($value) : CRM_Utils_System::relativeURL($value);
1012
1013 self::setItem($value, $group, $name);
1014 }
1015 }
1016
b5c2afd0 1017 /**
c490a46a 1018 * @param array $params
b5c2afd0
EM
1019 * @param bool $setInConfig
1020 */
00be9182 1021 public static function retrieveDirectoryAndURLPreferences(&$params, $setInConfig = FALSE) {
2c7039ef
DS
1022 if (CRM_Core_Config::isUpgradeMode()) {
1023 $isJoomla = (defined('CIVICRM_UF') && CIVICRM_UF == 'Joomla') ? TRUE : FALSE;
1024 // hack to set the resource base url so that js/ css etc is loaded correctly
1025 if ($isJoomla) {
1026 $params['userFrameworkResourceURL'] = CRM_Utils_File::addTrailingSlash(CIVICRM_UF_BASEURL, '/') . str_replace('administrator', '', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'userFrameworkResourceURL', 'value', 'name'));
1027 }
1028 if (self::isUpgradeFromPreFourOneAlpha1()) {
1029 return;
1030 }
1031 }
1032
6a488035
TO
1033 if ($setInConfig) {
1034 $config = CRM_Core_Config::singleton();
1035 }
1036
6a488035
TO
1037 $sql = "
1038SELECT name, group_name, value
1039FROM civicrm_setting
1040WHERE ( group_name = %1
1041OR group_name = %2 )
1042AND domain_id = %3
1043";
6ea503d4
TO
1044 $sqlParams = array(
1045 1 => array(self::DIRECTORY_PREFERENCES_NAME, 'String'),
6a488035
TO
1046 2 => array(self::URL_PREFERENCES_NAME, 'String'),
1047 3 => array(CRM_Core_Config::domainID(), 'Integer'),
1048 );
1049
1050 $dao = CRM_Core_DAO::executeQuery($sql,
1051 $sqlParams,
1052 TRUE,
1053 NULL,
1054 FALSE,
1055 TRUE,
1056 // trap exceptions as error
1057 TRUE
1058 );
1059
1060 if (is_a($dao, 'DB_Error')) {
2c7039ef
DS
1061 echo "Fatal DB error, exiting, seems like your schema does not have civicrm_setting table\n";
1062 exit();
6a488035
TO
1063 }
1064
1065 while ($dao->fetch()) {
1066 $value = self::getOverride($dao->group_name, $dao->name, NULL);
1067 if ($value === NULL && $dao->value) {
1068 $value = unserialize($dao->value);
1069 if ($dao->group_name == self::DIRECTORY_PREFERENCES_NAME) {
1070 $value = CRM_Utils_File::absoluteDirectory($value);
1071 }
1072 else {
1073 // CRM-7622: we need to remove the language part
1074 $value = CRM_Utils_System::absoluteURL($value, TRUE);
1075 }
1076 }
1077 // CRM-10931, If DB doesn't have any value, carry on with any default value thats already available
8cc574cf 1078 if (!isset($value) && !empty($params[$dao->name])) {
6a488035
TO
1079 $value = $params[$dao->name];
1080 }
1081 $params[$dao->name] = $value;
1082
1083 if ($setInConfig) {
1084 $config->{$dao->name} = $value;
1085 }
1086 }
1087 }
1088
1089 /**
1090 * Determine what, if any, overrides have been provided
1091 * for a setting.
1092 *
dd244018 1093 * @param $group
100fef9d 1094 * @param string $name
dd244018
EM
1095 * @param $default
1096 *
6a488035
TO
1097 * @return mixed, NULL or an overriden value
1098 */
1099 protected static function getOverride($group, $name, $default) {
1100 global $civicrm_setting;
1101 if ($group && $name && isset($civicrm_setting[$group][$name])) {
1102 return $civicrm_setting[$group][$name];
1103 }
1104 else {
1105 return $default;
1106 }
1107 }
6a488035 1108
2c7039ef 1109 /**
100fef9d 1110 * Civicrm_setting didn't exist before 4.1.alpha1 and this function helps taking decisions during upgrade
2c7039ef 1111 *
5c766a0b 1112 * @return bool
2c7039ef 1113 */
00be9182 1114 public static function isUpgradeFromPreFourOneAlpha1() {
2c7039ef
DS
1115 if (CRM_Core_Config::isUpgradeMode()) {
1116 $currentVer = CRM_Core_BAO_Domain::version();
1117 if (version_compare($currentVer, '4.1.alpha1') < 0) {
1118 return TRUE;
1119 }
1120 }
1121 return FALSE;
1122 }
96025800 1123
2c7039ef 1124}