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