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