my-homelab-configs/apps/website/lang_helper.php

40 lines
1.1 KiB
PHP

<?php
// lang_helper.php
// Include this at the top of every page.
// Provides: $lang, $text, $en, $availableLangs
$staticLangDir = __DIR__ . '/lang';
$runtimeLangDir = getenv('WEBSITE_LANG_WRITE_DIR') ?: null;
$langFiles = glob($staticLangDir . '/*.php') ?: [];
if ($runtimeLangDir && is_dir($runtimeLangDir)) {
$langFiles = array_merge($langFiles, glob($runtimeLangDir . '/*.php') ?: []);
}
$availableLangs = array_values(array_unique(array_map(
fn($f) => basename($f, '.php'),
$langFiles
)));
function getLang($supported) {
if (isset($_GET['lang']) && in_array($_GET['lang'], $supported)) {
return $_GET['lang'];
}
$browser = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? 'nah', 0, 2);
return in_array($browser, $supported) ? $browser : 'nah';
}
$lang = getLang($availableLangs);
$file = $runtimeLangDir ? "$runtimeLangDir/$lang.php" : '';
if (!$file || !file_exists($file)) {
$file = "$staticLangDir/$lang.php";
}
if (!file_exists($file)) {
$lang = 'nah';
$file = "$staticLangDir/nah.php";
}
// Always load English as translation source
$en = include "$staticLangDir/en.php";
$text = array_replace($en, include $file);