Merge pull request #107 from dlobo/CRM-12080
[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($componentID = null, $filters = array(), $domainID = null, $profile = null) {
528
529 $cacheString = 'settingsMetadata_' . $domainID . '_' . $profile;
530 foreach ($filters as $filterField => $filterString) {
531 $cacheString .= "_{$filterField}_{$filterString}";
532 }
533 $cached = 1;
534 $settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Specs', $cacheString, $componentID);
535 if ($settingsMetadata === NULL) {
536 $settingsMetadata = CRM_Core_BAO_Cache::getItem('CiviCRM setting Spec', 'All', $componentID);
537 if (empty($settingsMetadata)) {
538 $settingsMetadata = array();
539 global $civicrm_root;
540 $metaDataFolders = array($civicrm_root. '/settings');
541 CRM_Utils_Hook::alterSettingsFolders($metaDataFolders);
542 foreach ($metaDataFolders as $metaDataFolder) {
543 $settingsMetadata = $settingsMetadata + self::loadSettingsMetaData($metaDataFolder);
544 }
545 CRM_Core_BAO_Cache::setItem($settingsMetadata,'CiviCRM setting Spec', 'All', $componentID);
546 }
547 $cached = 0;
548 }
549
550 $hookCacheString = CRM_Utils_Hook::alterSettingsMetaData($settingsMetadata, $domainID, $profile);
551 self::_filterSettingsSpecification($filters, $settingsMetadata);
552 if(!$cached || !empty($hookCacheString)){
553 // this is a bit 'heavy' if you are using hooks but this function is expected to only be called during setting administration
554 // it should not be called by 'getvalue' or 'getitem
555 CRM_Core_BAO_Cache::setItem($settingsMetadata,'CiviCRM setting Specs', $cacheString . $hookCacheString, $componentID);
556 }
557 return $settingsMetadata;
558
559 }
560
561 /**
562 * Load up settings metadata from files
563 */
564 static function loadSettingsMetadata($metaDataFolder) {
565 $settingMetaData = array();
566 $settingsFiles = CRM_Utils_File::findFiles($metaDataFolder, '*.setting.php');
567 foreach ($settingsFiles as $file) {
568 $settings = include $file;
569 $settingMetaData = array_merge($settingMetaData, $settings);
570 }
571 CRM_Core_BAO_Cache::setItem($settingMetaData,'CiviCRM setting Spec', 'All');
572 return $settingMetaData;
573 }
574
575 /**
576 * Filter the settings metadata according to filters passed in. This is a convenience filter
577 * and allows selective reverting / filling of settings
578 *
579 * @param array $filters Filters to match against data
580 * @param array $settingSpec metadata to filter
581 */
582 static function _filterSettingsSpecification($filters, &$settingSpec) {
583 if (empty($filters)) {
584 return;
585 }
586 else if (array_keys($filters) == array('name')) {
587 $settingSpec = array($filters['name'] => $settingSpec[$filters['name']]);
588 return;
589 }
590 else {
591 foreach ($settingSpec as $field => $fieldValues) {
592 if (array_intersect_assoc($fieldValues, $filters) != $filters) {
593 unset($settingSpec[$field]);
594 }
595 }
596 return;
597 }
598 }
599
600 /**
601 * Look for any missing settings and convert them from config or load default as appropriate
602 * This should be run from GenCode & also from upgrades to add any new defaults.
603 *
604 * Multisites have often been overlooked in upgrade scripts so can be expected to be missing
605 * a number of settings
606 */
607 static function updateSettingsFromMetaData() {
608 $apiParams = array(
609 'version' => 3,
610 'domain_id' => 'all',
611 );
612 $existing = civicrm_api('setting', 'get', $apiParams);
613 if (!empty($existing['values'])) {
614 $allSettings = civicrm_api('setting', 'getfields', array('version' => 3));
615 foreach ($existing['values'] as $domainID => $domainSettings) {
616 CRM_Core_BAO_Domain::setDomain($domainID);
617 $missing = array_diff_key($allSettings['values'], $domainSettings);
618 foreach ($missing as $name => $settings) {
619 self::convertConfigToSetting($name, $domainID);
620 }
621 CRM_Core_BAO_Domain::resetDomain();
622 }
623 }
624 }
625
626 /**
627 * move an item from being in the config array to being stored as a setting
628 * remove from config - as appropriate based on metadata
629 *
630 * Note that where the key name is being changed the 'legacy_key' will give us the old name
631 */
632 static function convertConfigToSetting($name, $domainID = null) {
633 $config = CRM_Core_Config::singleton();
634 if (empty($domainID)) {
635 $domainID= CRM_Core_Config::domainID();
636 }
637 $domain = new CRM_Core_DAO_Domain();
638 $domain->id = $domainID;
639 $domain->find(TRUE);
640 if ($domain->config_backend) {
641 $values = unserialize($domain->config_backend);
642 } else {
643 $values = array();
644 }
645 $spec = self::getSettingSpecification(null, array('name' => $name), $domainID);
646 $configKey = CRM_Utils_Array::value('config_key', $spec[$name], CRM_Utils_Array::value('legacy_key', $spec[$name], $name));
647 //if the key is set to config_only we don't need to do anything
648 if(empty($spec[$name]['config_only'])){
649 if (!empty($values[$configKey])) {
650 civicrm_api('setting', 'create', array('version' => 3, $name => $values[$configKey], 'domain_id' => $domainID));
651 }
652 else {
653 civicrm_api('setting', 'fill', array('version' => 3, 'name' => $name, 'domain_id' => $domainID));
654 }
655
656 if (empty($spec[$name]['prefetch']) && !empty($values[$configKey])) {
657 unset($values[$configKey]);
658 $domain->config_backend = serialize($values);
659 $domain->save();
660 unset($config->$configKey);
661 }
662 }
663 }
664
665 static function valueOptions($group,
666 $name,
667 $system = TRUE,
668 $userID = NULL,
669 $localize = FALSE,
670 $returnField = 'name',
671 $returnNameANDLabels = FALSE,
672 $condition = NULL
673 ) {
674 $optionValue = self::getItem($group, $name);
675
676 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, $returnField);
677
678 //enabled name => label require for new contact edit form, CRM-4605
679 if ($returnNameANDLabels) {
680 $names = $labels = $nameAndLabels = array();
681 if ($returnField == 'name') {
682 $names = $groupValues;
683 $labels = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'label');
684 }
685 else {
686 $labels = $groupValues;
687 $names = CRM_Core_OptionGroup::values($name, FALSE, FALSE, $localize, $condition, 'name');
688 }
689 }
690
691 $returnValues = array();
692 foreach ($groupValues as $gn => $gv) {
693 $returnValues[$gv] = 0;
694 }
695
696 if ($optionValue && !empty($groupValues)) {
697 $dbValues = explode(CRM_Core_DAO::VALUE_SEPARATOR,
698 substr($optionValue, 1, -1)
699 );
700
701 if (!empty($dbValues)) {
702 foreach ($groupValues as $key => $val) {
703 if (in_array($key, $dbValues)) {
704 $returnValues[$val] = 1;
705 if ($returnNameANDLabels) {
706 $nameAndLabels[$names[$key]] = $labels[$key];
707 }
708 }
709 }
710 }
711 }
712 return ($returnNameANDLabels) ? $nameAndLabels : $returnValues;
713 }
714
715 static function setValueOption($group,
716 $name,
717 $value,
718 $system = TRUE,
719 $userID = NULL,
720 $keyField = 'name'
721 ) {
722 if (empty($value)) {
723 $optionValue = NULL;
724 }
725 elseif (is_array($value)) {
726 $groupValues = CRM_Core_OptionGroup::values($name, FALSE, FALSE, FALSE, NULL, $keyField);
727
728 $cbValues = array();
729 foreach ($groupValues as $key => $val) {
730 if (CRM_Utils_Array::value($val, $value)) {
731 $cbValues[$key] = 1;
732 }
733 }
734
735 if (!empty($cbValues)) {
736 $optionValue = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
737 array_keys($cbValues)
738 ) . CRM_Core_DAO::VALUE_SEPARATOR;
739 }
740 else {
741 $optionValue = NULL;
742 }
743 }
744 else {
745 $optionValue = $value;
746 }
747
748 self::setItem($optionValue, $group, $name);
749 }
750
751 static function fixAndStoreDirAndURL(&$params, $domainID = null) {
752 if (empty($domainID)) {
753 $domainID = CRM_Core_Config::domainID();
754 }
755 $sql = "
756 SELECT name, group_name
757 FROM civicrm_setting
758 WHERE domain_id = %1
759 AND ( group_name = %2
760 OR group_name = %3 )
761 ";
762 $sqlParams = array(
763 1 => array($domainID, 'Integer'),
764 2 => array(self::DIRECTORY_PREFERENCES_NAME, 'String'),
765 3 => array(self::URL_PREFERENCES_NAME, 'String'),
766 );
767
768 $dirParams = array();
769 $urlParams = array();
770
771 $dao = CRM_Core_DAO::executeQuery($sql,
772 $sqlParams,
773 TRUE,
774 NULL,
775 FALSE,
776 TRUE,
777 // trap exceptions as error
778 TRUE
779 );
780
781 if (is_a($dao, 'DB_Error')) {
782 if (CRM_Core_Config::isUpgradeMode()) {
783 // seems like this is a 4.0 -> 4.1 upgrade, so we suppress this error and continue
784 return;
785 }
786 else {
787 echo "Fatal DB error, exiting, seems like your schema does not have civicrm_setting table\n";
788 exit();
789 }
790 }
791
792 while ($dao->fetch()) {
793 if (!isset($params[$dao->name])) {
794 continue;
795 }
796 if ($dao->group_name == self::DIRECTORY_PREFERENCES_NAME) {
797 $dirParams[$dao->name] = CRM_Utils_Array::value($dao->name, $params, '');
798 }
799 else {
800 $urlParams[$dao->name] = CRM_Utils_Array::value($dao->name, $params, '');
801 }
802 unset($params[$dao->name]);
803 }
804
805 if (!empty($dirParams)) {
806 self::storeDirectoryOrURLPreferences($dirParams,
807 self::DIRECTORY_PREFERENCES_NAME
808 );
809 }
810
811 if (!empty($urlParams)) {
812 self::storeDirectoryOrURLPreferences($urlParams,
813 self::URL_PREFERENCES_NAME
814 );
815 }
816 }
817
818 static function storeDirectoryOrURLPreferences(&$params, $group) {
819 foreach ($params as $name => $value) {
820 // always try to store relative directory or url from CMS root
821 $value = ($group == self::DIRECTORY_PREFERENCES_NAME) ? CRM_Utils_File::relativeDirectory($value) : CRM_Utils_System::relativeURL($value);
822
823 self::setItem($value, $group, $name);
824 }
825 }
826
827 static function retrieveDirectoryAndURLPreferences(&$params, $setInConfig = FALSE) {
828 if ($setInConfig) {
829 $config = CRM_Core_Config::singleton();
830 }
831
832 $isJoomla = (defined('CIVICRM_UF') && CIVICRM_UF == 'Joomla') ? TRUE : FALSE;
833
834 if (CRM_Core_Config::isUpgradeMode() && !$isJoomla) {
835 $currentVer = CRM_Core_BAO_Domain::version();
836 if (version_compare($currentVer, '4.1.alpha1') < 0) {
837 return;
838 }
839 }
840 $sql = "
841 SELECT name, group_name, value
842 FROM civicrm_setting
843 WHERE ( group_name = %1
844 OR group_name = %2 )
845 AND domain_id = %3
846 ";
847 $sqlParams = array(1 => array(self::DIRECTORY_PREFERENCES_NAME, 'String'),
848 2 => array(self::URL_PREFERENCES_NAME, 'String'),
849 3 => array(CRM_Core_Config::domainID(), 'Integer'),
850 );
851
852 $dao = CRM_Core_DAO::executeQuery($sql,
853 $sqlParams,
854 TRUE,
855 NULL,
856 FALSE,
857 TRUE,
858 // trap exceptions as error
859 TRUE
860 );
861
862 if (is_a($dao, 'DB_Error')) {
863 if (CRM_Core_Config::isUpgradeMode()) {
864 // seems like this is a 4.0 -> 4.1 upgrade, so we suppress this error and continue
865 // hack to set the resource base url so that js/ css etc is loaded correctly
866 if ($isJoomla) {
867 $params['userFrameworkResourceURL'] = CRM_Utils_File::addTrailingSlash(CIVICRM_UF_BASEURL, '/') . str_replace('administrator', '', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'userFrameworkResourceURL', 'value', 'name'));
868 }
869 return;
870 }
871 else {
872 echo "Fatal DB error, exiting, seems like your schema does not have civicrm_setting table\n";
873 exit();
874 }
875 }
876
877 while ($dao->fetch()) {
878 $value = self::getOverride($dao->group_name, $dao->name, NULL);
879 if ($value === NULL && $dao->value) {
880 $value = unserialize($dao->value);
881 if ($dao->group_name == self::DIRECTORY_PREFERENCES_NAME) {
882 $value = CRM_Utils_File::absoluteDirectory($value);
883 }
884 else {
885 // CRM-7622: we need to remove the language part
886 $value = CRM_Utils_System::absoluteURL($value, TRUE);
887 }
888 }
889 // CRM-10931, If DB doesn't have any value, carry on with any default value thats already available
890 if (!isset($value) && CRM_Utils_Array::value($dao->name, $params)) {
891 $value = $params[$dao->name];
892 }
893 $params[$dao->name] = $value;
894
895 if ($setInConfig) {
896 $config->{$dao->name} = $value;
897 }
898 }
899 }
900
901 /**
902 * Determine what, if any, overrides have been provided
903 * for a setting.
904 *
905 * @return mixed, NULL or an overriden value
906 */
907 protected static function getOverride($group, $name, $default) {
908 global $civicrm_setting;
909 if ($group && $name && isset($civicrm_setting[$group][$name])) {
910 return $civicrm_setting[$group][$name];
911 }
912 else {
913 return $default;
914 }
915 }
916 }
917