An installation that predates the map update has none of the four map tables, so the first query threw an uncaught PDOException and the page answered 500 with an empty body - no hint what was wrong. map.php now checks for the tables up front and shows a setup page instead: it names the missing tables and, for accounts with roles.manage, offers a button that creates them. The statements are extracted from sql/schema.sql at runtime, so the schema file stays the single source of truth and cannot drift from what gets created. They are all CREATE TABLE IF NOT EXISTS, so running it twice is harmless, and doing it by hand in phpMyAdmin remains equivalent. Reproduced against a database built from the pre-update schema: map.php returned 500, now returns 200 with the setup page, the button creates all four tables, and the map renders afterwards. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
365 lines
12 KiB
PHP
365 lines
12 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Datenschicht der Taktikkarte. Anders als Raids/Premades/Reports/Events haengt die Karte
|
|
* nicht am Discord-Bot, sondern liegt komplett in der Website-Datenbank - der Bot kennt
|
|
* weder Kartenkacheln noch Marker.
|
|
*/
|
|
|
|
// Verzeichnis, in dem die gekachelten Karten liegen (je Karte ein Unterordner mit
|
|
// tiles.json + Zoomstufen-Ordnern, erzeugt von tools/make_map_tiles.php).
|
|
const MAP_TILES_DIR = __DIR__ . '/../assets/uploads/maps';
|
|
const MAP_TILES_URL = '/assets/uploads/maps';
|
|
|
|
/**
|
|
* Die Tabellen, die diese Seite braucht - in Anlegereihenfolge (Fremdschluessel!).
|
|
*/
|
|
const MAP_TABLES = ['map_categories', 'map_markers', 'map_tactics', 'map_tactic_shapes'];
|
|
|
|
/**
|
|
* Welche der Kartentabellen fehlen noch? Bei einer Installation, die es schon vor dem
|
|
* Karten-Update gab, sind das alle vier - ohne diese Pruefung wuerde die erste Abfrage
|
|
* mit einer PDOException und damit HTTP 500 aussteigen.
|
|
*
|
|
* @return array<int, string>
|
|
*/
|
|
function map_missing_tables(): array
|
|
{
|
|
$placeholders = implode(',', array_fill(0, count(MAP_TABLES), '?'));
|
|
$stmt = db()->prepare(
|
|
"SELECT table_name FROM information_schema.tables
|
|
WHERE table_schema = DATABASE() AND table_name IN ($placeholders)"
|
|
);
|
|
$stmt->execute(MAP_TABLES);
|
|
|
|
$existing = array_map('strtolower', $stmt->fetchAll(PDO::FETCH_COLUMN));
|
|
|
|
return array_values(array_filter(
|
|
MAP_TABLES,
|
|
static fn (string $table): bool => !in_array(strtolower($table), $existing, true)
|
|
));
|
|
}
|
|
|
|
/**
|
|
* Zieht die CREATE-TABLE-Befehle der Kartentabellen aus sql/schema.sql. Damit gibt es
|
|
* genau eine Quelle fuer die Struktur - das Schema kann nicht von dem abweichen, was
|
|
* hier angelegt wird.
|
|
*
|
|
* @return array<string, string> Tabellenname => SQL-Befehl
|
|
*/
|
|
function map_schema_statements(): array
|
|
{
|
|
$path = __DIR__ . '/../sql/schema.sql';
|
|
if (!is_file($path)) {
|
|
return [];
|
|
}
|
|
|
|
$schema = (string) file_get_contents($path);
|
|
$statements = [];
|
|
foreach (MAP_TABLES as $table) {
|
|
$pattern = '/CREATE TABLE IF NOT EXISTS\s+' . preg_quote($table, '/') . '\s*\(.*?\)\s*ENGINE[^;]*;/s';
|
|
if (preg_match($pattern, $schema, $match) === 1) {
|
|
$statements[$table] = $match[0];
|
|
}
|
|
}
|
|
|
|
return $statements;
|
|
}
|
|
|
|
/**
|
|
* Legt die fehlenden Kartentabellen an. Die Befehle sind alle "IF NOT EXISTS", ein
|
|
* zweiter Aufruf richtet also keinen Schaden an.
|
|
*
|
|
* @return int Anzahl ausgefuehrter Befehle
|
|
* @throws RuntimeException
|
|
*/
|
|
function map_create_tables(): int
|
|
{
|
|
$statements = map_schema_statements();
|
|
if (count($statements) !== count(MAP_TABLES)) {
|
|
throw new RuntimeException(
|
|
'sql/schema.sql wurde nicht gefunden oder enthält nicht alle Kartentabellen - '
|
|
. 'bitte den Abschnitt "Taktikkarte" aus sql/schema.sql von Hand ausführen.'
|
|
);
|
|
}
|
|
|
|
$pdo = db();
|
|
foreach ($statements as $sql) {
|
|
$pdo->exec($sql);
|
|
}
|
|
|
|
return count($statements);
|
|
}
|
|
|
|
/**
|
|
* Liest die verfuegbaren Karten aus dem Kachel-Verzeichnis. Jede Karte beschreibt sich
|
|
* ueber ihre eigene tiles.json selbst, dadurch kommt eine neue Region dazu, ohne dass
|
|
* Code oder Datenbank angefasst werden muessen.
|
|
*
|
|
* @return array<string, array<string, mixed>> Kartenschluessel => Manifest
|
|
*/
|
|
function map_available(): array
|
|
{
|
|
if (!is_dir(MAP_TILES_DIR)) {
|
|
return [];
|
|
}
|
|
|
|
$maps = [];
|
|
foreach (scandir(MAP_TILES_DIR) ?: [] as $entry) {
|
|
if ($entry === '.' || $entry === '..') {
|
|
continue;
|
|
}
|
|
$manifestPath = MAP_TILES_DIR . '/' . $entry . '/tiles.json';
|
|
if (!is_file($manifestPath)) {
|
|
continue;
|
|
}
|
|
|
|
$manifest = json_decode((string) file_get_contents($manifestPath), true);
|
|
if (!is_array($manifest) || empty($manifest['width']) || empty($manifest['height'])) {
|
|
continue;
|
|
}
|
|
|
|
$manifest['key'] = $entry;
|
|
$manifest['name'] = (string) ($manifest['name'] ?? ucfirst($entry));
|
|
$manifest['url_template'] = MAP_TILES_URL . '/' . rawurlencode($entry) . '/{z}/{x}_{y}.'
|
|
. (string) ($manifest['extension'] ?? 'jpg');
|
|
$maps[$entry] = $manifest;
|
|
}
|
|
|
|
ksort($maps);
|
|
return $maps;
|
|
}
|
|
|
|
/**
|
|
* Kategorien als zweistufige Struktur (Gruppen mit ihren Kategorien), inklusive der
|
|
* Marker-Anzahl je Kategorie - genau die Zahlen, die in der Sidebar hinter den Namen
|
|
* stehen.
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
function map_category_tree(string $mapKey): array
|
|
{
|
|
$stmt = db()->prepare(
|
|
'SELECT c.id, c.parent_id, c.name, c.icon, c.color, c.sort_order,
|
|
(SELECT COUNT(*) FROM map_markers m WHERE m.category_id = c.id AND m.map_key = ?) AS marker_count
|
|
FROM map_categories c
|
|
ORDER BY c.sort_order ASC, c.name ASC'
|
|
);
|
|
$stmt->execute([$mapKey]);
|
|
$rows = $stmt->fetchAll();
|
|
|
|
$groups = [];
|
|
$children = [];
|
|
foreach ($rows as $row) {
|
|
if ($row['parent_id'] === null) {
|
|
$row['children'] = [];
|
|
$row['total_count'] = 0;
|
|
$groups[(int) $row['id']] = $row;
|
|
} else {
|
|
$children[(int) $row['parent_id']][] = $row;
|
|
}
|
|
}
|
|
|
|
foreach ($groups as $id => $group) {
|
|
$groupChildren = $children[$id] ?? [];
|
|
$groups[$id]['children'] = $groupChildren;
|
|
$groups[$id]['total_count'] = array_sum(array_map(
|
|
fn (array $child): int => (int) $child['marker_count'],
|
|
$groupChildren
|
|
));
|
|
}
|
|
|
|
// Kategorien, deren Gruppe geloescht wurde, waeren sonst unsichtbar.
|
|
$orphans = [];
|
|
foreach ($children as $parentId => $list) {
|
|
if (!isset($groups[$parentId])) {
|
|
$orphans = array_merge($orphans, $list);
|
|
}
|
|
}
|
|
if (!empty($orphans)) {
|
|
$groups[0] = [
|
|
'id' => 0,
|
|
'parent_id' => null,
|
|
'name' => 'Ohne Gruppe',
|
|
'icon' => '',
|
|
'color' => '#a0a0a0',
|
|
'sort_order' => 9999,
|
|
'children' => $orphans,
|
|
'total_count' => array_sum(array_map(fn (array $c): int => (int) $c['marker_count'], $orphans)),
|
|
];
|
|
}
|
|
|
|
return array_values($groups);
|
|
}
|
|
|
|
/**
|
|
* Alle Marker einer Karte, fertig fuer die Uebergabe an das Frontend.
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
function map_markers(string $mapKey): array
|
|
{
|
|
$stmt = db()->prepare(
|
|
'SELECT m.id, m.category_id, m.name, m.description, m.pos_x, m.pos_y,
|
|
u.display_name, u.username
|
|
FROM map_markers m
|
|
LEFT JOIN users u ON u.id = m.created_by
|
|
WHERE m.map_key = ?
|
|
ORDER BY m.id ASC'
|
|
);
|
|
$stmt->execute([$mapKey]);
|
|
|
|
return array_map(static function (array $row): array {
|
|
$author = trim((string) ($row['display_name'] ?? '')) !== ''
|
|
? (string) $row['display_name']
|
|
: (string) ($row['username'] ?? '');
|
|
|
|
return [
|
|
'id' => (int) $row['id'],
|
|
'category_id' => (int) $row['category_id'],
|
|
'name' => (string) $row['name'],
|
|
'description' => (string) ($row['description'] ?? ''),
|
|
'x' => (float) $row['pos_x'],
|
|
'y' => (float) $row['pos_y'],
|
|
'author' => $author,
|
|
];
|
|
}, $stmt->fetchAll());
|
|
}
|
|
|
|
/**
|
|
* Taktiken einer Karte samt ihrer Zeichenobjekte.
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
function map_tactics(string $mapKey): array
|
|
{
|
|
$stmt = db()->prepare(
|
|
'SELECT t.id, t.name, t.description, t.updated_at, t.created_at, u.display_name, u.username
|
|
FROM map_tactics t
|
|
LEFT JOIN users u ON u.id = t.created_by
|
|
WHERE t.map_key = ?
|
|
ORDER BY t.name ASC'
|
|
);
|
|
$stmt->execute([$mapKey]);
|
|
$tactics = $stmt->fetchAll();
|
|
|
|
if (empty($tactics)) {
|
|
return [];
|
|
}
|
|
|
|
$ids = array_map(fn (array $t): int => (int) $t['id'], $tactics);
|
|
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
|
$shapeStmt = db()->prepare(
|
|
"SELECT id, tactic_id, shape_type, label, color, points, sort_order
|
|
FROM map_tactic_shapes WHERE tactic_id IN ($placeholders)
|
|
ORDER BY sort_order ASC, id ASC"
|
|
);
|
|
$shapeStmt->execute($ids);
|
|
|
|
$shapesByTactic = [];
|
|
foreach ($shapeStmt->fetchAll() as $shape) {
|
|
$points = json_decode((string) $shape['points'], true);
|
|
$shapesByTactic[(int) $shape['tactic_id']][] = [
|
|
'id' => (int) $shape['id'],
|
|
'type' => (string) $shape['shape_type'],
|
|
'label' => (string) $shape['label'],
|
|
'color' => (string) $shape['color'],
|
|
'points' => is_array($points) ? $points : [],
|
|
];
|
|
}
|
|
|
|
return array_map(static function (array $tactic) use ($shapesByTactic): array {
|
|
$author = trim((string) ($tactic['display_name'] ?? '')) !== ''
|
|
? (string) $tactic['display_name']
|
|
: (string) ($tactic['username'] ?? '');
|
|
|
|
return [
|
|
'id' => (int) $tactic['id'],
|
|
'name' => (string) $tactic['name'],
|
|
'description' => (string) ($tactic['description'] ?? ''),
|
|
'author' => $author,
|
|
'updated_at' => (string) ($tactic['updated_at'] ?? $tactic['created_at'] ?? ''),
|
|
'shapes' => $shapesByTactic[(int) $tactic['id']] ?? [],
|
|
];
|
|
}, $tactics);
|
|
}
|
|
|
|
/**
|
|
* Startbestueckung der Kategorien, angelehnt an die Gliederung gaengiger Aion-Karten.
|
|
* Wird nur angeboten, solange ueberhaupt keine Kategorie existiert - danach pflegt ihr
|
|
* die Liste selbst.
|
|
*
|
|
* @return array<int, array{name: string, icon: string, color: string, children: array<int, array{0: string, 1: string}>}>
|
|
*/
|
|
function map_default_categories(): array
|
|
{
|
|
return [
|
|
['name' => 'Orte', 'icon' => '🏰', 'color' => '#c9a227', 'children' => [
|
|
['Siedlung', '🏘'], ['Region', '🚩'], ['Festung', '🛡'], ['Dungeon', '🕳'], ['Rift', '🌀'],
|
|
]],
|
|
['name' => 'Sammelbares', 'icon' => '💠', 'color' => '#4fc3f7', 'children' => [
|
|
['Empyreische Spur', '✨'], ['Versteckter Würfel', '🎁'], ['Boss', '💀'],
|
|
]],
|
|
['name' => 'NPCs', 'icon' => '🧝', 'color' => '#81c784', 'children' => [
|
|
['Händler', '💰'], ['Handwerksstation', '⚒'], ['Lagerverwalter', '📦'], ['Instanz-Eingang', '🚪'],
|
|
]],
|
|
['name' => 'Quests', 'icon' => '📜', 'color' => '#ffb74d', 'children' => [
|
|
['Regionsquest', '❗'], ['Story-Quest', '📖'],
|
|
]],
|
|
['name' => 'Ressourcen', 'icon' => '⛏', 'color' => '#a1887f', 'children' => [
|
|
['Erz', '⛏'], ['Edelstein', '💎'], ['Holz', '🪵'], ['Kraut', '🌿'],
|
|
]],
|
|
['name' => 'Monster', 'icon' => '🐉', 'color' => '#e57373', 'children' => [
|
|
['Namhafter Boss', '👑'], ['Elite', '⚔'], ['Normal', '🐾'],
|
|
]],
|
|
['name' => 'Gilde', 'icon' => '⚜', 'color' => '#ba68c8', 'children' => [
|
|
['Sammelpunkt', '📍'], ['Eigene Notiz', '📝'],
|
|
]],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Legt die Standard-Kategorien an. Gibt die Anzahl der erzeugten Kategorien zurueck.
|
|
*/
|
|
function map_seed_default_categories(): int
|
|
{
|
|
$pdo = db();
|
|
$created = 0;
|
|
$sort = 0;
|
|
|
|
foreach (map_default_categories() as $group) {
|
|
$sort += 10;
|
|
$stmt = $pdo->prepare('INSERT INTO map_categories (parent_id, name, icon, color, sort_order) VALUES (NULL, ?, ?, ?, ?)');
|
|
$stmt->execute([$group['name'], $group['icon'], $group['color'], $sort]);
|
|
$groupId = (int) $pdo->lastInsertId();
|
|
$created++;
|
|
|
|
$childSort = 0;
|
|
foreach ($group['children'] as $child) {
|
|
$childSort += 10;
|
|
$childStmt = $pdo->prepare('INSERT INTO map_categories (parent_id, name, icon, color, sort_order) VALUES (?, ?, ?, ?, ?)');
|
|
$childStmt->execute([$groupId, $child[0], $child[1], $group['color'], $childSort]);
|
|
$created++;
|
|
}
|
|
}
|
|
|
|
return $created;
|
|
}
|
|
|
|
/**
|
|
* Prueft eine normierte Koordinate (0..1). Alles ausserhalb waere ausserhalb des
|
|
* Kartenbildes und damit unerreichbar.
|
|
*/
|
|
function map_valid_coordinate($value): bool
|
|
{
|
|
return is_numeric($value) && (float) $value >= 0.0 && (float) $value <= 1.0;
|
|
}
|
|
|
|
/**
|
|
* Prueft eine Farbangabe im Format #rrggbb.
|
|
*/
|
|
function map_valid_color(string $color): bool
|
|
{
|
|
return preg_match('/^#[0-9a-fA-F]{6}$/', $color) === 1;
|
|
}
|