Merge remote-tracking branch 'upstream/4.3' into 4.3-master-2013-05-01-14-11-47
[civicrm-core.git] / CRM / Core / BAO / ConfigSetting.php
CommitLineData
6a488035
TO
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 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2013
33 * $Id$
34 *
35 */
36
37/**
38 * file contains functions used in civicrm configuration
39 *
40 */
41class CRM_Core_BAO_ConfigSetting {
42
43 /**
b597d0b1
DL
44 * Function to create civicrm settings. This is the same as add but it clears the cache and
45 * reloads the config object
6a488035
TO
46 *
47 * @params array $params associated array of civicrm variables
48 *
49 * @return null
50 * @static
51 */
52 static function create($params) {
53 self::add($params);
54 $cache = CRM_Utils_Cache::singleton();
55 $cache->delete('CRM_Core_Config');
0e04f44e 56 $cache->delete('CRM_Core_Config' . CRM_Core_Config::domainID());
6a488035
TO
57 $config = CRM_Core_Config::singleton(TRUE, TRUE);
58 }
59
60 /**
61 * Function to add civicrm settings
62 *
63 * @params array $params associated array of civicrm variables
64 *
65 * @return null
66 * @static
67 */
68 static function add(&$params) {
69 self::fixParams($params);
70
71 // also set a template url so js files can use this
72 // CRM-6194
73 $params['civiRelativeURL'] = CRM_Utils_System::url('CIVI_BASE_TEMPLATE');
b597d0b1
DL
74 $params['civiRelativeURL'] =
75 str_replace(
76 'CIVI_BASE_TEMPLATE',
77 '',
6a488035
TO
78 $params['civiRelativeURL']
79 );
80
b597d0b1
DL
81 // also add the version number for use by template / js etc
82 $params['civiVersion'] = CRM_Utils_System::version();
83
6a488035
TO
84 $domain = new CRM_Core_DAO_Domain();
85 $domain->id = CRM_Core_Config::domainID();
86 $domain->find(TRUE);
87 if ($domain->config_backend) {
88 $values = unserialize($domain->config_backend);
89 self::formatParams($params, $values);
90 }
91
92 // CRM-6151
93 if (isset($params['localeCustomStrings']) &&
94 is_array($params['localeCustomStrings'])
95 ) {
96 $domain->locale_custom_strings = serialize($params['localeCustomStrings']);
97 }
98
99 // unset any of the variables we read from file that should not be stored in the database
100 // the username and certpath are stored flat with _test and _live
101 // check CRM-1470
102 $skipVars = self::skipVars();
103 foreach ($skipVars as $var) {
104 unset($params[$var]);
105 }
106
107 CRM_Core_BAO_Setting::fixAndStoreDirAndURL($params);
108
109 // also skip all Dir Params, we dont need to store those in the DB!
110 foreach ($params as $name => $val) {
111 if (substr($name, -3) == 'Dir') {
112 unset($params[$name]);
113 }
114 }
115
116 //keep user preferred language upto date, CRM-7746
117 $session = CRM_Core_Session::singleton();
118 $lcMessages = CRM_Utils_Array::value('lcMessages', $params);
119 if ($lcMessages && $session->get('userID')) {
120 $languageLimit = CRM_Utils_Array::value('languageLimit', $params);
121 if (is_array($languageLimit) &&
122 !in_array($lcMessages, array_keys($languageLimit))
123 ) {
124 $lcMessages = $session->get('lcMessages');
125 }
126
127 $ufm = new CRM_Core_DAO_UFMatch();
128 $ufm->contact_id = $session->get('userID');
129 if ($lcMessages && $ufm->find(TRUE)) {
130 $ufm->language = $lcMessages;
131 $ufm->save();
132 $session->set('lcMessages', $lcMessages);
133 $params['lcMessages'] = $lcMessages;
134 }
135 }
136
137 $domain->config_backend = serialize($params);
138 $domain->save();
139 }
140
141 /**
142 * Function to fix civicrm setting variables
143 *
144 * @params array $params associated array of civicrm variables
145 *
146 * @return null
147 * @static
148 */
149 static function fixParams(&$params) {
150 // in our old civicrm.settings.php we were using ISO code for country and
151 // province limit, now we have changed it to use ids
152
153 $countryIsoCodes = CRM_Core_PseudoConstant::countryIsoCode();
154
155 $specialArray = array('countryLimit', 'provinceLimit');
156
157 foreach ($params as $key => $value) {
158 if (in_array($key, $specialArray) && is_array($value)) {
159 foreach ($value as $k => $val) {
160 if (!is_numeric($val)) {
161 $params[$key][$k] = array_search($val, $countryIsoCodes);
162 }
163 }
164 }
165 elseif ($key == 'defaultContactCountry') {
166 if (!is_numeric($value)) {
167 $params[$key] = array_search($value, $countryIsoCodes);
168 }
169 }
170 }
171 }
172
173 /**
174 * Function to format the array containing before inserting in db
175 *
176 * @param array $params associated array of civicrm variables(submitted)
177 * @param array $values associated array of civicrm variables stored in db
178 *
179 * @return null
180 * @static
181 */
182 static function formatParams(&$params, &$values) {
183 if (empty($params) ||
184 !is_array($params)
185 ) {
186 $params = $values;
187 }
188 else {
189 foreach ($params as $key => $val) {
190 if (array_key_exists($key, $values)) {
191 unset($values[$key]);
192 }
193 }
194 $params = array_merge($params, $values);
195 }
196 }
197
198 /**
199 * Function to retrieve the settings values from db
200 *
201 * @return array $defaults
202 * @static
203 */
204 static function retrieve(&$defaults) {
205 $domain = new CRM_Core_DAO_Domain();
206
207 //we are initializing config, really can't use, CRM-7863
208 $urlVar = 'q';
209 if (defined('CIVICRM_UF') && CIVICRM_UF == 'Joomla') {
210 $urlVar = 'task';
211 }
212
213 if (CRM_Core_Config::isUpgradeMode()) {
214 $domain->selectAdd('config_backend');
215 }
216 elseif (CRM_Utils_Array::value($urlVar, $_GET) == 'admin/modules/list/confirm') {
217 $domain->selectAdd('config_backend', 'locales');
218 }
219 else {
220 $domain->selectAdd('config_backend, locales, locale_custom_strings');
221 }
222
223 $domain->id = CRM_Core_Config::domainID();
224 $domain->find(TRUE);
225 if ($domain->config_backend) {
226 $defaults = unserialize($domain->config_backend);
227 if ($defaults === FALSE || !is_array($defaults)) {
228 $defaults = array();
229 return;
230 }
231
232 $skipVars = self::skipVars();
233 foreach ($skipVars as $skip) {
234 if (array_key_exists($skip, $defaults)) {
235 unset($defaults[$skip]);
236 }
237 }
238
239 // since language field won't be present before upgrade.
240 if (CRM_Core_Config::isUpgradeMode()) {
241 // dont add if its empty
242 if (!empty($defaults)) {
243 // retrieve directory and url preferences also
244 CRM_Core_BAO_Setting::retrieveDirectoryAndURLPreferences($defaults);
245 }
246 return;
247 }
248
249 // check if there are any locale strings
250 if ($domain->locale_custom_strings) {
251 $defaults['localeCustomStrings'] = unserialize($domain->locale_custom_strings);
252 }
253 else {
254 $defaults['localeCustomStrings'] = NULL;
255 }
256
257 // are we in a multi-language setup?
258 $multiLang = $domain->locales ? TRUE : FALSE;
259
260 // set the current language
261 $lcMessages = NULL;
262
263 $session = CRM_Core_Session::singleton();
264
265 // on multi-lang sites based on request and civicrm_uf_match
266 if ($multiLang) {
267 $lcMessagesRequest = CRM_Utils_Request::retrieve('lcMessages', 'String', $this);
268 $languageLimit = array();
269 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
270 $languageLimit = $defaults['languageLimit'];
271 }
272
273 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
274 $lcMessages = $lcMessagesRequest;
275
276 //CRM-8559, cache navigation do not respect locale if it is changed, so reseting cache.
277 CRM_Core_BAO_Cache::deleteGroup('navigation');
278 }
279 else {
280 $lcMessagesRequest = NULL;
281 }
282
283 if (!$lcMessagesRequest) {
284 $lcMessagesSession = $session->get('lcMessages');
285 if (in_array($lcMessagesSession, array_keys($languageLimit))) {
286 $lcMessages = $lcMessagesSession;
287 }
288 else {
289 $lcMessagesSession = NULL;
290 }
291 }
292
293 if ($lcMessagesRequest) {
294 $ufm = new CRM_Core_DAO_UFMatch();
295 $ufm->contact_id = $session->get('userID');
296 if ($ufm->find(TRUE)) {
297 $ufm->language = $lcMessages;
298 $ufm->save();
299 }
300 $session->set('lcMessages', $lcMessages);
301 }
302
303 if (!$lcMessages and $session->get('userID')) {
304 $ufm = new CRM_Core_DAO_UFMatch();
305 $ufm->contact_id = $session->get('userID');
306 if ($ufm->find(TRUE) &&
307 in_array($ufm->language, array_keys($languageLimit))
308 ) {
309 $lcMessages = $ufm->language;
310 }
311 $session->set('lcMessages', $lcMessages);
312 }
313 }
314 global $dbLocale;
315
316 // try to inherit the language from the hosting CMS
317 if (CRM_Utils_Array::value('inheritLocale', $defaults)) {
318 // FIXME: On multilanguage installs, CRM_Utils_System::getUFLocale() in many cases returns nothing if $dbLocale is not set
319 $dbLocale = $multiLang ? "_{$defaults['lcMessages']}" : '';
320 $lcMessages = CRM_Utils_System::getUFLocale();
321 if ($domain->locales and !in_array($lcMessages, explode(CRM_Core_DAO::VALUE_SEPARATOR,
322 $domain->locales
323 ))) {
324 $lcMessages = NULL;
325 }
326 }
327
328 if ($lcMessages) {
329 // update config lcMessages - CRM-5027 fixed.
330 $defaults['lcMessages'] = $lcMessages;
331 }
332 else {
333 // if a single-lang site or the above didn't yield a result, use default
334 $lcMessages = CRM_Utils_Array::value( 'lcMessages', $defaults );
335 }
336
337 // set suffix for table names - use views if more than one language
338 $dbLocale = $multiLang ? "_{$lcMessages}" : '';
339
340 // FIXME: an ugly hack to fix CRM-4041
341 global $tsLocale;
342 $tsLocale = $lcMessages;
343
344 // FIXME: as bad aplace as any to fix CRM-5428
345 // (to be moved to a sane location along with the above)
346 if (function_exists('mb_internal_encoding')) {
347 mb_internal_encoding('UTF-8');
348 }
349 }
350
351 // dont add if its empty
352 if (!empty($defaults)) {
353 // retrieve directory and url preferences also
354 CRM_Core_BAO_Setting::retrieveDirectoryAndURLPreferences($defaults);
355 }
356 }
357
358 static function getConfigSettings() {
359 $config = CRM_Core_Config::singleton();
360
361 $url = $dir = $siteName = $siteRoot = NULL;
362 if ($config->userFramework == 'Joomla') {
363 $url = preg_replace('|administrator/components/com_civicrm/civicrm/|',
364 '',
365 $config->userFrameworkResourceURL
366 );
367
368 // lets use imageUploadDir since we dont mess around with its values
369 // in the config object, lets kep it a bit generic since folks
370 // might have different values etc
371 $dir = preg_replace('|civicrm/templates_c/.*$|',
372 '',
373 $config->templateCompileDir
374 );
375 $siteRoot = preg_replace('|/media/civicrm/.*$|',
376 '',
377 $config->imageUploadDir
378 );
379 }
380 else {
381 $url = preg_replace('|sites/[\w\.\-\_]+/modules/civicrm/|',
382 '',
383 $config->userFrameworkResourceURL
384 );
385
386 // lets use imageUploadDir since we dont mess around with its values
387 // in the config object, lets kep it a bit generic since folks
388 // might have different values etc
389 $dir = preg_replace('|/files/civicrm/.*$|',
390 '/files/',
391 $config->imageUploadDir
392 );
393
394 $matches = array();
395 if (preg_match('|/sites/([\w\.\-\_]+)/|',
396 $config->imageUploadDir,
397 $matches
398 )) {
399 $siteName = $matches[1];
400 if ($siteName) {
401 $siteName = "/sites/$siteName/";
402 $siteNamePos = strpos($dir, $siteName);
403 if ($siteNamePos !== FALSE) {
404 $siteRoot = substr($dir, 0, $siteNamePos);
405 }
406 }
407 }
408 }
409
410
411 return array($url, $dir, $siteName, $siteRoot);
412 }
413
414 static function getBestGuessSettings() {
415 $config = CRM_Core_Config::singleton();
416
417 $url = $config->userFrameworkBaseURL;
418 $siteName = $siteRoot = NULL;
419 if ($config->userFramework == 'Joomla') {
420 $url = preg_replace('|/administrator|',
421 '',
422 $config->userFrameworkBaseURL
423 );
424 $siteRoot = preg_replace('|/media/civicrm/.*$|',
425 '',
426 $config->imageUploadDir
427 );
428 }
429 $dir = preg_replace('|civicrm/templates_c/.*$|',
430 '',
431 $config->templateCompileDir
432 );
433
434 if ($config->userFramework != 'Joomla') {
435 $matches = array();
436 if (preg_match('|/sites/([\w\.\-\_]+)/|',
437 $config->templateCompileDir,
438 $matches
439 )) {
440 $siteName = $matches[1];
441 if ($siteName) {
442 $siteName = "/sites/$siteName/";
443 $siteNamePos = strpos($dir, $siteName);
444 if ($siteNamePos !== FALSE) {
445 $siteRoot = substr($dir, 0, $siteNamePos);
446 }
447 }
448 }
449 }
450
451 return array($url, $dir, $siteName, $siteRoot);
452 }
453
454 static function doSiteMove($defaultValues = array() ) {
455 $moveStatus = ts('Beginning site move process...') . '<br />';
456 // get the current and guessed values
457 list($oldURL, $oldDir, $oldSiteName, $oldSiteRoot) = self::getConfigSettings();
458 list($newURL, $newDir, $newSiteName, $newSiteRoot) = self::getBestGuessSettings();
459
460
461 // retrieve these values from the argument list
462 $variables = array('URL', 'Dir', 'SiteName', 'SiteRoot', 'Val_1', 'Val_2', 'Val_3');
463 $states = array('old', 'new');
464 foreach ($variables as $varSuffix) {
465 foreach ($states as $state) {
466 $var = "{$state}{$varSuffix}";
467 if (!isset($$var)) {
468 if (isset($defaultValues[$var])) {
469 $$var = $defaultValues[$var];
470 }
471 else {
472 $$var = NULL;
473 }
474 }
475 $$var = CRM_Utils_Request::retrieve($var,
476 'String',
477 CRM_Core_DAO::$_nullArray,
478 FALSE,
479 $$var,
480 'REQUEST'
481 );
482 }
483 }
484
485 $from = $to = array();
486 foreach ($variables as $varSuffix) {
487 $oldVar = "old{$varSuffix}";
488 $newVar = "new{$varSuffix}";
489 //skip it if either is empty or both are exactly the same
490 if ($$oldVar &&
491 $$newVar &&
492 $$oldVar != $$newVar
493 ) {
494 $from[] = $$oldVar;
495 $to[] = $$newVar;
496 }
497 }
498
499 $sql = "
500SELECT config_backend
501FROM civicrm_domain
502WHERE id = %1
503";
504 $params = array(1 => array(CRM_Core_Config::domainID(), 'Integer'));
505 $configBackend = CRM_Core_DAO::singleValueQuery($sql, $params);
506 if (!$configBackend) {
507 CRM_Core_Error::fatal(ts('Returning early due to unexpected error - civicrm_domain.config_backend column value is NULL. Try visiting CiviCRM Home page.'));
508 }
509 $configBackend = unserialize($configBackend);
510
511 $configBackend = str_replace($from,
512 $to,
513 $configBackend
514 );
515
516 $configBackend = serialize($configBackend);
517 $sql = "
518UPDATE civicrm_domain
519SET config_backend = %2
520WHERE id = %1
521";
522 $params[2] = array($configBackend, 'String');
523 CRM_Core_DAO::executeQuery($sql, $params);
524
525 // Apply the changes to civicrm_option_values
526 $optionGroups = array('url_preferences', 'directory_preferences');
527 foreach ($optionGroups as $option) {
528 foreach ($variables as $varSuffix) {
529 $oldVar = "old{$varSuffix}";
530 $newVar = "new{$varSuffix}";
531
532 $from = $$oldVar;
533 $to = $$newVar;
534
535 if ($from && $to && $from != $to) {
536 $sql = '
537UPDATE civicrm_option_value
538SET value = REPLACE(value, %1, %2)
539WHERE option_group_id = (
540 SELECT id
541 FROM civicrm_option_group
542 WHERE name = %3 )
543';
544 $params = array(1 => array($from, 'String'),
545 2 => array($to, 'String'),
546 3 => array($option, 'String'),
547 );
548 CRM_Core_DAO::executeQuery($sql, $params);
549 }
550 }
551 }
552
553 $moveStatus .= ts('Directory and Resource URLs have been updated in the moved database to reflect current site location.') . '<br />';
554
555 $config = CRM_Core_Config::singleton();
556
557 // clear the template_c and upload directory also
558 $config->cleanup(3, TRUE);
559 $moveStatus .= ts('Template cache and upload directory have been cleared.') . '<br />';
560
561 // clear all caches
562 CRM_Core_Config::clearDBCache();
563 $moveStatus .= ts('Database cache tables cleared.') . '<br />';
564
565 $resetSessionTable = CRM_Utils_Request::retrieve('resetSessionTable',
566 'Boolean',
567 CRM_Core_DAO::$_nullArray,
568 FALSE,
569 FALSE,
570 'REQUEST'
571 );
572 if ($config->userSystem->is_drupal &&
573 $resetSessionTable
574 ) {
575 db_query("DELETE FROM {sessions} WHERE 1");
576 $moveStatus .= ts('Drupal session table cleared.') . '<br />';
577 }
578 else {
579 $session = CRM_Core_Session::singleton();
580 $session->reset(2);
581 $moveStatus .= ts('Session has been reset.') . '<br />';
582 }
583
584 return $moveStatus;
585 }
586
587 /**
588 * takes a componentName and enables it in the config
589 * Primarily used during unit testing
590 *
591 * @param string $componentName name of the component to be enabled, needs to be valid
592 *
593 * @return boolean - true if valid component name and enabling succeeds, else false
594 * @static
595 */
596 static function enableComponent($componentName) {
597 $config = CRM_Core_Config::singleton();
598 if (in_array($componentName, $config->enableComponents)) {
599 // component is already enabled
600 return TRUE;
601 }
602 $components = CRM_Core_Component::getComponents();
603
604 // return if component does not exist
605 if (!array_key_exists($componentName, $components)) {
606 return FALSE;
607 }
608
609 // get config_backend value
610 $sql = "
611SELECT config_backend
612FROM civicrm_domain
613WHERE id = %1
614";
615 $params = array(1 => array(CRM_Core_Config::domainID(), 'Integer'));
616 $configBackend = CRM_Core_DAO::singleValueQuery($sql, $params);
617
618 if (!$configBackend) {
619 static $alreadyVisited = FALSE;
620 if ($alreadyVisited) {
621 CRM_Core_Error::fatal(ts('Returning early due to unexpected error - civicrm_domain.config_backend column value is NULL. Try visiting CiviCRM Home page.'));
622 }
623
624 $alreadyVisited = TRUE;
625
626 // try to recreate the config backend
627 $config = CRM_Core_Config::singleton(TRUE, TRUE);
628 return self::enableComponent($componentName);
629 }
630 $configBackend = unserialize($configBackend);
631
632 $configBackend['enableComponents'][] = $componentName;
633 $configBackend['enableComponentIDs'][] = $components[$componentName]->componentID;
634
635 // fix the config object
636 $config->enableComponents = $configBackend['enableComponents'];
637 $config->enableComponentIDs = $configBackend['enableComponentIDs'];
638
639 // also force reset of component array
640 CRM_Core_Component::getEnabledComponents(TRUE);
641
642 // check if component is already there, is so return
643 $configBackend = serialize($configBackend);
644 $sql = "
645UPDATE civicrm_domain
646SET config_backend = %2
647WHERE id = %1
648";
649 $params[2] = array($configBackend, 'String');
650 CRM_Core_DAO::executeQuery($sql, $params);
651
652 return TRUE;
653 }
654
655 static function skipVars() {
656 return array(
657 'dsn', 'templateCompileDir',
658 'userFrameworkDSN',
659 'userFramework',
660 'userFrameworkBaseURL', 'userFrameworkClass', 'userHookClass',
661 'userPermissionClass', 'userFrameworkURLVar', 'userFrameworkVersion',
662 'newBaseURL', 'newBaseDir', 'newSiteName', 'configAndLogDir',
663 'qfKey', 'gettextResourceDir', 'cleanURL',
664 'locale_custom_strings', 'localeCustomStrings',
665 'autocompleteContactSearch',
666 'autocompleteContactReference',
667 'checksumTimeout',
668 );
669 }
670}
671