Here is my improved version of Translatable::choose_site_locale with support for Session, Member->Locale and Browser Language Detection. May be some one may find this useful.
static function choose_site_locale($langsAvailable = array()) {
$siteMode = Director::get_site_mode(); // either 'cms' or 'site'
if(self::$current_locale) {
i18n::set_locale(self::$current_locale);
// HINT: Windows and Linux compatibility. First locale native name is used like "German",
// second locale in short form like "de_DE.utf-8" is used
setlocale(LC_ALL, i18n::$common_locales[Translatable::get_current_locale()], Translatable::get_current_locale() . ".utf8");
return self::$current_locale;
}
$session = new Session($_SESSION);
if(((isset($_GET['locale']) && !$langsAvailable) || (isset($_GET['locale']) && in_array($_GET['locale'], $langsAvailable))) && $_GET["locale"]) {
// get from GET parameter
$session->inst_set("locale", $_GET['locale']);
self::set_current_locale($_GET['locale']);
$session->inst_save();
} else if ($session->inst_get("locale")) {
self::set_current_locale($session->inst_get("locale"));
} else if ($session->inst_get("loggedInAs")) {
$member = Member::get_by_id("Member", $session->inst_get("loggedInAs"));
if ($member) {
$locale = $member->Locale;
} else {
$locale = self::default_locale();
}
self::set_current_locale($locale);
} else {
$locale = self::default_locale();
// First try to detect browser preferred language
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$locales = array();
$list = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach($list as $part) {
$priority = '';
@list($_locale, $priority) = explode(';', $part);
if ($priority) {
$priority = substr($priority, 2);
} else {
$priority = 1.0;
}
if (preg_match('/^([a-zA-Z]+)$/', $_locale, $match)) {
if (isset(i18n::$likely_subtags[$match[1]])) {
$_locale = i18n::$likely_subtags[$match[1]];
} else {
$_locale = self::default_locale();
}
} else if (preg_match('/^([a-zA-Z]+)-([a-zA-Z]+)$/', $_locale, $match)) {
$_locale = $match[1] . '_' . strtoupper($match[2]);
} else {
$_locale = self::default_locale();
}
if (in_array($_locale, $locales) == false) {
$locales[$priority] = $_locale;
}
}
// Sort browser locales by priority
krsort($locales);
// Try to find best matching browser locale
foreach($locales as $_locale) {
if ($langsAvailable) {
if (isset($langsAvailable[$_locale])) {
$locale = $_locale;
break;
}
} else if (self::$allowed_locales) {
if (in_array($_locale, &self::$allowed_locales)) {
$locale = $_locale;
break;
}
} else {
if (isset(i18n::$all_locales[$_locale])) {
$locale = $_locale;
break;
}
}
}
}
self::set_current_locale($locale);
}
i18n::set_locale(self::$current_locale);
setlocale(LC_ALL, i18n::$common_locales[Translatable::get_current_locale()], Translatable::get_current_locale() . ".utf8");
return self::$current_locale;
}