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

59 lines
1.7 KiB
PHP

<?php
// save_lang.php
// Receives: { "lang": "fr", "translations": { "nav_home": "Accueil", ... } }
// Merges with en.php base so all keys are always present, then saves lang/fr.php
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$body = json_decode(file_get_contents('php://input'), true);
if (!isset($body['lang'], $body['translations'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing lang or translations']);
exit;
}
$lang = preg_replace('/[^a-z]/', '', strtolower($body['lang']));
$translations = $body['translations'];
if (strlen($lang) < 2 || strlen($lang) > 5) {
http_response_code(400);
echo json_encode(['error' => 'Invalid lang code']);
exit;
}
// Load English as base — ensures every key exists even if not translated
$base = include __DIR__ . '/lang/en.php';
// Overwrite only keys that were translated
foreach ($translations as $key => $value) {
if (array_key_exists($key, $base)) {
$base[$key] = $value;
}
}
// Build PHP file content
$lines = ["<?php", "return ["];
foreach ($base as $key => $value) {
$key = addslashes($key);
$value = addslashes($value);
$lines[] = " '$key' => '$value',";
}
$lines[] = "];";
$content = implode("\n", $lines) . "\n";
$path = __DIR__ . "/lang/$lang.php";
if (file_put_contents($path, $content) === false) {
http_response_code(500);
echo json_encode(['error' => 'Could not write file — check permissions on lang/']);
exit;
}
echo json_encode(['success' => true, 'lang' => $lang, 'path' => "lang/$lang.php"]);