73 lines
2.3 KiB
PHP
73 lines
2.3 KiB
PHP
<?php
|
|
|
|
$staticLangDir = __DIR__ . '/lang';
|
|
$runtimeLangDir = getenv('WEBSITE_LANG_WRITE_DIR') ?: null;
|
|
$staticLangFiles = glob($staticLangDir . '/*.php') ?: [];
|
|
$runtimeLangFiles = [];
|
|
if ($runtimeLangDir && is_dir($runtimeLangDir)) {
|
|
$runtimeLangFiles = glob($runtimeLangDir . '/*.json') ?: [];
|
|
}
|
|
|
|
$availableLangs = array_values(array_unique(array_map(
|
|
fn($f) => preg_replace('/\.(php|json)$/', '', basename($f)),
|
|
array_merge($staticLangFiles, $runtimeLangFiles)
|
|
)));
|
|
$availableLangs = array_values(array_filter(
|
|
$availableLangs,
|
|
fn($code) => is_string($code) && preg_match('/^[a-z]{2,5}$/', $code)
|
|
));
|
|
|
|
function getLang($supported) {
|
|
if (isset($_GET['lang']) && in_array($_GET['lang'], $supported, true)) {
|
|
return $_GET['lang'];
|
|
}
|
|
$browser = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? 'nah', 0, 2));
|
|
return in_array($browser, $supported, true) ? $browser : 'nah';
|
|
}
|
|
|
|
function cleanRuntimeTranslation(string $value, int $maxLength = 2000): string {
|
|
$value = strip_tags($value);
|
|
$value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value) ?? '';
|
|
$value = trim($value);
|
|
if (strlen($value) > $maxLength) {
|
|
$value = substr($value, 0, $maxLength);
|
|
}
|
|
return $value;
|
|
}
|
|
|
|
function loadRuntimeTranslations(string $file, array $base): array {
|
|
$raw = file_get_contents($file);
|
|
if ($raw === false || strlen($raw) > 131072) {
|
|
return [];
|
|
}
|
|
|
|
$decoded = json_decode($raw, true);
|
|
if (!is_array($decoded)) {
|
|
return [];
|
|
}
|
|
|
|
$translations = [];
|
|
foreach ($decoded as $key => $value) {
|
|
if (!is_string($key) || !array_key_exists($key, $base) || (!is_string($value) && !is_numeric($value))) {
|
|
continue;
|
|
}
|
|
$translations[$key] = cleanRuntimeTranslation((string) $value);
|
|
}
|
|
return $translations;
|
|
}
|
|
|
|
$lang = getLang($availableLangs);
|
|
|
|
$en = include "$staticLangDir/en.php";
|
|
$staticFile = "$staticLangDir/$lang.php";
|
|
$runtimeFile = $runtimeLangDir ? "$runtimeLangDir/$lang.json" : '';
|
|
|
|
if (file_exists($staticFile)) {
|
|
$text = array_replace($en, include $staticFile);
|
|
} elseif ($runtimeFile && file_exists($runtimeFile)) {
|
|
$text = array_replace($en, loadRuntimeTranslations($runtimeFile, $en));
|
|
} else {
|
|
$lang = 'nah';
|
|
$text = array_replace($en, include "$staticLangDir/nah.php");
|
|
}
|