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