LuminaWebsite/includes/map_build.php
Maaxxs 52fea9f92d Karte: build a map from an image right on the page
Pick an image, press "Karte bauen", done - no FTP, no command line tool.
The panel sits on the setup page while no map exists and under the map as
"Karte neu bauen" afterwards.

The tiles are cut in the browser and only the finished 256px JPEGs are
uploaded. That is the point: on ordinary shared hosting a 50MB map image
runs into upload_max_filesize, cutting it server side runs into memory_limit
and max_execution_time, and GD is not installed everywhere. This way the
server needs none of it - it validates small JPEGs and stores them.

Uploads go into a side folder <key>__build that only replaces the live map
once every tile has arrived, so an abort - by button, by error or by closing
the browser - leaves the existing map untouched.

The server trusts nothing from the client: the key must match a strict
pattern, tile coordinates must lie inside 2^z on their level, and each file
is checked with getimagesize for an actual JPEG within a size limit before it
is stored.

Verified against tools/make_map_tiles.php on the same source image: same zoom
levels, same per-level tile counts (1/4/12/40), same tile names, same
manifest.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 14:57:11 +02:00

274 lines
9 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/map.php';
/**
* Serverseite des Karten-Bauens.
*
* Geschnitten werden die Kacheln im Browser (siehe assets/js/map_build.js) - hier kommen
* nur noch fertige 256er-JPEGs an, die geprueft und abgelegt werden. Das ist Absicht:
* ein grosses Kartenbild serverseitig zu zerlegen scheitert auf typischem Webspace an
* memory_limit, max_execution_time, fehlendem GD oder upload_max_filesize. So braucht
* der Server nichts davon.
*
* Gebaut wird immer in einen Nebenordner "<schluessel>__build"; erst wenn alle Kacheln
* oben sind, tritt er an die Stelle der alten Karte. Bricht der Vorgang ab, bleibt die
* bisherige Karte unangetastet.
*/
const MAP_BUILD_SUFFIX = '__build';
/** Obergrenze je hochgeladener Kachel - 256x256 JPEG liegt weit darunter. */
const MAP_BUILD_MAX_TILE_BYTES = 512 * 1024;
/** Schutz vor absurden Angaben; 12 Stufen waeren ein 1-Million-Pixel-Quadrat. */
const MAP_BUILD_MAX_ZOOM = 12;
/**
* Prueft einen Kartenschluessel. Er wird zu einem Ordnernamen, darf also nichts
* enthalten, was aus dem Kartenverzeichnis herausfuehren koennte.
*/
function map_build_valid_key(string $key): bool
{
return preg_match('/^[a-z0-9][a-z0-9_-]{0,48}$/', $key) === 1;
}
function map_build_dir(string $key): string
{
return MAP_TILES_DIR . '/' . $key . MAP_BUILD_SUFFIX;
}
function map_build_state_path(string $key): string
{
return map_build_dir($key) . '/build.json';
}
/**
* @return array<string, mixed>|null
*/
function map_build_state(string $key): ?array
{
$path = map_build_state_path($key);
if (!is_file($path)) {
return null;
}
$state = json_decode((string) file_get_contents($path), true);
return is_array($state) ? $state : null;
}
/**
* Legt den Bauordner an (ein eventuell vorhandener Rest wird verworfen) und merkt sich,
* was am Ende in die tiles.json gehoert.
*
* @throws RuntimeException
*/
function map_build_begin(string $key, string $name, int $width, int $height, int $tileSize, int $maxZoom): void
{
if (!map_build_valid_key($key)) {
throw new RuntimeException('Ungültiger Kartenschlüssel (erlaubt: a-z, 0-9, - und _).');
}
if ($width < 1 || $height < 1 || $width > 200000 || $height > 200000) {
throw new RuntimeException('Unplausible Bildgröße.');
}
if ($tileSize < 64 || $tileSize > 1024) {
throw new RuntimeException('Ungültige Kachelgröße.');
}
if ($maxZoom < 0 || $maxZoom > MAP_BUILD_MAX_ZOOM) {
throw new RuntimeException('Ungültige Anzahl Zoomstufen.');
}
$dir = map_build_dir($key);
if (is_dir($dir)) {
map_build_remove_dir($dir);
}
if (!mkdir($dir, 0775, true) && !is_dir($dir)) {
throw new RuntimeException('Der Ordner für die Karte konnte nicht angelegt werden. '
. 'Ist assets/uploads/maps/ für den Webserver beschreibbar?');
}
$state = [
'key' => $key,
'name' => $name !== '' ? $name : ucfirst($key),
'width' => $width,
'height' => $height,
'tile_size' => $tileSize,
'min_zoom' => 0,
'max_zoom' => $maxZoom,
'extension' => 'jpg',
'tiles_written' => 0,
'started_at' => date('c'),
];
file_put_contents(map_build_state_path($key), json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
/**
* Nimmt eine hochgeladene Kachel entgegen.
*
* @param array<string, mixed> $file Ein Eintrag aus $_FILES
* @throws RuntimeException
*/
function map_build_store_tile(array $state, array $file, int $z, int $x, int $y): void
{
$key = (string) $state['key'];
$maxZoom = (int) $state['max_zoom'];
if ($z < 0 || $z > $maxZoom) {
throw new RuntimeException("Zoomstufe $z liegt außerhalb der Karte.");
}
// Auf jeder Stufe gibt es hoechstens 2^z Kacheln je Achse - alles darueber waere
// ein Versuch, irgendwohin sonst zu schreiben.
$limit = 1 << $z;
if ($x < 0 || $y < 0 || $x >= $limit || $y >= $limit) {
throw new RuntimeException("Kachel $z/$x/$y liegt außerhalb der Karte.");
}
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new RuntimeException("Kachel $z/$x/$y wurde nicht vollständig übertragen.");
}
if (($file['size'] ?? 0) > MAP_BUILD_MAX_TILE_BYTES) {
throw new RuntimeException("Kachel $z/$x/$y ist zu groß.");
}
$tmp = (string) ($file['tmp_name'] ?? '');
if (!is_uploaded_file($tmp)) {
throw new RuntimeException('Ungültiger Upload.');
}
// Nicht dem Dateinamen oder dem gemeldeten Typ trauen, sondern den Inhalt ansehen.
$info = @getimagesize($tmp);
if ($info === false || $info[2] !== IMAGETYPE_JPEG) {
throw new RuntimeException("Kachel $z/$x/$y ist kein JPEG.");
}
if ($info[0] > 1024 || $info[1] > 1024) {
throw new RuntimeException("Kachel $z/$x/$y hat unerwartete Maße.");
}
$zoomDir = map_build_dir($key) . '/' . $z;
if (!is_dir($zoomDir) && !mkdir($zoomDir, 0775, true) && !is_dir($zoomDir)) {
throw new RuntimeException("Ordner für Zoomstufe $z konnte nicht angelegt werden.");
}
if (!move_uploaded_file($tmp, $zoomDir . '/' . $x . '_' . $y . '.jpg')) {
throw new RuntimeException("Kachel $z/$x/$y konnte nicht gespeichert werden.");
}
}
/** Zaehlt die abgelegten Kacheln im Bauordner mit. */
function map_build_count(string $key, int $written): void
{
$state = map_build_state($key);
if ($state === null) {
return;
}
$state['tiles_written'] = (int) ($state['tiles_written'] ?? 0) + $written;
file_put_contents(map_build_state_path($key), json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
/**
* Schliesst den Bau ab: tiles.json schreiben und den Bauordner an die Stelle der alten
* Karte setzen. Erst hier wird die bisherige Karte ersetzt.
*
* @throws RuntimeException
*/
function map_build_finish(string $key): int
{
$state = map_build_state($key);
if ($state === null) {
throw new RuntimeException('Zu dieser Karte läuft kein Bauvorgang.');
}
$manifest = [
'name' => $state['name'],
'width' => (int) $state['width'],
'height' => (int) $state['height'],
'tile_size' => (int) $state['tile_size'],
'min_zoom' => (int) $state['min_zoom'],
'max_zoom' => (int) $state['max_zoom'],
'extension' => 'jpg',
'generated_at' => date('c'),
];
$buildDir = map_build_dir($key);
file_put_contents(
$buildDir . '/tiles.json',
json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);
@unlink(map_build_state_path($key));
$target = MAP_TILES_DIR . '/' . $key;
if (is_dir($target)) {
// Erst zur Seite schieben, damit bei einem Fehler beim Umbenennen nicht beide
// Stände weg sind.
$retired = $target . '__old_' . bin2hex(random_bytes(4));
if (!rename($target, $retired)) {
throw new RuntimeException('Die bisherige Karte konnte nicht ersetzt werden (Schreibrechte?).');
}
if (!rename($buildDir, $target)) {
rename($retired, $target);
throw new RuntimeException('Die neue Karte konnte nicht aktiviert werden (Schreibrechte?).');
}
map_build_remove_dir($retired);
} elseif (!rename($buildDir, $target)) {
throw new RuntimeException('Die neue Karte konnte nicht aktiviert werden (Schreibrechte?).');
}
return (int) ($state['tiles_written'] ?? 0);
}
/** Bricht einen Bauvorgang ab und raeumt den Nebenordner weg. */
function map_build_abort(string $key): void
{
if (!map_build_valid_key($key)) {
return;
}
$dir = map_build_dir($key);
if (is_dir($dir)) {
map_build_remove_dir($dir);
}
}
/**
* Loescht ein Verzeichnis samt Inhalt. Bewusst eng gehalten: nur innerhalb des
* Kartenverzeichnisses, keine Symlinks.
*/
function map_build_remove_dir(string $dir): void
{
$base = realpath(MAP_TILES_DIR);
$real = realpath($dir);
if ($base === false || $real === false || !str_starts_with($real, $base . DIRECTORY_SEPARATOR)) {
return;
}
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($real, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($items as $item) {
if ($item->isDir() && !$item->isLink()) {
@rmdir($item->getPathname());
} else {
@unlink($item->getPathname());
}
}
@rmdir($real);
}
/**
* Wie viele Kacheln ein Bild ergibt - fuer die Fortschrittsanzeige und um dem Nutzer
* vorab zu sagen, worauf er sich einlaesst.
*/
function map_build_tile_count(int $width, int $height, int $tileSize, int $maxZoom): int
{
$total = 0;
for ($z = 0; $z <= $maxZoom; $z++) {
$scale = 2 ** ($z - $maxZoom);
$levelWidth = max(1, (int) round($width * $scale));
$levelHeight = max(1, (int) round($height * $scale));
$total += (int) (ceil($levelWidth / $tileSize) * ceil($levelHeight / $tileSize));
}
return $total;
}