mirror of
https://github.com/serghey-rodin/vesta.git
synced 2025-08-14 10:37:39 -07:00
Detect user language
This commit is contained in:
parent
05b76fefb2
commit
2bd84f00f9
6 changed files with 72 additions and 13 deletions
|
@ -45,3 +45,68 @@ function __() {
|
|||
array_unshift($args,$_SESSION['language']);
|
||||
return call_user_func_array("_translate",$args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects user language from Accept-Language HTTP header.
|
||||
* @param string Fallback language (default: 'en')
|
||||
* @return string Language code (such as 'en' and 'ja')
|
||||
*/
|
||||
function detect_user_language($fallback='en') {
|
||||
static $user_lang = '';
|
||||
|
||||
// Already detected
|
||||
if (!empty($user_lang)) return $user_lang;
|
||||
|
||||
// Check if Accept-Language header is available
|
||||
if (!isset($_SERVER) ||
|
||||
!isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ||
|
||||
!is_string($_SERVER['HTTP_ACCEPT_LANGUAGE'])
|
||||
) {
|
||||
// Store result for reusing
|
||||
$user_lang = $fallback;
|
||||
return $user_lang;
|
||||
}
|
||||
|
||||
// Sort Accept-Language by `q` value
|
||||
$accept_langs = explode(',', preg_replace('/\s/', '', strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])));
|
||||
$accept_langs_sorted = [];
|
||||
foreach ($accept_langs as $lang) {
|
||||
$div = explode(';q=', $lang, 2);
|
||||
if (count($div) < 2) {
|
||||
// `q` value was not specfied
|
||||
// -> Set default `q` value (1)
|
||||
$div[] = '1';
|
||||
}
|
||||
list($code, $q) = $div;
|
||||
if (preg_match('/^[\w\-]+$/', $code)) {
|
||||
// Acceptable language code
|
||||
$accept_langs_sorted[$code] = (double)$q;
|
||||
}
|
||||
}
|
||||
arsort($accept_langs_sorted);
|
||||
|
||||
// List lanugages
|
||||
exec (VESTA_CMD."v-list-sys-languages json", $output, $return_var);
|
||||
$languages = json_decode(implode('', $output), true);
|
||||
unset($output);
|
||||
|
||||
// Find best matching language
|
||||
foreach ($accept_langs_sorted as $user_lang => $dummy) {
|
||||
$decision = '';
|
||||
foreach ($languages as $prov_lang) {
|
||||
if (strlen($decision) > strlen($prov_lang)) continue;
|
||||
if (strpos($user_lang, $prov_lang) !== false) {
|
||||
$decision = $prov_lang;
|
||||
}
|
||||
}
|
||||
if (!empty($decision)) {
|
||||
// Store result for reusing
|
||||
$user_lang = $decision;
|
||||
return $user_lang;
|
||||
}
|
||||
}
|
||||
|
||||
// Store result for reusing
|
||||
$user_lang = $fallback;
|
||||
return $user_lang;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue