translation: improve initialization

- Keep current language in session
- allow selection using lang request parameter
- allow reseting current language using reset_lang request parameter
- improve logging problems
- add 'Hello word!' test to validate initializatio
This commit is contained in:
Benjamin Renard 2021-10-07 20:46:13 +02:00
parent 6d8abbf391
commit 5dd35cabb2

View file

@ -80,12 +80,23 @@ function init_translation() {
$available_langs = get_available_langs(); $available_langs = get_available_langs();
if (php_sapi_name() != "cli") { if (php_sapi_name() != "cli") {
if (isset($_REQUEST['lang']) && in_array($_REQUEST['lang'], $available_langs)) {
$lang = $_REQUEST['lang'];
logging('TRACE', "Select lang from request parameter: '$lang'");
}
elseif (isset($_SESSION['lang']) && in_array($_SESSION['lang'], $available_langs) && !isset($_REQUEST['reset_lang'])) {
$lang = $_SESSION['lang'];
logging('TRACE', "Restore lang from session: '$lang'");
}
else {
$lang = Locale::lookup( $lang = Locale::lookup(
get_available_langs(), get_available_langs(),
Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']), Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']),
true, true,
Locale::getPrimaryLanguage($default_locale) Locale::getPrimaryLanguage($default_locale)
); );
logging('TRACE', "Best lang found is '$lang'");
}
} }
else { else {
$lang = null; $lang = null;
@ -101,13 +112,16 @@ function init_translation() {
else else
logging('TRACE', "Lang detected from CLI env : '$lang'"); logging('TRACE', "Lang detected from CLI env : '$lang'");
} }
logging('TRACE', "Best lang found is '$lang'");
// Keep selected lang in session
$_SESSION['lang'] = $lang;
$locale = lang2locale($lang); $locale = lang2locale($lang);
logging('TRACE', "Matching locale found with language '$lang' is '$locale'"); logging('TRACE', "Matching locale found with language '$lang' is '$locale'");
// Gettext firstly look the LANGUAGE env variable, so set it // Gettext firstly look the LANGUAGE env variable, so set it
putenv("LANGUAGE=$locale"); if (!putenv("LANGUAGE=$locale"))
logging('ERROR', "Fail to set LANGUAGE variable in environnement to '$locale'");
// Set the locale // Set the locale
if (setlocale(LC_ALL, $locale) === false) if (setlocale(LC_ALL, $locale) === false)
@ -117,4 +131,5 @@ function init_translation() {
$fullpath = bindtextdomain(TEXT_DOMAIN, $root_lang_dir); $fullpath = bindtextdomain(TEXT_DOMAIN, $root_lang_dir);
logging('TRACE', "Text domain fullpath is '$fullpath'."); logging('TRACE', "Text domain fullpath is '$fullpath'.");
logging('TRACE', "Text domain is '".textdomain(TEXT_DOMAIN)."'."); logging('TRACE', "Text domain is '".textdomain(TEXT_DOMAIN)."'.");
logging('TRACE', "Test: "._('Hello world !'));
} }