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