Merge pull request #1382 from swati-karande/CRM-13146
[civicrm-core.git] / CRM / Core / BAO / ConfigSetting.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 *
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 */
41 class CRM_Core_BAO_ConfigSetting {
42
43 /**
44 * Function to create civicrm settings. This is the same as add but it clears the cache and
45 * reloads the config object
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');
56 $cache->delete('CRM_Core_Config' . CRM_Core_Config::domainID());
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');
74 $params['civiRelativeURL'] =
75 str_replace(
76 'CIVI_BASE_TEMPLATE',
77 '',
78 $params['civiRelativeURL']
79 );
80
81 // also add the version number for use by template / js etc
82 $params['civiVersion'] = CRM_Utils_System::version();
83
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 // check if there are any locale strings
240 if ($domain->locale_custom_strings) {
241 $defaults['localeCustomStrings'] = unserialize($domain->locale_custom_strings);
242 }
243 else {
244 $defaults['localeCustomStrings'] = NULL;
245 }
246
247 // are we in a multi-language setup?
248 $multiLang = $domain->locales ? TRUE : FALSE;
249
250 // set the current language
251 $lcMessages = NULL;
252
253 $session = CRM_Core_Session::singleton();
254
255 // on multi-lang sites based on request and civicrm_uf_match
256 if ($multiLang) {
257 $lcMessagesRequest = CRM_Utils_Request::retrieve('lcMessages', 'String', $this);
258 $languageLimit = array();
259 if (array_key_exists('languageLimit', $defaults) && is_array($defaults['languageLimit'])) {
260 $languageLimit = $defaults['languageLimit'];
261 }
262
263 if (in_array($lcMessagesRequest, array_keys($languageLimit))) {
264 $lcMessages = $lcMessagesRequest;
265
266 //CRM-8559, cache navigation do not respect locale if it is changed, so reseting cache.
267 CRM_Core_BAO_Cache::deleteGroup('navigation');
268 }
269 else {
270 $lcMessagesRequest = NULL;
271 }
272
273 if (!$lcMessagesRequest) {
274 $lcMessagesSession = $session->get('lcMessages');
275 if (in_array($lcMessagesSession, array_keys($languageLimit))) {
276 $lcMessages = $lcMessagesSession;
277 }
278 else {
279 $lcMessagesSession = NULL;
280 }
281 }
282
283 if ($lcMessagesRequest) {
284 $ufm = new CRM_Core_DAO_UFMatch();
285 $ufm->contact_id = $session->get('userID');
286 if ($ufm->find(TRUE)) {
287 $ufm->language = $lcMessages;
288 $ufm->save();
289 }
290 $session->set('lcMessages', $lcMessages);
291 }
292
293 if (!$lcMessages and $session->get('userID')) {
294 $ufm = new CRM_Core_DAO_UFMatch();
295 $ufm->contact_id = $session->get('userID');
296 if ($ufm->find(TRUE) &&
297 in_array($ufm->language, array_keys($languageLimit))
298 ) {
299 $lcMessages = $ufm->language;
300 }
301 $session->set('lcMessages', $lcMessages);
302 }
303 }
304 global $dbLocale;
305
306 // try to inherit the language from the hosting CMS
307 if (CRM_Utils_Array::value('inheritLocale', $defaults)) {
308 // FIXME: On multilanguage installs, CRM_Utils_System::getUFLocale() in many cases returns nothing if $dbLocale is not set
309 $dbLocale = $multiLang ? "_{$defaults['lcMessages']}" : '';
310 $lcMessages = CRM_Utils_System::getUFLocale();
311 if ($domain->locales and !in_array($lcMessages, explode(CRM_Core_DAO::VALUE_SEPARATOR,
312 $domain->locales
313 ))) {
314 $lcMessages = NULL;
315 }
316 }
317
318 if ($lcMessages) {
319 // update config lcMessages - CRM-5027 fixed.
320 $defaults['lcMessages'] = $lcMessages;
321 }
322 else {
323 // if a single-lang site or the above didn't yield a result, use default
324 $lcMessages = CRM_Utils_Array::value( 'lcMessages', $defaults );
325 }
326
327 // set suffix for table names - use views if more than one language
328 $dbLocale = $multiLang ? "_{$lcMessages}" : '';
329
330 // FIXME: an ugly hack to fix CRM-4041
331 global $tsLocale;
332 $tsLocale = $lcMessages;
333
334 // FIXME: as bad aplace as any to fix CRM-5428
335 // (to be moved to a sane location along with the above)
336 if (function_exists('mb_internal_encoding')) {
337 mb_internal_encoding('UTF-8');
338 }
339 }
340
341 // dont add if its empty
342 if (!empty($defaults)) {
343 // retrieve directory and url preferences also
344 CRM_Core_BAO_Setting::retrieveDirectoryAndURLPreferences($defaults);
345
346 // Pickup enabled-components from settings table if found.
347 $enableComponents = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'enable_components', NULL, array());
348 if (!empty($enableComponents)) {
349 $defaults['enableComponents'] = $enableComponents;
350
351 $components = CRM_Core_Component::getComponents();
352 $enabledComponentIDs = array();
353 foreach ($defaults['enableComponents'] as $name) {
354 $enabledComponentIDs[] = $components[$name]->componentID;
355 }
356 $defaults['enableComponentIDs'] = $enabledComponentIDs;
357 }
358 }
359 }
360
361 static function getConfigSettings() {
362 $config = CRM_Core_Config::singleton();
363
364 $url = $dir = $siteName = $siteRoot = NULL;
365 if ($config->userFramework == 'Joomla') {
366 $url = preg_replace(
367 '|administrator/components/com_civicrm/civicrm/|',
368 '',
369 $config->userFrameworkResourceURL
370 );
371
372 // lets use imageUploadDir since we dont mess around with its values
373 // in the config object, lets kep it a bit generic since folks
374 // might have different values etc
375 $dir = preg_replace(
376 '|civicrm/templates_c/.*$|',
377 '',
378 $config->templateCompileDir
379 );
380 $siteRoot = preg_replace(
381 '|/media/civicrm/.*$|',
382 '',
383 $config->imageUploadDir
384 );
385 }
386 else if ($config->userFramework == 'WordPress') {
387 $url = preg_replace(
388 '|wp-content/plugins/civicrm/civicrm/|',
389 '',
390 $config->userFrameworkResourceURL
391 );
392
393 // lets use imageUploadDir since we dont mess around with its values
394 // in the config object, lets kep it a bit generic since folks
395 // might have different values etc
396 $dir = preg_replace(
397 '|civicrm/templates_c/.*$|',
398 '',
399 $config->templateCompileDir
400 );
401 $siteRoot = preg_replace(
402 '|/wp-content/plugins/files/civicrm/.*$|',
403 '',
404 $config->imageUploadDir
405 );
406 }
407 else {
408 $url = preg_replace(
409 '|sites/[\w\.\-\_]+/modules/civicrm/|',
410 '',
411 $config->userFrameworkResourceURL
412 );
413
414 // lets use imageUploadDir since we dont mess around with its values
415 // in the config object, lets kep it a bit generic since folks
416 // might have different values etc
417 $dir = preg_replace(
418 '|/files/civicrm/.*$|',
419 '/files/',
420 $config->imageUploadDir
421 );
422
423 $matches = array();
424 if (preg_match(
425 '|/sites/([\w\.\-\_]+)/|',
426 $config->imageUploadDir,
427 $matches
428 )) {
429 $siteName = $matches[1];
430 if ($siteName) {
431 $siteName = "/sites/$siteName/";
432 $siteNamePos = strpos($dir, $siteName);
433 if ($siteNamePos !== FALSE) {
434 $siteRoot = substr($dir, 0, $siteNamePos);
435 }
436 }
437 }
438 }
439
440
441 return array($url, $dir, $siteName, $siteRoot);
442 }
443
444 /**
445 * Return likely default settings
446 * @return array site settings
447 * -$url,
448 * - $dir Base Directory
449 * - $siteName
450 * - $siteRoot
451 */
452 static function getBestGuessSettings() {
453 $config = CRM_Core_Config::singleton();
454 $dir = preg_replace(
455 '|civicrm/templates_c/.*$|',
456 '',
457 $config->templateCompileDir
458 );
459
460 list($url, $siteName, $siteRoot) = $config->userSystem->getDefaultSiteSettings($dir);
461 return array($url, $dir, $siteName, $siteRoot);
462 }
463
464 static function doSiteMove($defaultValues = array() ) {
465 $moveStatus = ts('Beginning site move process...') . '<br />';
466 // get the current and guessed values
467 list($oldURL, $oldDir, $oldSiteName, $oldSiteRoot) = self::getConfigSettings();
468 list($newURL, $newDir, $newSiteName, $newSiteRoot) = self::getBestGuessSettings();
469
470
471 // retrieve these values from the argument list
472 $variables = array('URL', 'Dir', 'SiteName', 'SiteRoot', 'Val_1', 'Val_2', 'Val_3');
473 $states = array('old', 'new');
474 foreach ($variables as $varSuffix) {
475 foreach ($states as $state) {
476 $var = "{$state}{$varSuffix}";
477 if (!isset($$var)) {
478 if (isset($defaultValues[$var])) {
479 $$var = $defaultValues[$var];
480 }
481 else {
482 $$var = NULL;
483 }
484 }
485 $$var = CRM_Utils_Request::retrieve($var,
486 'String',
487 CRM_Core_DAO::$_nullArray,
488 FALSE,
489 $$var,
490 'REQUEST'
491 );
492 }
493 }
494
495 $from = $to = array();
496 foreach ($variables as $varSuffix) {
497 $oldVar = "old{$varSuffix}";
498 $newVar = "new{$varSuffix}";
499 //skip it if either is empty or both are exactly the same
500 if ($$oldVar &&
501 $$newVar &&
502 $$oldVar != $$newVar
503 ) {
504 $from[] = $$oldVar;
505 $to[] = $$newVar;
506 }
507 }
508
509 $sql = "
510 SELECT config_backend
511 FROM civicrm_domain
512 WHERE id = %1
513 ";
514 $params = array(1 => array(CRM_Core_Config::domainID(), 'Integer'));
515 $configBackend = CRM_Core_DAO::singleValueQuery($sql, $params);
516 if (!$configBackend) {
517 CRM_Core_Error::fatal(ts('Returning early due to unexpected error - civicrm_domain.config_backend column value is NULL. Try visiting CiviCRM Home page.'));
518 }
519 $configBackend = unserialize($configBackend);
520
521 $configBackend = str_replace($from,
522 $to,
523 $configBackend
524 );
525
526 $configBackend = serialize($configBackend);
527 $sql = "
528 UPDATE civicrm_domain
529 SET config_backend = %2
530 WHERE id = %1
531 ";
532 $params[2] = array($configBackend, 'String');
533 CRM_Core_DAO::executeQuery($sql, $params);
534
535 // Apply the changes to civicrm_option_values
536 $optionGroups = array('url_preferences', 'directory_preferences');
537 foreach ($optionGroups as $option) {
538 foreach ($variables as $varSuffix) {
539 $oldVar = "old{$varSuffix}";
540 $newVar = "new{$varSuffix}";
541
542 $from = $$oldVar;
543 $to = $$newVar;
544
545 if ($from && $to && $from != $to) {
546 $sql = '
547 UPDATE civicrm_option_value
548 SET value = REPLACE(value, %1, %2)
549 WHERE option_group_id = (
550 SELECT id
551 FROM civicrm_option_group
552 WHERE name = %3 )
553 ';
554 $params = array(1 => array($from, 'String'),
555 2 => array($to, 'String'),
556 3 => array($option, 'String'),
557 );
558 CRM_Core_DAO::executeQuery($sql, $params);
559 }
560 }
561 }
562
563 $moveStatus .= ts('Directory and Resource URLs have been updated in the moved database to reflect current site location.') . '<br />';
564
565 $config = CRM_Core_Config::singleton();
566
567 // clear the template_c and upload directory also
568 $config->cleanup(3, TRUE);
569 $moveStatus .= ts('Template cache and upload directory have been cleared.') . '<br />';
570
571 // clear all caches
572 CRM_Core_Config::clearDBCache();
573 $moveStatus .= ts('Database cache tables cleared.') . '<br />';
574
575 $resetSessionTable = CRM_Utils_Request::retrieve('resetSessionTable',
576 'Boolean',
577 CRM_Core_DAO::$_nullArray,
578 FALSE,
579 FALSE,
580 'REQUEST'
581 );
582 if ($config->userSystem->is_drupal &&
583 $resetSessionTable
584 ) {
585 db_query("DELETE FROM {sessions} WHERE 1");
586 $moveStatus .= ts('Drupal session table cleared.') . '<br />';
587 }
588 else {
589 $session = CRM_Core_Session::singleton();
590 $session->reset(2);
591 $moveStatus .= ts('Session has been reset.') . '<br />';
592 }
593
594 return $moveStatus;
595 }
596
597 /**
598 * takes a componentName and enables it in the config
599 * Primarily used during unit testing
600 *
601 * @param string $componentName name of the component to be enabled, needs to be valid
602 *
603 * @return boolean - true if valid component name and enabling succeeds, else false
604 * @static
605 */
606 static function enableComponent($componentName) {
607 $config = CRM_Core_Config::singleton();
608 if (in_array($componentName, $config->enableComponents)) {
609 // component is already enabled
610 return TRUE;
611 }
612 $components = CRM_Core_Component::getComponents();
613
614 // return if component does not exist
615 if (!array_key_exists($componentName, $components)) {
616 return FALSE;
617 }
618
619 // get enabled-components from DB and add to the list
620 $enabledComponents =
621 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'enable_components', NULL, array());
622 $enabledComponents[] = $componentName;
623
624 $enabledComponentIDs = array();
625 foreach ($enabledComponents as $name) {
626 $enabledComponentIDs[] = $components[$name]->componentID;
627 }
628
629 // fix the config object
630 $config->enableComponents = $enabledComponents;
631 $config->enableComponentIDs = $enabledComponentIDs;
632
633 // also force reset of component array
634 CRM_Core_Component::getEnabledComponents(TRUE);
635
636 // update DB
637 CRM_Core_BAO_Setting::setItem($enabledComponents,
638 CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,'enable_components');
639
640 return TRUE;
641 }
642
643 static function skipVars() {
644 return array(
645 'dsn', 'templateCompileDir',
646 'userFrameworkDSN',
647 'userFramework',
648 'userFrameworkBaseURL', 'userFrameworkClass', 'userHookClass',
649 'userPermissionClass', 'userFrameworkURLVar', 'userFrameworkVersion',
650 'newBaseURL', 'newBaseDir', 'newSiteName', 'configAndLogDir',
651 'qfKey', 'gettextResourceDir', 'cleanURL',
652 'locale_custom_strings', 'localeCustomStrings',
653 'autocompleteContactSearch',
654 'autocompleteContactReference',
655 'checksumTimeout',
656 );
657 }
658 }
659