Files
geograsim/App/sims/tourismusregion/api/save_map.php
T

53 lines
2.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// Speichert Editor-Daten (Routen-Kurven + Bauslots) nach js/maps-custom.json.
// Das Spiel lädt diese Datei beim Start und überschreibt damit die
// eingebauten Karten-Daten. Nur lokal (XAMPP) gedacht.
//
// WICHTIG: Vor jedem Überschreiben wird die bisherige Datei automatisch als
// Zeitstempel-Backup nach api/mapbackups/ gesichert so geht nichts verloren.
// Ein leeres {} wird abgelehnt, damit versehentliche Resets nicht speichern.
header('Content-Type: application/json; charset=utf-8');
// Plattform-Guard: Schreiben nur für eingeloggte Lehrpersonen.
// Pfad funktioniert lokal (App/sims/...) UND auf Prod (Top-Level sims/...).
require_once __DIR__ . '/../../../php/config/app.php';
require_once __DIR__ . '/../../../php/lib/Database.php';
require_once __DIR__ . '/../../../php/lib/Response.php';
require_once __DIR__ . '/../../../php/lib/Session.php';
Session::start(); // Session laden, sonst ist $_SESSION leer → Auth-Check wirft immer 401
// Backend-Editor: Admin ODER eingeloggte Lehrperson darf speichern.
if (empty($_SESSION['admin_id']) && !Session::teacherId()) {
http_response_code(401);
echo json_encode(['ok' => false, 'error' => 'Nicht eingeloggt (Admin oder Lehrperson erforderlich).']);
exit;
}
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data) || count($data) === 0) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'invalid or empty json']);
exit;
}
$target = __DIR__ . '/../js/maps-custom.json';
$backupDir = __DIR__ . '/mapbackups';
// vorhandene, nicht-leere Datei zuerst sichern
if (file_exists($target)) {
$old = trim((string)file_get_contents($target));
if ($old !== '' && $old !== '{}') {
if (!is_dir($backupDir)) @mkdir($backupDir, 0777, true);
@copy($target, $backupDir . '/maps-custom-' . date('Ymd-His') . '.json');
@copy($target, $backupDir . '/maps-custom.prev.json'); // schneller Griff aufs letzte
$files = glob($backupDir . '/maps-custom-*.json'); // max. 40 Backups halten
if ($files && count($files) > 40) {
sort($files);
foreach (array_slice($files, 0, count($files) - 40) as $f) @unlink($f);
}
}
}
$ok = file_put_contents($target, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
echo json_encode(['ok' => (bool)$ok, 'file' => 'js/maps-custom.json', 'backed_up' => is_dir($backupDir)]);