From 5dd35cabb24d757d8dd0fba17a2d8cf76563d0d4 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Thu, 7 Oct 2021 20:46:13 +0200 Subject: [PATCH] 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 --- includes/translation.php | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/includes/translation.php b/includes/translation.php index e580936..d042381 100644 --- a/includes/translation.php +++ b/includes/translation.php @@ -80,12 +80,23 @@ function init_translation() { $available_langs = get_available_langs(); if (php_sapi_name() != "cli") { - $lang = Locale::lookup( - get_available_langs(), - Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']), - true, - Locale::getPrimaryLanguage($default_locale) - ); + 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( + get_available_langs(), + Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']), + true, + Locale::getPrimaryLanguage($default_locale) + ); + logging('TRACE', "Best lang found is '$lang'"); + } } else { $lang = null; @@ -101,13 +112,16 @@ function init_translation() { else 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); logging('TRACE', "Matching locale found with language '$lang' is '$locale'"); // 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 if (setlocale(LC_ALL, $locale) === false) @@ -117,4 +131,5 @@ function init_translation() { $fullpath = bindtextdomain(TEXT_DOMAIN, $root_lang_dir); logging('TRACE', "Text domain fullpath is '$fullpath'."); logging('TRACE', "Text domain is '".textdomain(TEXT_DOMAIN)."'."); + logging('TRACE', "Test: "._('Hello world !')); }