Skip to content

Commit

Permalink
Better language detection and take server language otherwise
Browse files Browse the repository at this point in the history
  • Loading branch information
wincelau committed Sep 27, 2023
1 parent 54b39bb commit e165f15
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 14 deletions.
40 changes: 27 additions & 13 deletions app.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
<?php

setlocale(LC_ALL, "");

$f3 = require(__DIR__.'/vendor/fatfree/base.php');

$f3->set('FALLBACK', null);
$f3->language($f3->get('HEADERS')['Accept-Language']);

session_start();

if(getenv("DEBUG")) {
$f3->set('DEBUG', getenv("DEBUG"));
}

$f3->set('LANGUAGES',
$f3->set('SUPPORTED_LANGUAGES',
['fr' => 'Français',
'en' => 'English',
'ar' => 'العربية']);
Expand All @@ -34,26 +39,18 @@
}

if ($f3->get('GET.lang')) {
$lang = $f3->get('GET.lang');
changeLanguage($lang, $f3);
} elseif (isset($_SESSION['LANGUAGE'])) {
changeLanguage($_SESSION['LANGUAGE'], $f3);
selectLanguage($f3->get('GET.lang'), $f3, true);
} elseif (isset($_COOKIE['LANGUAGE'])) {
changeLanguage($_COOKIE['LANGUAGE'], $f3);
selectLanguage($_COOKIE['LANGUAGE'], $f3, true);
} else {
selectLanguage($f3->get('LANGUAGE'), $f3);
}

$domain = basename(glob($f3->get('ROOT')."/locale/application_*.pot")[0], '.pot');

bindtextdomain($domain, $f3->get('ROOT')."/locale");
textdomain($domain);

function changeLanguage($lang, $f3) {
$_SESSION['LANGUAGE'] = $lang;
setcookie("LANGUAGE", $lang, strtotime('+1 year'));
putenv("LANGUAGE=$lang");
$f3->set('LANGUAGE', $lang);
}

$f3->set('TRANSLATION_LANGUAGE', _("en"));
$f3->set('DIRECTION_LANGUAGE', 'ltr');
if($f3->get('TRANSLATION_LANGUAGE') == "ar") {
Expand Down Expand Up @@ -474,6 +471,23 @@ function getCommit() {
return substr($commit, 0, 7);
}

function selectLanguage($lang, $f3, $putCookie = false) {
$langSupported = null;
foreach(explode(',', $lang) as $l) {
if(array_key_exists($l, $f3->get('SUPPORTED_LANGUAGES'))) {
$langSupported = $l;
break;
}
}
if(!$langSupported) {
return null;
}
if($putCookie) {
setcookie("LANGUAGE", $langSupported, strtotime('+1 year'));
}
putenv("LANGUAGE=$langSupported");
}

function convertPHPSizeToBytes($sSize)
{
$sSuffix = strtoupper(substr($sSize, -1));
Expand Down
2 changes: 1 addition & 1 deletion templates/components/navtab.html.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<span class="d-md-none"><i class="bi bi-translate"></i></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<?php foreach ($LANGUAGES as $key => $langue):?>
<?php foreach ($SUPPORTED_LANGUAGES as $key => $langue):?>
<li><a class="dropdown-item" href="?lang=<?php echo $key ?>"><?php echo $langue ?></a></li>
<?php endforeach; ?>
</ul>
Expand Down

0 comments on commit e165f15

Please sign in to comment.