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