From cbc494ab9bebe0ac20172b0a3119797df51f5808 Mon Sep 17 00:00:00 2001 From: jkbockstael Date: Thu, 21 Apr 2011 17:51:47 +0200 Subject: [PATCH] CustomPages : added language.inc.php for browser language detection and string translation facilities. --- custompages/language.inc.php | 64 ++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 custompages/language.inc.php diff --git a/custompages/language.inc.php b/custompages/language.inc.php new file mode 100644 index 0000000000..bfd2a47e06 --- /dev/null +++ b/custompages/language.inc.php @@ -0,0 +1,64 @@ + + +// This requires the Chamilo system to be initialized +require_once('/main/inc/global.inc.php'); + +// Returns the best match between available languages and visitor preferences +// return the best match as 2-chars code, null when none match +function get_preferred_language($available_langs) { + // Parsing the Accept-languages HTTP header + $langs = array(); + foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $httplang) { + $rawlang = explode(';q=', $httplang); + if (strpos($rawlang[0], '-') !== FALSE) { + // We ignore the locale part, as in en-GB vs en-US + $rawlang[0] = substr($rawlang[0], 0, strpos($rawlang[0], '-')); + } + if (count($rawlang) == 1) { + $rawlang[1] = 1.0; // The absence of weighting means a weight of 1 (max) + } + $langs[$rawlang[1]][] = $rawlang[0]; + } + krsort($langs, SORT_NUMERIC); + // Choosing the best match + foreach($langs as $weight => $codes) { + foreach ($codes as $code) { + if (in_array($code, $available_langs)) { + return $code; + } + } + } + // No match + return null; +} + +// Wrapper function for the get_lang function +// use this if you want to avoid translation caching issues +function cp_get_lang($variable) { + return get_lang($variable, null, $_SESSION['user_language_choice']); +} + +// Note that Chamilo languages are expressed as full english names, not 2-characters codes +// e.g. 'english' instead of 'en', 'french' instead of 'fr', ... +// We need a matching array. Note the value for the null key, which is the default language. +// Also note that this is an example matchin array, not all languages are present. +$chamilo_langs = array(null => 'english', 'en' => 'english', 'fr' => 'french', 'es' => 'spanish'); + +// Which language files will we need ? +$language_file = array('courses', 'index', 'registration', 'admin','userInfo'); + +// Let's find out which language to serve to this particular browser +$lang_match = $chamilo_langs[get_preferred_language($available_langs)]; + +// Chamilo overrides this parameters at some places, e.g. in the logout link +if (isset($_REQUEST['language']) && !empty($_REQUEST['language']) && in_array($_REQUEST['language'], $chamilo_langs)) { + $lang_match = $_REQUEST['language']; +} + +// We need to set the relevant session variables to the best match, to use Chamilo's i18n lib. +$_user['language'] = $lang_match; +$_SESSION['user_language_choice'] = $lang_match; +?>