Karte: tactical map tab with own markers and tactic layers

New "Karte" tab: a tiled zoom/pan map of the game world with a category
sidebar (groups, per-category marker counts, show all / hide all, search)
and marker popups, plus tactic layers drawn on top of it.

Markers are placed by clicking the map (map.manage) and live in freely
editable two-level categories, each with its own emoji and colour. A tactic
(map.tactics) is a separate drawing layer that can be toggled on and off:
rally points, dashed routes, areas and text notes in any colour, finished by
double click, an explicit button or Enter, removed by clicking them.

Coordinates are stored as a fraction of the map's width/height rather than
in pixels, so re-tiling the map at a different resolution never moves
anything.

The map data lives entirely in the website database - the Discord bot is not
involved. tools/make_map_tiles.php slices a high-resolution image into the
zoom pyramid locally; the resulting folder is uploaded by FTP and picked up
automatically, one region per folder. Leaflet 1.9.4 is vendored under
assets/vendor/ so there is still no CDN and no build step.

New permissions map.view / map.manage / map.tactics and four new tables -
existing installs have to add both once (see README).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Maaxxs 2026-09-20 13:25:12 +02:00
parent 300dae4263
commit 6b5661dd53
22 changed files with 3250 additions and 3 deletions

3
.gitignore vendored
View file

@ -2,3 +2,6 @@ config.php
assets/uploads/avatars/*
!assets/uploads/avatars/.htaccess
!assets/uploads/avatars/.gitkeep
assets/uploads/maps/*
!assets/uploads/maps/.htaccess
!assets/uploads/maps/.gitkeep

View file

@ -18,6 +18,8 @@ und wird später ausgebaut. Fokus dieser Version ist der Mitglieder-/Admin-Berei
- Jeder Benutzer kann mehreren Berechtigungsgruppen angehören
- Events-Seite: geplante (wiederkehrende) Event-Erinnerungen des Bots ansehen, anlegen,
bearbeiten und löschen - synchron mit `/event_planen` / `/event_liste` im Discord
- Taktikkarte: gekachelte Zoom-Karte der Spielwelt mit eigenen Markern (Kategorien, Filter,
Suche) und Taktik-Ebenen zum Einzeichnen von Sammelpunkten, Routen, Zonen und Notizen
- Raids-Seite: zeigt anstehende Raid-Termine, Anforderungen, Gruppen und Anmeldungen,
bezogen von einer externen API (`config.php: raids_api`), Filter Aktiv/Archiviert/Alle
- "Mein Profil"-Seite: Anzeigename ändern, Passwort ändern, Discord-Verknüpfung verwalten
@ -36,7 +38,8 @@ sql/schema.sql Datenbankstruktur zum Import (z.B. via phpMyAdmin)
includes/ PHP-Logik (Datenbank, Auth, Berechtigungen, Layout)
index.php, login.php, ... Öffentlich aufrufbare Seiten
admin/ Admin-Bereich (Benutzerverwaltung, Berechtigungsgruppen)
assets/ CSS
assets/ CSS, JS, Bilder, mitgelieferte Bibliotheken (assets/vendor/)
tools/ Hilfsscripte für die Kommandozeile (z.B. Kartenkacheln erzeugen)
```
Alles liegt in einem einzigen Verzeichnis, das direkt als Dokumentenstamm/Document Root der
@ -254,6 +257,71 @@ Das Feature braucht eine Erweiterung der Bot-API (`PATCH /api/events/{id}` zum B
Bot-Repos (Aion2_RaidPlaner), nicht dieses hier. Nach dem Deployen der Bot-Änderung muss der
Bot-Prozess neu gestartet werden.
### Taktikkarte
Eine zoom- und verschiebbare Karte der Spielwelt mit eigenen Markern und darüber liegenden
Taktik-Ebenen. Vorbild ist die Bedienung gängiger interaktiver Aion-Karten: links eine Sidebar
mit Kategorien (gruppiert, mit Marker-Anzahl hinter jedem Eintrag), Häkchen pro Kategorie bzw.
Gruppe, "Alle einblenden"/"Alle ausblenden" und eine Suche; rechts die Karte mit Marker-Popups.
Wichtig: Diese Seite bringt die **Mechanik** mit, nicht die Daten. Kartenmaterial und Marker
pflegt ihr selbst - aus fremden Karten-Seiten werden weder Kacheln noch Marker übernommen.
**Marker.** Mitglieder mit `map.manage` aktivieren oben "Marker setzen" und klicken auf die
Karte; im Popup werden Name, Kategorie und eine optionale Beschreibung erfasst. Bestehende
Marker lassen sich über ihr Popup bearbeiten oder löschen. Die Kategorien sind zweistufig
(Gruppe -> Kategorie) und komplett frei anlegbar, jeweils mit Symbol (Emoji) und Farbe, die
zusammen die Marker-Nadel ergeben. Solange noch keine Kategorie existiert, gibt es einen
Knopf, der eine Startgliederung (Orte, Sammelbares, NPCs, Quests, Ressourcen, Monster, Gilde)
anlegt - danach ist alles frei änderbar.
**Taktiken.** Eine Taktik ist eine eigene Zeichenebene über der Karte, die sich unabhängig
ein- und ausblenden lässt - z.B. eine pro Festungskampf oder Raid-Route. Mitglieder mit
`map.tactics` legen eine Taktik an und zeichnen dann Sammelpunkte, Routen (gestrichelte
Linien), Flächen und Textnotizen in frei wählbaren Farben. Routen und Flächen werden per
Doppelklick, über den Knopf "Abschließen" oder mit Enter beendet, Esc bricht ab; ein Klick auf
ein vorhandenes Objekt löscht es (mit Rückfrage). Beschriftung und Farbe kommen jeweils aus
einem kleinen Dialog.
Marker- und Taktik-Koordinaten werden als Anteil der Kartenbreite/-höhe gespeichert (0..1),
nicht in Pixeln. Ein später neu gekacheltes oder höher aufgelöstes Kartenbild verschiebt
deshalb nichts.
Neue Berechtigungen: `map.view` (Karte und Taktiken ansehen), `map.manage` (Marker und
Kategorien verwalten) und `map.tactics` (Taktiken anlegen/bearbeiten) müssen bei einem vor
diesem Update installierten Account nachträglich unter Berechtigungsgruppen angelegt und
zugewiesen werden.
Die Karte läuft komplett in der Website-Datenbank, der Discord-Bot ist daran nicht beteiligt.
Für eine bestehende Datenbank fehlen die vier Tabellen - einmalig nachziehen (der Abschnitt
"Taktikkarte" am Ende von `sql/schema.sql` enthält genau diese `CREATE TABLE`-Befehle).
Die Kartendarstellung nutzt [Leaflet](https://leafletjs.com) 1.9.4, das unter
`assets/vendor/leaflet/` mitgeliefert wird (kein CDN, kein Build-Schritt, keine externe
Abhängigkeit zur Laufzeit).
#### Kartenbild kacheln
Die Karte wird als Kachel-Pyramide ausgeliefert: mehrere Zoomstufen aus einem hoch aufgelösten
Bild, damit sie auch nah herangezoomt scharf bleibt und nie das ganze Bild auf einmal geladen
werden muss. Erzeugt wird sie einmalig lokal (nicht auf dem Webspace):
```
php -d memory_limit=2G tools/make_map_tiles.php verteron "C:\Bilder\verteron.png" --name="Verteron"
```
Der erste Parameter ist der Kartenschlüssel (nur Kleinbuchstaben/Ziffern/`-`/`_`), der zweite
das Quellbild (PNG, JPEG oder WebP). Optional: `--name=` für den angezeigten Namen,
`--tile-size=` (Standard 256) und `--quality=` (JPEG-Qualität, Standard 82). Das Script
braucht die PHP-Erweiterung GD.
Das Ergebnis landet in `assets/uploads/maps/<schlüssel>/` (ein Ordner je Zoomstufe plus eine
`tiles.json`) und wird per FTP genau dorthin auf den Webspace geladen. Mehr ist nicht nötig:
`map.php` findet jeden Unterordner mit einer `tiles.json` von allein. Liegen mehrere Karten
dort, erscheint oben in der Sidebar automatisch eine Auswahlliste - eine Region pro Ordner.
Die Kacheln selbst sind bewusst von Git ausgenommen (`.gitignore`), damit das Repository nicht
mit hunderten Bilddateien vollläuft.
### Mitgliederliste
Zeigt alle aktiven Gildenmitglieder mit Profilbild und Rollen. Unter Berechtigungsgruppen ->

View file

@ -1892,3 +1892,388 @@ input.role-weight-input {
margin-top: 0.8rem;
font-size: 0.85rem;
}
/* --- Taktikkarte --- */
.app-content.bg-map {
background-image: linear-gradient(rgba(20, 20, 20, 0.72), rgba(20, 20, 20, 0.85)), url('/assets/images/Landscapes/web/landscape8-bg.jpg');
}
/* Die Karte braucht mehr Platz als die 1100px der normalen Inhaltsspalte. */
.container-wide { max-width: 1600px; }
.map-page {
display: grid;
grid-template-columns: 300px minmax(0, 1fr);
gap: 1rem;
align-items: start;
}
.map-sidebar {
background: rgba(35, 35, 35, 0.72);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border: 1px solid var(--border);
border-radius: 10px;
padding: 1rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
max-height: calc(100vh - 4rem);
position: sticky;
top: 2rem;
}
.map-sidebar-head { display: flex; flex-direction: column; gap: 0.6rem; }
.map-sidebar-head h1 { margin: 0; font-size: 1.4rem; }
.map-bulk-actions { display: flex; gap: 0.5rem; }
.map-bulk-actions button { flex: 1; font-size: 0.8rem; padding: 0.4rem 0.5rem; }
.map-tabs {
display: flex;
gap: 0.35rem;
border-bottom: 1px solid var(--border);
padding-bottom: 0.5rem;
}
.map-tab {
flex: 1;
background: transparent;
border: 1px solid transparent;
border-radius: 6px;
color: var(--text-muted);
padding: 0.4rem 0.5rem;
font-size: 0.85rem;
cursor: pointer;
}
.map-tab:hover { color: var(--text); }
.map-tab.active { background: rgba(201, 162, 39, 0.15); color: var(--gold); border-color: var(--gold); }
.map-tab-count {
display: inline-block;
margin-left: 0.3rem;
padding: 0 0.35rem;
border-radius: 999px;
background: var(--bg-panel-alt);
font-size: 0.72rem;
}
/* Nur die Liste scrollt, Kopf und Reiter bleiben stehen. Wie bei .modal-overlay
muss die Sichtbarkeit ueber :not([hidden]) laufen, sonst wuerde "display: flex"
das "hidden"-Attribut ueberstimmen und beide Reiter waeren gleichzeitig offen. */
.map-panel { display: none; }
.map-panel:not([hidden]) {
overflow-y: auto;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.map-empty { text-align: center; padding: 1rem 0; }
.map-hint { font-size: 0.78rem; margin-top: 0.6rem; }
.map-group { border-bottom: 1px solid rgba(61, 61, 61, 0.5); padding-bottom: 0.35rem; }
.map-group[hidden] { display: none; }
.map-group:last-child { border-bottom: none; }
.map-group-head {
display: flex;
align-items: center;
gap: 0.35rem;
padding: 0.3rem 0;
}
.map-group-toggle {
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
padding: 0;
display: flex;
transition: transform 0.15s ease;
}
.map-group.collapsed .map-group-toggle { transform: rotate(-90deg); }
.map-group.collapsed .map-group-children { display: none; }
.map-group-label,
.map-category-label {
display: flex;
align-items: center;
gap: 0.45rem;
flex: 1;
min-width: 0;
cursor: pointer;
font-size: 0.88rem;
}
.map-group-label { font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.04em; }
.map-group-label input,
.map-category-label input { width: auto; flex-shrink: 0; margin: 0; }
.map-group-name,
.map-category-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.map-group-children { padding-left: 1.1rem; }
.map-category {
display: flex;
align-items: center;
gap: 0.35rem;
padding: 0.15rem 0;
}
/* Die Suche blendet nicht passende Kategorien per "hidden" aus - ohne diese Regel
wuerde "display: flex" das ueberstimmen (wie bei .modal-overlay). */
.map-category[hidden] { display: none; }
.map-category-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 50%;
font-size: 0.7rem;
flex-shrink: 0;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35) inset;
}
.map-count {
font-size: 0.72rem;
color: var(--text-muted);
flex-shrink: 0;
font-variant-numeric: tabular-nums;
}
.map-category .icon-button,
.map-group-head .icon-button { padding: 0.15rem; opacity: 0; }
.map-category:hover .icon-button,
.map-group-head:hover .icon-button { opacity: 1; }
.map-category .icon-button .icon,
.map-group-head .icon-button .icon { width: 14px; height: 14px; }
.map-add-category,
.map-add-tactic { margin-top: 0.5rem; font-size: 0.82rem; }
.map-tactic {
display: flex;
align-items: center;
gap: 0.35rem;
padding: 0.35rem 0.4rem;
border-radius: 6px;
border: 1px solid transparent;
}
.map-tactic:hover { background: var(--bg-panel-alt); }
.map-tactic.editing { border-color: var(--gold); background: rgba(201, 162, 39, 0.12); }
.map-tactic-label { display: flex; align-items: center; gap: 0.45rem; flex: 1; min-width: 0; cursor: pointer; font-size: 0.88rem; }
.map-tactic-label input { width: auto; flex-shrink: 0; margin: 0; }
.map-tactic-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* --- Kartenflaeche --- */
.map-stage {
background: rgba(35, 35, 35, 0.72);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border: 1px solid var(--border);
border-radius: 10px;
padding: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.map-toolbar {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.map-toolbar-spacer { flex: 1; }
.map-tool {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.4rem 0.7rem;
background: var(--bg-panel-alt);
border: 1px solid var(--border);
border-radius: 6px;
color: var(--text);
font-size: 0.82rem;
cursor: pointer;
}
/* Wie bei .modal-overlay: "display: inline-flex" wuerde das "hidden"-Attribut
ueberstimmen, deshalb hier explizit ausblenden. */
.map-tool[hidden] { display: none; }
.map-tool:hover { border-color: var(--gold); color: var(--gold); }
.map-tool.active { background: rgba(201, 162, 39, 0.2); border-color: var(--gold); color: var(--gold); }
.map-tool-finish { border-color: var(--success); color: var(--success); }
.map-tool-finish:hover { background: rgba(76, 175, 80, 0.15); border-color: var(--success); color: var(--success); }
.map-tool .icon { width: 16px; height: 16px; }
.map-tool-group { display: none; }
.map-tool-group:not([hidden]) {
display: flex;
align-items: center;
gap: 0.4rem;
flex-wrap: wrap;
padding: 0.3rem 0.5rem;
border: 1px dashed var(--gold);
border-radius: 8px;
}
.map-tool-group-label { font-size: 0.8rem; color: var(--gold); font-weight: 600; margin-right: 0.2rem; }
.map-tool-group input[type="color"] {
width: 34px;
height: 30px;
padding: 2px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg-panel-alt);
cursor: pointer;
}
.map-coords {
font-size: 0.78rem;
color: var(--text-muted);
font-variant-numeric: tabular-nums;
min-width: 5.5rem;
text-align: right;
}
.map-canvas {
height: calc(100vh - 12rem);
min-height: 420px;
border-radius: 8px;
border: 1px solid var(--border);
overflow: hidden;
}
/* Leaflet faerbt seinen Container per Default hellgrau. Dieselbe Farbe wie die
aufgefuellten Randkacheln (siehe tools/make_map_tiles.php) laesst den Rand der
Karte nahtlos in die Flaeche uebergehen. */
.map-canvas.leaflet-container { background: #14161a; }
.map-canvas.map-placing { cursor: crosshair; }
.map-status { margin: 0; font-size: 0.8rem; min-height: 1.2em; }
.map-setup-steps { line-height: 1.9; }
.map-setup-steps code { word-break: break-all; }
/* --- Marker und Taktik-Objekte auf der Karte --- */
.map-marker-icon { background: none; border: none; }
.map-marker-pin {
display: flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border-radius: 50% 50% 50% 4px;
transform: rotate(-45deg);
border: 2px solid rgba(0, 0, 0, 0.55);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
}
.map-marker-glyph { transform: rotate(45deg); font-size: 12px; line-height: 1; }
.map-marker-icon:hover .map-marker-pin { filter: brightness(1.25); }
/* Treffer der Suche bleiben sichtbar, alles andere wird nur gedaempft, damit
der Zusammenhang auf der Karte erhalten bleibt. Anklickbar sind die gedaempften
Marker dann aber nicht mehr - sonst faengt man sie beim Klick auf einen Treffer ab. */
.map-marker-filtered { opacity: 0.18; pointer-events: none; }
.map-shape-point { background: none; border: none; }
.map-shape-dot {
display: block;
width: 18px;
height: 18px;
border-radius: 50%;
border: 2px solid rgba(0, 0, 0, 0.6);
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.25);
}
.map-shape-label,
.map-shape-text span {
display: inline-block;
margin-top: 3px;
padding: 1px 6px;
background: rgba(20, 20, 20, 0.85);
border: 1px solid var(--border);
border-radius: 4px;
font-size: 11px;
color: var(--text);
white-space: nowrap;
}
.map-shape-text { background: none; border: none; }
.map-shape-text span { border-width: 2px; font-size: 12px; }
/* Leaflet-Popups an das dunkle Theme anpassen. */
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
background: var(--bg-panel);
color: var(--text);
border: 1px solid var(--border);
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.5);
}
.leaflet-popup-content { margin: 0.7rem 0.9rem; font-size: 0.85rem; }
.leaflet-container a.leaflet-popup-close-button { color: var(--text-muted); }
/* Leaflet misst die Popup-Breite an der natuerlichen Breite des Inhalts. Da der
Beschreibungstext umbrechen darf, waere die gemessene Breite sonst nur so breit
wie das laengste Wort - deshalb eine sinnvolle Mindestbreite vorgeben. */
.map-popup { min-width: 190px; max-width: 260px; }
.map-popup-title { display: block; font-size: 0.95rem; }
.map-popup-category { color: var(--text-muted); font-size: 0.78rem; margin-bottom: 0.4rem; }
.map-popup-text { white-space: pre-wrap; }
.map-popup-author { color: var(--text-muted); font-size: 0.75rem; margin-top: 0.4rem; }
.map-popup-edit {
margin-top: 0.6rem;
padding: 0.25rem 0.6rem;
font-size: 0.78rem;
background: var(--bg-panel-alt);
border: 1px solid var(--border);
border-radius: 5px;
color: var(--text);
cursor: pointer;
}
.map-popup-edit:hover { border-color: var(--gold); color: var(--gold); }
.leaflet-control-zoom a {
background: var(--bg-panel);
color: var(--text);
border-color: var(--border);
}
.leaflet-control-zoom a:hover { background: var(--bg-panel-alt); color: var(--gold); }
.map-category-form-row { display: grid; grid-template-columns: 1fr 100px; gap: 0.75rem; }
@media (max-width: 1000px) {
.map-page { grid-template-columns: minmax(0, 1fr); }
.map-sidebar { position: static; max-height: 60vh; }
.map-canvas { height: 60vh; }
}

891
assets/js/map.js Normal file
View file

@ -0,0 +1,891 @@
(function () {
'use strict';
var page = document.querySelector('.map-page');
var dataEl = document.getElementById('map-data');
if (!page || !dataEl || typeof L === 'undefined') return;
var data = JSON.parse(dataEl.textContent);
var manifest = data.manifest;
var mapKey = page.getAttribute('data-map-key');
var canManage = page.getAttribute('data-can-manage') === '1';
var canTactics = page.getAttribute('data-can-tactics') === '1';
var csrfToken = (document.querySelector('meta[name="csrf-token"]') || {}).content || '';
var statusEl = document.getElementById('map-status');
function postJson(payload) {
payload.csrf_token = csrfToken;
payload.map_key = mapKey;
return fetch('/map_action.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
}).then(function (response) { return response.json(); });
}
function setStatus(text, isError) {
if (!statusEl) return;
statusEl.textContent = text || '';
statusEl.className = 'map-status text-muted' + (isError ? ' error' : '');
}
// ---------------------------------------------------------------------
// Karte: gekacheltes Bild ohne Geo-Bezug, deshalb CRS.Simple. Alle Marker
// liegen als 0..1-Anteil der Bildbreite/-hoehe vor und werden hier ueber
// die maximale Zoomstufe in Leaflet-Koordinaten uebersetzt - dadurch bleiben
// sie auch dann richtig, wenn die Karte spaeter neu gekachelt wird.
// ---------------------------------------------------------------------
var map = L.map('map-canvas', {
crs: L.CRS.Simple,
minZoom: manifest.min_zoom,
maxZoom: manifest.max_zoom,
zoomControl: true,
attributionControl: false,
maxBoundsViscosity: 0.85,
doubleClickZoom: false,
// Die Zoomstufen der Kachel-Pyramide sind Zweierpotenzen. Ohne Zwischenstufen
// koennte die Startansicht die Flaeche nur selten gut ausnutzen (die naechst
// groessere Stufe passt meist nicht mehr hinein), deshalb Viertelschritte.
zoomSnap: 0.25,
zoomDelta: 0.5
});
function toLatLng(x, y) {
return map.unproject([x * manifest.width, y * manifest.height], manifest.max_zoom);
}
function toNormalized(latlng) {
var point = map.project(latlng, manifest.max_zoom);
return [
Math.min(1, Math.max(0, point.x / manifest.width)),
Math.min(1, Math.max(0, point.y / manifest.height))
];
}
// Rund um das Kartenbild liegt noch Leerraum (aufgefuellte Randkacheln). Ein Klick
// dorthin wuerde durch das Klemmen in toNormalized() still an den Bildrand rutschen -
// deshalb solche Klicks lieber ablehnen als das Objekt woanders abzulegen.
function isInsideMap(latlng) {
var point = map.project(latlng, manifest.max_zoom);
return point.x >= 0 && point.x <= manifest.width
&& point.y >= 0 && point.y <= manifest.height;
}
var bounds = L.latLngBounds(toLatLng(0, 1), toLatLng(1, 0));
map.setMaxBounds(bounds.pad(0.15));
L.tileLayer(manifest.url_template, {
tileSize: manifest.tile_size,
minZoom: manifest.min_zoom,
maxZoom: manifest.max_zoom,
bounds: bounds,
noWrap: true,
// Randkacheln jenseits des Bildes gibt es nicht - statt eines kaputten
// Bildes soll dort einfach nichts stehen.
errorTileUrl: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
}).addTo(map);
function resetView() {
map.fitBounds(bounds, { padding: [8, 8] });
}
resetView();
var resetBtn = document.getElementById('map-reset-view');
if (resetBtn) resetBtn.addEventListener('click', resetView);
// Positionsanzeige (praktisch, um Koordinaten durchzugeben)
var coordsEl = document.getElementById('map-coords');
if (coordsEl) {
map.on('mousemove', function (e) {
var pos = toNormalized(e.latlng);
coordsEl.textContent = (pos[0] * 100).toFixed(1) + ' / ' + (pos[1] * 100).toFixed(1);
});
map.on('mouseout', function () { coordsEl.textContent = ''; });
}
// ---------------------------------------------------------------------
// Marker
// ---------------------------------------------------------------------
var categoriesById = {};
data.categories.forEach(function (category) { categoriesById[category.id] = category; });
var markerLayers = {}; // category_id -> L.LayerGroup
var markerById = {}; // marker_id -> {data, layer, group}
var visibleCategories = {};
var searchTerm = '';
function categoryIcon(category) {
return L.divIcon({
className: 'map-marker-icon',
html: '<span class="map-marker-pin" style="background:' + (category ? category.color : '#c9a227') + '">'
+ '<span class="map-marker-glyph">' + (category && category.icon ? category.icon : '') + '</span></span>',
iconSize: [26, 26],
iconAnchor: [13, 13],
popupAnchor: [0, -14]
});
}
function escapeHtml(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function popupHtml(marker) {
var category = categoriesById[marker.category_id];
var html = '<div class="map-popup">'
+ '<strong class="map-popup-title">' + escapeHtml(marker.name) + '</strong>'
+ '<div class="map-popup-category">' + escapeHtml(category ? category.icon + ' ' + category.name : '') + '</div>';
if (marker.description) {
html += '<div class="map-popup-text">' + escapeHtml(marker.description).replace(/\n/g, '<br>') + '</div>';
}
if (marker.author) {
html += '<div class="map-popup-author">von ' + escapeHtml(marker.author) + '</div>';
}
if (canManage) {
html += '<button type="button" class="map-popup-edit" data-marker-id="' + marker.id + '">Bearbeiten</button>';
}
return html + '</div>';
}
function layerForCategory(categoryId) {
if (!markerLayers[categoryId]) {
markerLayers[categoryId] = L.layerGroup();
if (visibleCategories[categoryId] !== false) {
markerLayers[categoryId].addTo(map);
}
}
return markerLayers[categoryId];
}
function addMarker(markerData) {
var category = categoriesById[markerData.category_id];
var layer = L.marker(toLatLng(markerData.x, markerData.y), {
icon: categoryIcon(category),
draggable: false,
title: markerData.name
});
layer.bindPopup(popupHtml(markerData));
layer.addTo(layerForCategory(markerData.category_id));
markerById[markerData.id] = { data: markerData, layer: layer };
return layer;
}
data.markers.forEach(addMarker);
function removeMarker(markerId) {
var entry = markerById[markerId];
if (!entry) return;
var layer = markerLayers[entry.data.category_id];
if (layer) layer.removeLayer(entry.layer);
delete markerById[markerId];
}
// Sichtbarkeit: Kategorie-Haken UND Suchbegriff muessen passen.
function applyFilters() {
Object.keys(markerLayers).forEach(function (categoryId) {
var wanted = visibleCategories[categoryId] !== false;
var layer = markerLayers[categoryId];
if (wanted && !map.hasLayer(layer)) layer.addTo(map);
if (!wanted && map.hasLayer(layer)) map.removeLayer(layer);
});
if (searchTerm === '') {
Object.keys(markerById).forEach(function (id) {
var entry = markerById[id];
var element = entry.layer.getElement();
if (element) element.classList.remove('map-marker-filtered');
});
return;
}
Object.keys(markerById).forEach(function (id) {
var entry = markerById[id];
var category = categoriesById[entry.data.category_id];
var haystack = (entry.data.name + ' ' + (entry.data.description || '') + ' '
+ (category ? category.name : '')).toLowerCase();
var element = entry.layer.getElement();
if (!element) return;
element.classList.toggle('map-marker-filtered', haystack.indexOf(searchTerm) === -1);
});
}
document.querySelectorAll('.map-category-checkbox').forEach(function (checkbox) {
visibleCategories[checkbox.value] = checkbox.checked;
checkbox.addEventListener('change', function () {
visibleCategories[checkbox.value] = checkbox.checked;
syncGroupCheckbox(checkbox.closest('.map-group'));
applyFilters();
});
});
function syncGroupCheckbox(group) {
if (!group) return;
var groupBox = group.querySelector('.map-group-checkbox');
var boxes = group.querySelectorAll('.map-category-checkbox');
if (!groupBox || boxes.length === 0) return;
var checked = 0;
boxes.forEach(function (box) { if (box.checked) checked++; });
groupBox.checked = checked > 0;
groupBox.indeterminate = checked > 0 && checked < boxes.length;
}
document.querySelectorAll('.map-group-checkbox').forEach(function (groupBox) {
groupBox.addEventListener('change', function () {
var group = groupBox.closest('.map-group');
group.querySelectorAll('.map-category-checkbox').forEach(function (box) {
box.checked = groupBox.checked;
visibleCategories[box.value] = box.checked;
});
groupBox.indeterminate = false;
applyFilters();
});
});
document.querySelectorAll('.map-group-toggle').forEach(function (toggle) {
toggle.addEventListener('click', function () {
var group = toggle.closest('.map-group');
var collapsed = group.classList.toggle('collapsed');
toggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
});
});
function setAllCategories(checked) {
document.querySelectorAll('.map-category-checkbox').forEach(function (box) {
box.checked = checked;
visibleCategories[box.value] = checked;
});
document.querySelectorAll('.map-group-checkbox').forEach(function (box) {
box.checked = checked;
box.indeterminate = false;
});
applyFilters();
}
var showAllBtn = document.getElementById('map-show-all');
var hideAllBtn = document.getElementById('map-hide-all');
if (showAllBtn) showAllBtn.addEventListener('click', function () { setAllCategories(true); });
if (hideAllBtn) hideAllBtn.addEventListener('click', function () { setAllCategories(false); });
var searchInput = document.getElementById('map-search');
if (searchInput) {
searchInput.addEventListener('input', function () {
searchTerm = searchInput.value.trim().toLowerCase();
applyFilters();
// Kategorien, die nicht zur Suche passen, in der Sidebar ausblenden …
document.querySelectorAll('.map-category').forEach(function (row) {
var name = (row.getAttribute('data-name') || '').toLowerCase();
row.hidden = searchTerm !== '' && name.indexOf(searchTerm) === -1
&& !hasMatchingMarker(row.getAttribute('data-category-id'));
});
// … und Gruppen, von denen dadurch nichts mehr uebrig bleibt, gleich mit.
document.querySelectorAll('.map-group').forEach(function (group) {
var visible = Array.prototype.some.call(
group.querySelectorAll('.map-category'),
function (row) { return !row.hidden; }
);
group.hidden = searchTerm !== '' && !visible;
});
});
}
function hasMatchingMarker(categoryId) {
return Object.keys(markerById).some(function (id) {
var entry = markerById[id];
if (String(entry.data.category_id) !== String(categoryId)) return false;
return (entry.data.name + ' ' + (entry.data.description || '')).toLowerCase().indexOf(searchTerm) !== -1;
});
}
// ---- Sidebar-Reiter ----
document.querySelectorAll('.map-tab').forEach(function (tab) {
tab.addEventListener('click', function () {
document.querySelectorAll('.map-tab').forEach(function (t) { t.classList.remove('active'); });
tab.classList.add('active');
document.querySelectorAll('.map-panel').forEach(function (panel) {
panel.hidden = panel.getAttribute('data-panel') !== tab.getAttribute('data-panel');
});
});
});
var mapSelect = document.getElementById('map-select');
if (mapSelect) {
mapSelect.addEventListener('change', function () {
window.location.href = '/map.php?map=' + encodeURIComponent(mapSelect.value);
});
}
// ---------------------------------------------------------------------
// Modals
// ---------------------------------------------------------------------
function openModal(id) {
var modal = document.getElementById(id);
if (modal) modal.hidden = false;
}
function closeModal(id) {
var modal = document.getElementById(id);
if (!modal) return;
modal.hidden = true;
var feedback = modal.querySelector('.map-feedback');
if (feedback) feedback.textContent = '';
}
document.querySelectorAll('.modal-overlay').forEach(function (overlay) {
var closeBtn = overlay.querySelector('.modal-close');
if (closeBtn) closeBtn.addEventListener('click', function () { overlay.hidden = true; });
overlay.addEventListener('click', function (e) {
if (e.target === overlay) overlay.hidden = true;
});
});
function feedback(formId, text, isError) {
var form = document.getElementById(formId);
if (!form) return;
var el = form.querySelector('.map-feedback');
if (!el) return;
el.textContent = text || '';
el.className = 'map-feedback text-muted' + (isError ? ' error' : '');
}
// ---------------------------------------------------------------------
// Marker setzen/bearbeiten
// ---------------------------------------------------------------------
var markerForm = document.getElementById('map-marker-form');
var markerModalTitle = document.getElementById('map-marker-modal-title');
var markerDeleteBtn = document.getElementById('map-marker-delete');
var placingMarker = false;
var markerToolBtn = document.getElementById('map-tool-marker');
if (markerToolBtn) {
markerToolBtn.addEventListener('click', function () {
placingMarker = !placingMarker;
markerToolBtn.classList.toggle('active', placingMarker);
document.getElementById('map-canvas').classList.toggle('map-placing', placingMarker);
setStatus(placingMarker ? 'Klicke auf die Karte, um den Marker zu setzen (Esc bricht ab).' : '');
});
}
function openMarkerForm(marker, position) {
if (!markerForm) return;
markerForm.marker_id.value = marker ? marker.id : '';
markerForm.name.value = marker ? marker.name : '';
markerForm.description.value = marker ? (marker.description || '') : '';
markerForm.x.value = marker ? marker.x : position[0];
markerForm.y.value = marker ? marker.y : position[1];
if (marker) markerForm.category_id.value = String(marker.category_id);
markerModalTitle.textContent = marker ? 'Marker bearbeiten' : 'Marker anlegen';
markerDeleteBtn.hidden = !marker;
openModal('map-marker-modal');
markerForm.name.focus();
}
map.on('click', function (e) {
if (!drawingShape && (!placingMarker || !canManage)) return;
if (!isInsideMap(e.latlng)) {
setStatus('Dieser Punkt liegt außerhalb der Karte.', true);
return;
}
if (drawingShape) { handleDrawClick(e); return; }
openMarkerForm(null, toNormalized(e.latlng));
});
document.addEventListener('keydown', function (e) {
var inField = /^(INPUT|TEXTAREA|SELECT)$/.test((e.target.tagName || '').toUpperCase());
if (e.key === 'Escape') {
if (placingMarker && markerToolBtn) markerToolBtn.click();
if (drawingShape) cancelDrawing();
return;
}
if (e.key === 'Enter' && !inField && drawingShape) {
e.preventDefault();
finishShape();
}
});
// Popup-Buttons entstehen erst beim Oeffnen des Popups, deshalb delegiert.
document.addEventListener('click', function (e) {
var editBtn = e.target.closest('.map-popup-edit');
if (!editBtn) return;
var entry = markerById[editBtn.getAttribute('data-marker-id')];
if (entry) {
map.closePopup();
openMarkerForm(entry.data);
}
});
if (markerForm) {
markerForm.addEventListener('submit', function (e) {
e.preventDefault();
feedback('map-marker-form', 'Wird gespeichert …');
postJson({
action: 'marker_save',
marker_id: markerForm.marker_id.value,
category_id: markerForm.category_id.value,
name: markerForm.name.value,
description: markerForm.description.value,
x: parseFloat(markerForm.x.value),
y: parseFloat(markerForm.y.value)
}).then(function (result) {
if (result.status !== 'success') {
feedback('map-marker-form', result.message, true);
return;
}
window.location.reload();
}).catch(function () {
feedback('map-marker-form', 'Verbindung fehlgeschlagen.', true);
});
});
document.getElementById('map-marker-cancel').addEventListener('click', function () {
closeModal('map-marker-modal');
});
markerDeleteBtn.addEventListener('click', function () {
if (!window.confirm('Diesen Marker wirklich löschen?')) return;
postJson({ action: 'marker_delete', marker_id: markerForm.marker_id.value })
.then(function (result) {
if (result.status !== 'success') {
feedback('map-marker-form', result.message, true);
return;
}
removeMarker(markerForm.marker_id.value);
closeModal('map-marker-modal');
window.location.reload();
});
});
}
// ---------------------------------------------------------------------
// Kategorien
// ---------------------------------------------------------------------
var categoryForm = document.getElementById('map-category-form');
var categoryDeleteBtn = document.getElementById('map-category-delete');
var seedBtn = document.getElementById('map-seed-categories');
if (seedBtn) {
seedBtn.addEventListener('click', function () {
seedBtn.disabled = true;
postJson({ action: 'category_seed' }).then(function (result) {
if (result.status === 'success') {
window.location.reload();
} else {
seedBtn.disabled = false;
setStatus(result.message, true);
}
});
});
}
var addCategoryBtn = document.getElementById('map-add-category');
if (addCategoryBtn) {
addCategoryBtn.addEventListener('click', function () {
categoryForm.category_id.value = '';
categoryForm.name.value = '';
categoryForm.icon.value = '';
categoryForm.color.value = '#c9a227';
categoryForm.parent_id.value = '0';
document.getElementById('map-category-modal-title').textContent = 'Kategorie anlegen';
categoryDeleteBtn.hidden = true;
openModal('map-category-modal');
});
}
document.querySelectorAll('.map-category-edit').forEach(function (btn) {
btn.addEventListener('click', function () {
categoryForm.category_id.value = btn.getAttribute('data-category-id');
categoryForm.name.value = btn.getAttribute('data-name') || '';
categoryForm.icon.value = btn.getAttribute('data-icon') || '';
categoryForm.color.value = btn.getAttribute('data-color') || '#c9a227';
categoryForm.parent_id.value = btn.getAttribute('data-parent-id') || '0';
document.getElementById('map-category-modal-title').textContent = 'Kategorie bearbeiten';
categoryDeleteBtn.hidden = false;
openModal('map-category-modal');
});
});
if (categoryForm) {
categoryForm.addEventListener('submit', function (e) {
e.preventDefault();
feedback('map-category-form', 'Wird gespeichert …');
postJson({
action: 'category_save',
category_id: categoryForm.category_id.value,
parent_id: categoryForm.parent_id.value,
name: categoryForm.name.value,
icon: categoryForm.icon.value,
color: categoryForm.color.value
}).then(function (result) {
if (result.status !== 'success') {
feedback('map-category-form', result.message, true);
return;
}
window.location.reload();
});
});
document.getElementById('map-category-cancel').addEventListener('click', function () {
closeModal('map-category-modal');
});
categoryDeleteBtn.addEventListener('click', function () {
if (!window.confirm('Kategorie mitsamt allen darin enthaltenen Markern löschen?')) return;
postJson({ action: 'category_delete', category_id: categoryForm.category_id.value })
.then(function (result) {
if (result.status !== 'success') {
feedback('map-category-form', result.message, true);
return;
}
window.location.reload();
});
});
}
// ---------------------------------------------------------------------
// Taktiken: eigene Zeichenebene je Taktik (Punkte, Routen, Flaechen, Notizen)
// ---------------------------------------------------------------------
var tacticLayers = {}; // tactic_id -> L.FeatureGroup
var tacticsById = {};
var activeTacticId = null;
var drawingShape = null; // aktuell gezeichneter Typ
var drawPoints = [];
var drawPreview = null;
data.tactics.forEach(function (tactic) {
tacticsById[tactic.id] = tactic;
tacticLayers[tactic.id] = L.featureGroup();
tactic.shapes.forEach(function (shape) { drawShape(tactic.id, shape); });
});
function shapeLatLngs(shape) {
return shape.points.map(function (point) { return toLatLng(point[0], point[1]); });
}
function drawShape(tacticId, shape) {
var group = tacticLayers[tacticId];
if (!group) return;
var latlngs = shapeLatLngs(shape);
var layer;
if (shape.type === 'route') {
layer = L.polyline(latlngs, { color: shape.color, weight: 4, opacity: 0.9, dashArray: '10 6' });
} else if (shape.type === 'area') {
layer = L.polygon(latlngs, { color: shape.color, weight: 3, opacity: 0.9, fillOpacity: 0.2 });
} else if (shape.type === 'text') {
layer = L.marker(latlngs[0], {
icon: L.divIcon({
className: 'map-shape-text',
html: '<span style="border-color:' + shape.color + '">' + escapeHtml(shape.label) + '</span>',
iconSize: null
})
});
} else {
layer = L.marker(latlngs[0], {
icon: L.divIcon({
className: 'map-shape-point',
html: '<span class="map-shape-dot" style="background:' + shape.color + '"></span>'
+ (shape.label ? '<span class="map-shape-label">' + escapeHtml(shape.label) + '</span>' : ''),
iconSize: null,
iconAnchor: [9, 9]
})
});
}
if (shape.label && shape.type !== 'text' && shape.type !== 'point') {
layer.bindTooltip(shape.label, { permanent: false, sticky: true });
}
layer.shapeId = shape.id;
layer.on('click', function (e) {
if (!canTactics || activeTacticId !== tacticId || drawingShape) return;
L.DomEvent.stopPropagation(e);
if (window.confirm('Objekt "' + (shape.label || shape.type) + '" löschen?')) {
postJson({ action: 'shape_delete', shape_id: shape.id }).then(function (result) {
if (result.status === 'success') {
group.removeLayer(layer);
setStatus('Objekt gelöscht.');
} else {
setStatus(result.message, true);
}
});
}
});
group.addLayer(layer);
}
document.querySelectorAll('.map-tactic-checkbox').forEach(function (checkbox) {
checkbox.addEventListener('change', function () {
var group = tacticLayers[checkbox.value];
if (!group) return;
if (checkbox.checked) {
group.addTo(map);
} else {
map.removeLayer(group);
}
});
});
// ---- Taktik anlegen/bearbeiten ----
var tacticForm = document.getElementById('map-tactic-form');
var tacticDeleteBtn = document.getElementById('map-tactic-delete');
var tacticTools = document.getElementById('map-tactic-tools');
var tacticActiveName = document.getElementById('map-tactic-active-name');
var addTacticBtn = document.getElementById('map-add-tactic');
if (addTacticBtn) {
addTacticBtn.addEventListener('click', function () {
tacticForm.tactic_id.value = '';
tacticForm.name.value = '';
tacticForm.description.value = '';
document.getElementById('map-tactic-modal-title').textContent = 'Taktik anlegen';
tacticDeleteBtn.hidden = true;
openModal('map-tactic-modal');
tacticForm.name.focus();
});
}
document.querySelectorAll('.map-tactic-edit').forEach(function (btn) {
btn.addEventListener('click', function () {
var row = btn.closest('.map-tactic');
var tactic = tacticsById[row.getAttribute('data-tactic-id')];
if (!tactic) return;
tacticForm.tactic_id.value = tactic.id;
tacticForm.name.value = tactic.name;
tacticForm.description.value = tactic.description || '';
document.getElementById('map-tactic-modal-title').textContent = 'Taktik bearbeiten';
tacticDeleteBtn.hidden = false;
openModal('map-tactic-modal');
});
});
if (tacticForm) {
tacticForm.addEventListener('submit', function (e) {
e.preventDefault();
feedback('map-tactic-form', 'Wird gespeichert …');
postJson({
action: 'tactic_save',
tactic_id: tacticForm.tactic_id.value,
name: tacticForm.name.value,
description: tacticForm.description.value
}).then(function (result) {
if (result.status !== 'success') {
feedback('map-tactic-form', result.message, true);
return;
}
// Eine frisch angelegte Taktik ist noch nicht im DOM - dafuer neu laden
// und danach direkt in den Bearbeiten-Modus springen.
if (!tacticForm.tactic_id.value) {
window.location.href = '/map.php?map=' + encodeURIComponent(mapKey) + '&edit=' + result.tactic_id;
return;
}
closeModal('map-tactic-modal');
startTacticEditing(parseInt(tacticForm.tactic_id.value, 10));
var row = document.querySelector('.map-tactic[data-tactic-id="' + tacticForm.tactic_id.value + '"] .map-tactic-name');
if (row) row.textContent = tacticForm.name.value;
});
});
document.getElementById('map-tactic-cancel').addEventListener('click', function () {
closeModal('map-tactic-modal');
});
tacticDeleteBtn.addEventListener('click', function () {
if (!window.confirm('Diese Taktik mitsamt allen Objekten löschen?')) return;
postJson({ action: 'tactic_delete', tactic_id: tacticForm.tactic_id.value })
.then(function (result) {
if (result.status !== 'success') {
feedback('map-tactic-form', result.message, true);
return;
}
window.location.reload();
});
});
}
function startTacticEditing(tacticId) {
if (!canTactics || !tacticsById[tacticId]) return;
activeTacticId = tacticId;
// Beim Bearbeiten muss die Ebene sichtbar sein, sonst zeichnet man ins Leere.
var checkbox = document.querySelector('.map-tactic-checkbox[value="' + tacticId + '"]');
if (checkbox && !checkbox.checked) {
checkbox.checked = true;
checkbox.dispatchEvent(new Event('change'));
}
if (!map.hasLayer(tacticLayers[tacticId])) tacticLayers[tacticId].addTo(map);
document.querySelectorAll('.map-tactic').forEach(function (row) {
row.classList.toggle('editing', row.getAttribute('data-tactic-id') === String(tacticId));
});
if (tacticTools) tacticTools.hidden = false;
if (tacticActiveName) tacticActiveName.textContent = tacticsById[tacticId].name;
setStatus('Taktik wird bearbeitet - Werkzeug wählen und auf die Karte klicken. Klick auf ein Objekt löscht es.');
}
function stopTacticEditing() {
activeTacticId = null;
cancelDrawing();
if (tacticTools) tacticTools.hidden = true;
document.querySelectorAll('.map-tactic').forEach(function (row) { row.classList.remove('editing'); });
setStatus('');
}
var tacticCloseBtn = document.getElementById('map-tactic-close');
if (tacticCloseBtn) tacticCloseBtn.addEventListener('click', stopTacticEditing);
document.querySelectorAll('#map-tactic-tools .map-tool[data-shape]').forEach(function (btn) {
btn.addEventListener('click', function () {
var shape = btn.getAttribute('data-shape');
if (drawingShape === shape) { cancelDrawing(); return; }
cancelDrawing();
drawingShape = shape;
drawPoints = [];
btn.classList.add('active');
document.getElementById('map-canvas').classList.add('map-placing');
if (finishBtn) finishBtn.hidden = shape !== 'route' && shape !== 'area';
setStatus(shape === 'route' || shape === 'area'
? 'Punkte anklicken, Doppelklick beendet die Form (Esc bricht ab).'
: 'Auf die Karte klicken, um das Objekt zu setzen (Esc bricht ab).');
});
});
function cancelDrawing() {
drawingShape = null;
drawPoints = [];
if (drawPreview) { map.removeLayer(drawPreview); drawPreview = null; }
document.querySelectorAll('#map-tactic-tools .map-tool').forEach(function (b) { b.classList.remove('active'); });
document.getElementById('map-canvas').classList.remove('map-placing');
if (finishBtn) finishBtn.hidden = true;
}
function currentColor() {
var picker = document.getElementById('map-shape-color');
return picker ? picker.value : '#c9a227';
}
function handleDrawClick(e) {
if (!activeTacticId) return;
var position = toNormalized(e.latlng);
if (drawingShape === 'point' || drawingShape === 'text') {
askForLabel(drawingShape, [position]);
return;
}
drawPoints.push(position);
var latlngs = drawPoints.map(function (p) { return toLatLng(p[0], p[1]); });
if (drawPreview) map.removeLayer(drawPreview);
drawPreview = drawingShape === 'area'
? L.polygon(latlngs, { color: currentColor(), weight: 2, dashArray: '4 4', fillOpacity: 0.12 })
: L.polyline(latlngs, { color: currentColor(), weight: 3, dashArray: '4 4' });
drawPreview.addTo(map);
}
// Route/Flaeche abschliessen: per Doppelklick, ueber den Button oder mit Enter.
// Doppelklick allein reicht nicht - auf Touch-Geraeten loest Doppeltippen kein
// zuverlaessiges dblclick aus.
function finishShape() {
if (!drawingShape || (drawingShape !== 'route' && drawingShape !== 'area')) return;
if (drawPoints.length < 2) {
setStatus('Bitte mindestens zwei Punkte setzen.', true);
return;
}
askForLabel(drawingShape, drawPoints.slice());
}
map.on('dblclick', function (e) {
if (!drawingShape || (drawingShape !== 'route' && drawingShape !== 'area')) return;
L.DomEvent.stop(e);
finishShape();
});
var finishBtn = document.getElementById('map-shape-finish');
if (finishBtn) finishBtn.addEventListener('click', finishShape);
// Beschriftung/Farbe kommen aus einem eigenen Popup statt aus window.prompt -
// dieselbe Optik wie die uebrigen Dialoge der Seite.
var shapeForm = document.getElementById('map-shape-form');
var pendingShape = null;
function askForLabel(type, points) {
pendingShape = { type: type, points: points };
var labels = { point: 'Punkt beschriften', route: 'Route beschriften', area: 'Fläche beschriften', text: 'Notiz eingeben' };
document.getElementById('map-shape-modal-title').textContent = labels[type] || 'Objekt beschriften';
// Nur die Notiz besteht aus ihrem Text - bei allen anderen ist er optional.
document.getElementById('map-shape-label-hint').textContent = type === 'text' ? '(erforderlich)' : '(optional)';
shapeForm.label.value = '';
shapeForm.color.value = currentColor();
openModal('map-shape-modal');
shapeForm.label.focus();
}
if (shapeForm) {
shapeForm.addEventListener('submit', function (e) {
e.preventDefault();
if (!pendingShape) return;
var label = shapeForm.label.value.trim();
if (pendingShape.type === 'text' && label === '') {
feedback('map-shape-form', 'Bitte einen Text für die Notiz eingeben.', true);
return;
}
saveShape(pendingShape.type, label, pendingShape.points, shapeForm.color.value);
pendingShape = null;
closeModal('map-shape-modal');
cancelDrawing();
});
document.getElementById('map-shape-cancel').addEventListener('click', function () {
pendingShape = null;
closeModal('map-shape-modal');
cancelDrawing();
});
// Auch Schliessen ueber das X oder einen Klick neben das Popup bricht das
// angefangene Zeichnen ab, damit kein Werkzeug aktiv haengen bleibt.
document.getElementById('map-shape-modal').addEventListener('click', function (e) {
if (e.target.id === 'map-shape-modal' || e.target.closest('.modal-close')) {
pendingShape = null;
cancelDrawing();
}
});
}
function saveShape(type, label, points, color) {
postJson({
action: 'shape_save',
tactic_id: activeTacticId,
type: type,
label: label,
color: color,
points: points
}).then(function (result) {
if (result.status !== 'success') {
setStatus(result.message, true);
return;
}
var shape = { id: result.shape_id, type: type, label: label, color: color, points: points };
tacticsById[activeTacticId].shapes.push(shape);
drawShape(activeTacticId, shape);
setStatus('Objekt gespeichert.');
}).catch(function () {
setStatus('Verbindung fehlgeschlagen.', true);
});
}
// Nach dem Anlegen einer Taktik landet man per ?edit=<id> direkt im Bearbeiten-Modus.
var editParam = new URLSearchParams(window.location.search).get('edit');
if (editParam) {
document.querySelector('.map-tab[data-panel="tactics"]').click();
startTacticEditing(parseInt(editParam, 10));
}
})();

View file

View file

@ -0,0 +1,17 @@
# Hochgeladene Kartenkacheln duerfen niemals als Skript ausgefuehrt werden -
# der Ordner wird per FTP befuellt und enthaelt ausschliesslich Bilder/JSON.
<IfModule mod_php.c>
php_flag engine off
</IfModule>
<IfModule mod_php7.c>
php_flag engine off
</IfModule>
<FilesMatch "\.(php|phtml|php[0-9]?|phar|cgi|pl)$">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Deny from all
</IfModule>
</FilesMatch>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
assets/vendor/leaflet/images/layers.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 696 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 618 B

661
assets/vendor/leaflet/leaflet.css vendored Normal file
View file

@ -0,0 +1,661 @@
/* required styles */
.leaflet-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-container,
.leaflet-pane > svg,
.leaflet-pane > canvas,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
position: absolute;
left: 0;
top: 0;
}
.leaflet-container {
overflow: hidden;
}
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
-webkit-user-drag: none;
}
/* Prevents IE11 from highlighting tiles in blue */
.leaflet-tile::selection {
background: transparent;
}
/* Safari renders non-retina tile on retina better with this, but Chrome is worse */
.leaflet-safari .leaflet-tile {
image-rendering: -webkit-optimize-contrast;
}
/* hack that prevents hw layers "stretching" when loading new tiles */
.leaflet-safari .leaflet-tile-container {
width: 1600px;
height: 1600px;
-webkit-transform-origin: 0 0;
}
.leaflet-marker-icon,
.leaflet-marker-shadow {
display: block;
}
/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */
/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */
.leaflet-container .leaflet-overlay-pane svg {
max-width: none !important;
max-height: none !important;
}
.leaflet-container .leaflet-marker-pane img,
.leaflet-container .leaflet-shadow-pane img,
.leaflet-container .leaflet-tile-pane img,
.leaflet-container img.leaflet-image-layer,
.leaflet-container .leaflet-tile {
max-width: none !important;
max-height: none !important;
width: auto;
padding: 0;
}
.leaflet-container img.leaflet-tile {
/* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */
mix-blend-mode: plus-lighter;
}
.leaflet-container.leaflet-touch-zoom {
-ms-touch-action: pan-x pan-y;
touch-action: pan-x pan-y;
}
.leaflet-container.leaflet-touch-drag {
-ms-touch-action: pinch-zoom;
/* Fallback for FF which doesn't support pinch-zoom */
touch-action: none;
touch-action: pinch-zoom;
}
.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom {
-ms-touch-action: none;
touch-action: none;
}
.leaflet-container {
-webkit-tap-highlight-color: transparent;
}
.leaflet-container a {
-webkit-tap-highlight-color: rgba(51, 181, 229, 0.4);
}
.leaflet-tile {
filter: inherit;
visibility: hidden;
}
.leaflet-tile-loaded {
visibility: inherit;
}
.leaflet-zoom-box {
width: 0;
height: 0;
-moz-box-sizing: border-box;
box-sizing: border-box;
z-index: 800;
}
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
.leaflet-overlay-pane svg {
-moz-user-select: none;
}
.leaflet-pane { z-index: 400; }
.leaflet-tile-pane { z-index: 200; }
.leaflet-overlay-pane { z-index: 400; }
.leaflet-shadow-pane { z-index: 500; }
.leaflet-marker-pane { z-index: 600; }
.leaflet-tooltip-pane { z-index: 650; }
.leaflet-popup-pane { z-index: 700; }
.leaflet-map-pane canvas { z-index: 100; }
.leaflet-map-pane svg { z-index: 200; }
.leaflet-vml-shape {
width: 1px;
height: 1px;
}
.lvml {
behavior: url(#default#VML);
display: inline-block;
position: absolute;
}
/* control positioning */
.leaflet-control {
position: relative;
z-index: 800;
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
.leaflet-top,
.leaflet-bottom {
position: absolute;
z-index: 1000;
pointer-events: none;
}
.leaflet-top {
top: 0;
}
.leaflet-right {
right: 0;
}
.leaflet-bottom {
bottom: 0;
}
.leaflet-left {
left: 0;
}
.leaflet-control {
float: left;
clear: both;
}
.leaflet-right .leaflet-control {
float: right;
}
.leaflet-top .leaflet-control {
margin-top: 10px;
}
.leaflet-bottom .leaflet-control {
margin-bottom: 10px;
}
.leaflet-left .leaflet-control {
margin-left: 10px;
}
.leaflet-right .leaflet-control {
margin-right: 10px;
}
/* zoom and fade animations */
.leaflet-fade-anim .leaflet-popup {
opacity: 0;
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
transition: opacity 0.2s linear;
}
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
opacity: 1;
}
.leaflet-zoom-animated {
-webkit-transform-origin: 0 0;
-ms-transform-origin: 0 0;
transform-origin: 0 0;
}
svg.leaflet-zoom-animated {
will-change: transform;
}
.leaflet-zoom-anim .leaflet-zoom-animated {
-webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
transition: transform 0.25s cubic-bezier(0,0,0.25,1);
}
.leaflet-zoom-anim .leaflet-tile,
.leaflet-pan-anim .leaflet-tile {
-webkit-transition: none;
-moz-transition: none;
transition: none;
}
.leaflet-zoom-anim .leaflet-zoom-hide {
visibility: hidden;
}
/* cursors */
.leaflet-interactive {
cursor: pointer;
}
.leaflet-grab {
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: grab;
}
.leaflet-crosshair,
.leaflet-crosshair .leaflet-interactive {
cursor: crosshair;
}
.leaflet-popup-pane,
.leaflet-control {
cursor: auto;
}
.leaflet-dragging .leaflet-grab,
.leaflet-dragging .leaflet-grab .leaflet-interactive,
.leaflet-dragging .leaflet-marker-draggable {
cursor: move;
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
cursor: grabbing;
}
/* marker & overlays interactivity */
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-image-layer,
.leaflet-pane > svg path,
.leaflet-tile-container {
pointer-events: none;
}
.leaflet-marker-icon.leaflet-interactive,
.leaflet-image-layer.leaflet-interactive,
.leaflet-pane > svg path.leaflet-interactive,
svg.leaflet-image-layer.leaflet-interactive path {
pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */
pointer-events: auto;
}
/* visual tweaks */
.leaflet-container {
background: #ddd;
outline-offset: 1px;
}
.leaflet-container a {
color: #0078A8;
}
.leaflet-zoom-box {
border: 2px dotted #38f;
background: rgba(255,255,255,0.5);
}
/* general typography */
.leaflet-container {
font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
font-size: 12px;
font-size: 0.75rem;
line-height: 1.5;
}
/* general toolbar styles */
.leaflet-bar {
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
border-radius: 4px;
}
.leaflet-bar a {
background-color: #fff;
border-bottom: 1px solid #ccc;
width: 26px;
height: 26px;
line-height: 26px;
display: block;
text-align: center;
text-decoration: none;
color: black;
}
.leaflet-bar a,
.leaflet-control-layers-toggle {
background-position: 50% 50%;
background-repeat: no-repeat;
display: block;
}
.leaflet-bar a:hover,
.leaflet-bar a:focus {
background-color: #f4f4f4;
}
.leaflet-bar a:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.leaflet-bar a:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom: none;
}
.leaflet-bar a.leaflet-disabled {
cursor: default;
background-color: #f4f4f4;
color: #bbb;
}
.leaflet-touch .leaflet-bar a {
width: 30px;
height: 30px;
line-height: 30px;
}
.leaflet-touch .leaflet-bar a:first-child {
border-top-left-radius: 2px;
border-top-right-radius: 2px;
}
.leaflet-touch .leaflet-bar a:last-child {
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
}
/* zoom control */
.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
font: bold 18px 'Lucida Console', Monaco, monospace;
text-indent: 1px;
}
.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out {
font-size: 22px;
}
/* layers control */
.leaflet-control-layers {
box-shadow: 0 1px 5px rgba(0,0,0,0.4);
background: #fff;
border-radius: 5px;
}
.leaflet-control-layers-toggle {
background-image: url(images/layers.png);
width: 36px;
height: 36px;
}
.leaflet-retina .leaflet-control-layers-toggle {
background-image: url(images/layers-2x.png);
background-size: 26px 26px;
}
.leaflet-touch .leaflet-control-layers-toggle {
width: 44px;
height: 44px;
}
.leaflet-control-layers .leaflet-control-layers-list,
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
display: none;
}
.leaflet-control-layers-expanded .leaflet-control-layers-list {
display: block;
position: relative;
}
.leaflet-control-layers-expanded {
padding: 6px 10px 6px 6px;
color: #333;
background: #fff;
}
.leaflet-control-layers-scrollbar {
overflow-y: scroll;
overflow-x: hidden;
padding-right: 5px;
}
.leaflet-control-layers-selector {
margin-top: 2px;
position: relative;
top: 1px;
}
.leaflet-control-layers label {
display: block;
font-size: 13px;
font-size: 1.08333em;
}
.leaflet-control-layers-separator {
height: 0;
border-top: 1px solid #ddd;
margin: 5px -10px 5px -6px;
}
/* Default icon URLs */
.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */
background-image: url(images/marker-icon.png);
}
/* attribution and scale controls */
.leaflet-container .leaflet-control-attribution {
background: #fff;
background: rgba(255, 255, 255, 0.8);
margin: 0;
}
.leaflet-control-attribution,
.leaflet-control-scale-line {
padding: 0 5px;
color: #333;
line-height: 1.4;
}
.leaflet-control-attribution a {
text-decoration: none;
}
.leaflet-control-attribution a:hover,
.leaflet-control-attribution a:focus {
text-decoration: underline;
}
.leaflet-attribution-flag {
display: inline !important;
vertical-align: baseline !important;
width: 1em;
height: 0.6669em;
}
.leaflet-left .leaflet-control-scale {
margin-left: 5px;
}
.leaflet-bottom .leaflet-control-scale {
margin-bottom: 5px;
}
.leaflet-control-scale-line {
border: 2px solid #777;
border-top: none;
line-height: 1.1;
padding: 2px 5px 1px;
white-space: nowrap;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.8);
text-shadow: 1px 1px #fff;
}
.leaflet-control-scale-line:not(:first-child) {
border-top: 2px solid #777;
border-bottom: none;
margin-top: -2px;
}
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
border-bottom: 2px solid #777;
}
.leaflet-touch .leaflet-control-attribution,
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
box-shadow: none;
}
.leaflet-touch .leaflet-control-layers,
.leaflet-touch .leaflet-bar {
border: 2px solid rgba(0,0,0,0.2);
background-clip: padding-box;
}
/* popup */
.leaflet-popup {
position: absolute;
text-align: center;
margin-bottom: 20px;
}
.leaflet-popup-content-wrapper {
padding: 1px;
text-align: left;
border-radius: 12px;
}
.leaflet-popup-content {
margin: 13px 24px 13px 20px;
line-height: 1.3;
font-size: 13px;
font-size: 1.08333em;
min-height: 1px;
}
.leaflet-popup-content p {
margin: 17px 0;
margin: 1.3em 0;
}
.leaflet-popup-tip-container {
width: 40px;
height: 20px;
position: absolute;
left: 50%;
margin-top: -1px;
margin-left: -20px;
overflow: hidden;
pointer-events: none;
}
.leaflet-popup-tip {
width: 17px;
height: 17px;
padding: 1px;
margin: -10px auto 0;
pointer-events: auto;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
.leaflet-popup-content-wrapper,
.leaflet-popup-tip {
background: white;
color: #333;
box-shadow: 0 3px 14px rgba(0,0,0,0.4);
}
.leaflet-container a.leaflet-popup-close-button {
position: absolute;
top: 0;
right: 0;
border: none;
text-align: center;
width: 24px;
height: 24px;
font: 16px/24px Tahoma, Verdana, sans-serif;
color: #757575;
text-decoration: none;
background: transparent;
}
.leaflet-container a.leaflet-popup-close-button:hover,
.leaflet-container a.leaflet-popup-close-button:focus {
color: #585858;
}
.leaflet-popup-scrolled {
overflow: auto;
}
.leaflet-oldie .leaflet-popup-content-wrapper {
-ms-zoom: 1;
}
.leaflet-oldie .leaflet-popup-tip {
width: 24px;
margin: 0 auto;
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
}
.leaflet-oldie .leaflet-control-zoom,
.leaflet-oldie .leaflet-control-layers,
.leaflet-oldie .leaflet-popup-content-wrapper,
.leaflet-oldie .leaflet-popup-tip {
border: 1px solid #999;
}
/* div icon */
.leaflet-div-icon {
background: #fff;
border: 1px solid #666;
}
/* Tooltip */
/* Base styles for the element that has a tooltip */
.leaflet-tooltip {
position: absolute;
padding: 6px;
background-color: #fff;
border: 1px solid #fff;
border-radius: 3px;
color: #222;
white-space: nowrap;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
pointer-events: none;
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
}
.leaflet-tooltip.leaflet-interactive {
cursor: pointer;
pointer-events: auto;
}
.leaflet-tooltip-top:before,
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
position: absolute;
pointer-events: none;
border: 6px solid transparent;
background: transparent;
content: "";
}
/* Directions */
.leaflet-tooltip-bottom {
margin-top: 6px;
}
.leaflet-tooltip-top {
margin-top: -6px;
}
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-top:before {
left: 50%;
margin-left: -6px;
}
.leaflet-tooltip-top:before {
bottom: 0;
margin-bottom: -12px;
border-top-color: #fff;
}
.leaflet-tooltip-bottom:before {
top: 0;
margin-top: -12px;
margin-left: -6px;
border-bottom-color: #fff;
}
.leaflet-tooltip-left {
margin-left: -6px;
}
.leaflet-tooltip-right {
margin-left: 6px;
}
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
top: 50%;
margin-top: -6px;
}
.leaflet-tooltip-left:before {
right: 0;
margin-right: -12px;
border-left-color: #fff;
}
.leaflet-tooltip-right:before {
left: 0;
margin-left: -12px;
border-right-color: #fff;
}
/* Printing */
@media print {
/* Prevent printers from removing background-images of controls. */
.leaflet-control {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}

6
assets/vendor/leaflet/leaflet.js vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -125,6 +125,10 @@ function icon(string $name): string
'crown' => '<path d="M4 8l4 3 4-6 4 6 4-3-2 9H6z"/><path d="M6 20h12"/>',
'menu' => '<line x1="4" y1="7" x2="20" y2="7"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="17" x2="20" y2="17"/>',
'flag' => '<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/>',
'map' => '<polygon points="2 7 9 4 15 7 22 4 22 17 15 20 9 17 2 20 2 7"/><line x1="9" y1="4" x2="9" y2="17"/><line x1="15" y1="7" x2="15" y2="20"/>',
'map-pin' => '<path d="M12 21s7-5.6 7-11a7 7 0 1 0-14 0c0 5.4 7 11 7 11z"/><circle cx="12" cy="10" r="2.5"/>',
'route' => '<circle cx="5" cy="18" r="2.5"/><circle cx="19" cy="6" r="2.5"/><path d="M7.5 18h5a4 4 0 0 0 0-8h-1a4 4 0 0 1 0-8h5" transform="translate(0 2)"/>',
'area' => '<polygon points="4 8 10 4 20 7 18 18 7 20"/><circle cx="4" cy="8" r="1.6"/><circle cx="10" cy="4" r="1.6"/><circle cx="20" cy="7" r="1.6"/><circle cx="18" cy="18" r="1.6"/><circle cx="7" cy="20" r="1.6"/>',
'bell' => '<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/>',
'hash' => '<line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/>',
'at-sign' => '<circle cx="12" cy="12" r="4"/><path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-3.92 7.94"/>',

View file

@ -6,6 +6,7 @@ $canManageRoles = $currentUser && user_has_permission('roles.manage');
$canViewRaids = $currentUser && user_has_permission('raids.view');
$canViewPremades = $currentUser && user_has_permission('premades.view');
$canViewEvents = $currentUser && user_has_permission('events.view');
$canViewMap = $currentUser && user_has_permission('map.view');
$canViewMembers = $currentUser && user_has_permission('members.view');
$canViewReports = $currentUser && user_has_permission('reports.view');
$showAdminMenu = $canViewUsers || $canManageRoles || $canViewReports;
@ -16,6 +17,7 @@ $isProfileActive = $currentScript === 'profile.php';
$isRaidsActive = $currentScript === 'raids.php';
$isPremadesActive = $currentScript === 'premades.php';
$isEventsActive = $currentScript === 'events.php';
$isMapActive = $currentScript === 'map.php';
$isMembersActive = $currentScript === 'members.php';
$isReportsActive = $currentScript === 'reports.php';
$isUsersActive = in_array($currentScript, ['users.php', 'user_form.php', 'user_delete.php'], true);
@ -28,6 +30,7 @@ $pageBackgrounds = [
'raids.php' => 'bg-raids',
'premades.php' => 'bg-premades',
'events.php' => 'bg-events',
'map.php' => 'bg-map',
'members.php' => 'bg-members',
'users.php' => 'bg-admin',
'user_form.php' => 'bg-admin',
@ -58,6 +61,11 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($
<link rel="icon" type="image/png" sizes="32x32" href="/assets/images/favicon-32.png">
<link rel="icon" type="image/png" sizes="48x48" href="/assets/images/favicon-48.png">
<link rel="apple-touch-icon" href="/assets/images/apple-touch-icon.png">
<?php if ($currentScript === 'map.php'): ?>
<!-- Vor style.css, damit die eigenen Anpassungen an Leaflet-Elementen (Popups,
Zoom-Buttons) bei gleicher Spezifitaet gewinnen. -->
<link rel="stylesheet" href="/assets/vendor/leaflet/leaflet.css">
<?php endif; ?>
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body<?= $currentUser ? '' : ' class="guest-bg"' ?>>
@ -99,7 +107,7 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($
</a>
<?php endif; ?>
<?php if ($canViewRaids || $canViewPremades || $canViewEvents): ?>
<?php if ($canViewRaids || $canViewPremades || $canViewEvents || $canViewMap): ?>
<div class="sidebar-nav-gap"></div>
<?php endif; ?>
<?php if ($canViewRaids): ?>
@ -117,6 +125,11 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($
<?= icon('bell') ?><span class="label">Events</span>
</a>
<?php endif; ?>
<?php if ($canViewMap): ?>
<a href="/map.php" class="sidebar-link<?= $isMapActive ? ' active' : '' ?>" title="Karte">
<?= icon('map') ?><span class="label">Karte</span>
</a>
<?php endif; ?>
<?php if ($showAdminMenu): ?>
<div class="sidebar-section-label">Admin</div>
<?php if ($canViewUsers): ?>
@ -147,7 +160,7 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($
</div>
</aside>
<div class="app-content<?= $pageBackgroundClass ? ' ' . e($pageBackgroundClass) : '' ?>">
<main class="container">
<main class="container<?= !empty($containerWide) ? ' container-wide' : '' ?>">
<?php foreach ($otherFlashes as $flash): ?>
<div class="flash flash-<?= e($flash['type']) ?>"><?= e($flash['message']) ?></div>
<?php endforeach; ?>

285
includes/map.php Normal file
View file

@ -0,0 +1,285 @@
<?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';
/**
* 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;
}

View file

@ -18,6 +18,9 @@ const CORE_PERMISSIONS = [
['key' => 'premades.manage', 'description' => 'Alle Premade-Gruppen verwalten (nicht nur die eigene)'],
['key' => 'events.view', 'description' => 'Geplante Event-Erinnerungen einsehen'],
['key' => 'events.manage', 'description' => 'Event-Erinnerungen planen, bearbeiten und löschen'],
['key' => 'map.view', 'description' => 'Taktikkarte ansehen'],
['key' => 'map.manage', 'description' => 'Marker und Kategorien der Karte verwalten'],
['key' => 'map.tactics', 'description' => 'Taktiken auf der Karte anlegen und bearbeiten'],
['key' => 'members.view', 'description' => 'Mitgliederliste einsehen'],
['key' => 'reports.view', 'description' => 'Eingegangene Reports einsehen'],
['key' => 'reports.manage', 'description' => 'Reports löschen/archivieren und die Punkte-Gewichtung verwalten'],

View file

@ -59,6 +59,8 @@ function seed_defaults(PDO $pdo): array
->execute([$memberRoleId, $permissionIds['members.view']]);
$pdo->prepare('INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?, ?)')
->execute([$memberRoleId, $permissionIds['events.view']]);
$pdo->prepare('INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?, ?)')
->execute([$memberRoleId, $permissionIds['map.view']]);
return ['admin_role_id' => $adminRoleId];
}

356
map.php Normal file
View file

@ -0,0 +1,356 @@
<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/map.php';
require_permission('map.view');
$canManageMap = user_has_permission('map.manage');
$canEditTactics = user_has_permission('map.tactics');
$maps = map_available();
$mapKey = (string) ($_GET['map'] ?? '');
if ($mapKey === '' || !isset($maps[$mapKey])) {
$mapKey = (string) array_key_first($maps);
}
$manifest = $maps[$mapKey] ?? null;
$categoryTree = $manifest ? map_category_tree($mapKey) : [];
$markers = $manifest ? map_markers($mapKey) : [];
$tactics = $manifest ? map_tactics($mapKey) : [];
// Flache Kategorienliste fuer die Auswahlfelder im Marker-Formular.
$flatCategories = [];
foreach ($categoryTree as $group) {
foreach ($group['children'] as $child) {
$flatCategories[] = [
'id' => (int) $child['id'],
'name' => (string) $child['name'],
'group' => (string) $group['name'],
'icon' => (string) $child['icon'],
'color' => (string) $child['color'],
];
}
}
$totalMarkers = count($markers);
$pageTitle = 'Karte';
$containerWide = true;
include __DIR__ . '/includes/header.php';
?>
<?php if (!$manifest): ?>
<div class="panel">
<h1>Taktikkarte</h1>
<p class="text-muted">
Es ist noch keine Karte hinterlegt. Die Karte wird als Kachel-Pyramide ausgeliefert
(mehrere Zoomstufen), damit sie auch nah herangezoomt scharf bleibt.
</p>
<h2>Karte einrichten</h2>
<ol class="map-setup-steps">
<li>Ein möglichst hoch aufgelöstes Bild der Region besorgen (z.B. ein eigener Screenshot der Ingame-Karte).</li>
<li>Lokal einmal das Kachel-Script laufen lassen:<br>
<code>php tools/make_map_tiles.php verteron "C:\Pfad\zu\verteron.png" --name="Verteron"</code></li>
<li>Den erzeugten Ordner <code>assets/uploads/maps/verteron/</code> per FTP hochladen.</li>
</ol>
<p class="text-muted">
Danach erscheint die Karte hier automatisch - mehrere Regionen nebeneinander funktionieren
genauso, jeder Unterordner mit einer <code>tiles.json</code> wird zu einer eigenen Karte.
</p>
</div>
<?php else: ?>
<div class="map-page"
data-map-key="<?= e($mapKey) ?>"
data-can-manage="<?= $canManageMap ? '1' : '0' ?>"
data-can-tactics="<?= $canEditTactics ? '1' : '0' ?>">
<div class="map-sidebar">
<div class="map-sidebar-head">
<?php if (count($maps) > 1): ?>
<select class="map-select" id="map-select">
<?php foreach ($maps as $key => $available): ?>
<option value="<?= e($key) ?>" <?= $key === $mapKey ? 'selected' : '' ?>><?= e((string) $available['name']) ?></option>
<?php endforeach; ?>
</select>
<?php else: ?>
<h1><?= e((string) $manifest['name']) ?></h1>
<?php endif; ?>
<input type="text" id="map-search" placeholder="Suchen …" autocomplete="off">
<div class="map-bulk-actions">
<button type="button" class="button-secondary" id="map-show-all">Alle einblenden</button>
<button type="button" class="button-secondary" id="map-hide-all">Alle ausblenden</button>
</div>
</div>
<div class="map-tabs">
<button type="button" class="map-tab active" data-panel="markers">Marker <span class="map-tab-count"><?= $totalMarkers ?></span></button>
<button type="button" class="map-tab" data-panel="tactics">Taktiken <span class="map-tab-count"><?= count($tactics) ?></span></button>
</div>
<div class="map-panel" data-panel="markers">
<?php if (empty($categoryTree)): ?>
<div class="map-empty">
<p class="text-muted">Noch keine Kategorien angelegt.</p>
<?php if ($canManageMap): ?>
<button type="button" class="button-success" id="map-seed-categories">Standard-Kategorien anlegen</button>
<p class="text-muted map-hint">Legt eine Gliederung nach Orten, Ressourcen, NPCs, Quests und Monstern an, die ihr danach frei anpassen könnt.</p>
<?php endif; ?>
</div>
<?php else: ?>
<div class="map-category-tree" id="map-category-tree">
<?php foreach ($categoryTree as $group): ?>
<div class="map-group" data-group-id="<?= (int) $group['id'] ?>">
<div class="map-group-head">
<button type="button" class="map-group-toggle" aria-expanded="true">
<?= icon('chevron-down') ?>
</button>
<label class="map-group-label">
<input type="checkbox" class="map-group-checkbox" checked>
<span class="map-group-icon"><?= e((string) $group['icon']) ?></span>
<span class="map-group-name"><?= e((string) $group['name']) ?></span>
</label>
<span class="map-count"><?= (int) $group['total_count'] ?></span>
<?php if ($canManageMap && (int) $group['id'] > 0): ?>
<button type="button" class="icon-button map-category-edit"
data-category-id="<?= (int) $group['id'] ?>"
data-parent-id="0"
data-name="<?= e((string) $group['name']) ?>"
data-icon="<?= e((string) $group['icon']) ?>"
data-color="<?= e((string) $group['color']) ?>"
title="Gruppe bearbeiten"><?= icon('edit') ?></button>
<?php endif; ?>
</div>
<div class="map-group-children">
<?php foreach ($group['children'] as $child): ?>
<div class="map-category" data-category-id="<?= (int) $child['id'] ?>" data-name="<?= e((string) $child['name']) ?>">
<label class="map-category-label">
<input type="checkbox" class="map-category-checkbox" value="<?= (int) $child['id'] ?>" checked>
<span class="map-category-icon" style="background: <?= e((string) $child['color']) ?>;"><?= e((string) $child['icon']) ?></span>
<span class="map-category-name"><?= e((string) $child['name']) ?></span>
</label>
<span class="map-count"><?= (int) $child['marker_count'] ?></span>
<?php if ($canManageMap): ?>
<button type="button" class="icon-button map-category-edit"
data-category-id="<?= (int) $child['id'] ?>"
data-parent-id="<?= (int) $group['id'] ?>"
data-name="<?= e((string) $child['name']) ?>"
data-icon="<?= e((string) $child['icon']) ?>"
data-color="<?= e((string) $child['color']) ?>"
title="Kategorie bearbeiten"><?= icon('edit') ?></button>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php if ($canManageMap): ?>
<button type="button" class="button-secondary map-add-category" id="map-add-category">+ Kategorie</button>
<?php endif; ?>
<?php endif; ?>
</div>
<div class="map-panel" data-panel="tactics" hidden>
<?php if (empty($tactics)): ?>
<p class="text-muted" id="map-tactics-empty">Noch keine Taktiken angelegt.</p>
<?php endif; ?>
<div class="map-tactic-list" id="map-tactic-list">
<?php foreach ($tactics as $tactic): ?>
<div class="map-tactic" data-tactic-id="<?= (int) $tactic['id'] ?>">
<label class="map-tactic-label">
<input type="checkbox" class="map-tactic-checkbox" value="<?= (int) $tactic['id'] ?>">
<span class="map-tactic-name"><?= e($tactic['name']) ?></span>
</label>
<span class="map-count"><?= count($tactic['shapes']) ?></span>
<?php if ($canEditTactics): ?>
<button type="button" class="icon-button map-tactic-edit" title="Taktik bearbeiten"><?= icon('edit') ?></button>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php if ($canEditTactics): ?>
<button type="button" class="button-secondary map-add-tactic" id="map-add-tactic">+ Neue Taktik</button>
<?php endif; ?>
</div>
</div>
<div class="map-stage">
<div class="map-toolbar">
<?php if ($canManageMap): ?>
<button type="button" class="map-tool" id="map-tool-marker" title="Marker setzen: Werkzeug aktivieren und auf die Karte klicken">
<?= icon('map-pin') ?><span>Marker setzen</span>
</button>
<?php endif; ?>
<?php if ($canEditTactics): ?>
<div class="map-tool-group" id="map-tactic-tools" hidden>
<span class="map-tool-group-label" id="map-tactic-active-name"></span>
<button type="button" class="map-tool" data-shape="point" title="Punkt/Sammelpunkt setzen"><?= icon('map-pin') ?><span>Punkt</span></button>
<button type="button" class="map-tool" data-shape="route" title="Route zeichnen: klicken für Punkte, Doppelklick beendet"><?= icon('route') ?><span>Route</span></button>
<button type="button" class="map-tool" data-shape="area" title="Fläche zeichnen: klicken für Eckpunkte, Doppelklick beendet"><?= icon('area') ?><span>Fläche</span></button>
<button type="button" class="map-tool" data-shape="text" title="Textnotiz setzen"><?= icon('edit') ?><span>Notiz</span></button>
<input type="color" id="map-shape-color" value="#c9a227" title="Farbe für neue Objekte">
<button type="button" class="map-tool map-tool-finish" id="map-shape-finish" hidden
title="Route/Fläche abschließen (geht auch per Doppelklick oder Enter)">
<?= icon('check') ?><span>Abschließen</span>
</button>
<button type="button" class="map-tool map-tool-done" id="map-tactic-close" title="Taktik-Bearbeitung beenden"><?= icon('x') ?><span>Fertig</span></button>
</div>
<?php endif; ?>
<div class="map-toolbar-spacer"></div>
<span class="map-coords" id="map-coords" title="Position des Mauszeigers"></span>
<button type="button" class="map-tool" id="map-reset-view" title="Ansicht zurücksetzen"><?= icon('restore') ?><span>Ansicht</span></button>
</div>
<div id="map-canvas" class="map-canvas"></div>
<p class="map-status text-muted" id="map-status"></p>
</div>
</div>
<!-- Marker anlegen/bearbeiten -->
<div class="modal-overlay" id="map-marker-modal" hidden>
<div class="modal">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2 id="map-marker-modal-title">Marker anlegen</h2>
<form id="map-marker-form">
<input type="hidden" name="marker_id" value="">
<input type="hidden" name="x" value="">
<input type="hidden" name="y" value="">
<div>
<label>Name</label>
<input type="text" name="name" maxlength="120" placeholder="z. B. Orihalum-Ader">
</div>
<div>
<label>Kategorie</label>
<select name="category_id">
<?php
$lastGroup = null;
foreach ($flatCategories as $category):
if ($category['group'] !== $lastGroup):
if ($lastGroup !== null): ?></optgroup><?php endif; ?>
<optgroup label="<?= e($category['group']) ?>">
<?php $lastGroup = $category['group'];
endif; ?>
<option value="<?= (int) $category['id'] ?>"><?= e($category['icon'] . ' ' . $category['name']) ?></option>
<?php endforeach;
if ($lastGroup !== null): ?></optgroup><?php endif; ?>
</select>
</div>
<div>
<label>Beschreibung <span class="text-muted">(optional)</span></label>
<textarea name="description" rows="3" placeholder="z. B. Respawn ca. 5 Min., 3er-Gruppe empfohlen"></textarea>
</div>
<div class="actions">
<button type="submit">Speichern</button>
<button type="button" class="button-secondary" id="map-marker-cancel">Abbrechen</button>
<button type="button" class="icon-button icon-button-danger" id="map-marker-delete" title="Marker löschen" hidden><?= icon('trash') ?></button>
<span class="map-feedback text-muted"></span>
</div>
</form>
</div>
</div>
<!-- Kategorie anlegen/bearbeiten -->
<div class="modal-overlay" id="map-category-modal" hidden>
<div class="modal">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2 id="map-category-modal-title">Kategorie anlegen</h2>
<form id="map-category-form">
<input type="hidden" name="category_id" value="">
<div>
<label>Gruppe</label>
<select name="parent_id">
<option value="0">– Eigene Gruppe (Überschrift) –</option>
<?php foreach ($categoryTree as $group): ?>
<?php if ((int) $group['id'] > 0): ?>
<option value="<?= (int) $group['id'] ?>"><?= e((string) $group['name']) ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div>
<label>Name</label>
<input type="text" name="name" maxlength="80" placeholder="z. B. Orihalum-Erz">
</div>
<div class="map-category-form-row">
<div>
<label>Symbol</label>
<input type="text" name="icon" maxlength="4" placeholder="⛏">
</div>
<div>
<label>Farbe</label>
<input type="color" name="color" value="#c9a227">
</div>
</div>
<div class="actions">
<button type="submit">Speichern</button>
<button type="button" class="button-secondary" id="map-category-cancel">Abbrechen</button>
<button type="button" class="icon-button icon-button-danger" id="map-category-delete" title="Kategorie mitsamt ihren Markern löschen" hidden><?= icon('trash') ?></button>
<span class="map-feedback text-muted"></span>
</div>
</form>
</div>
</div>
<!-- Beschriftung fuer ein neu gezeichnetes Taktik-Objekt -->
<div class="modal-overlay" id="map-shape-modal" hidden>
<div class="modal">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2 id="map-shape-modal-title">Objekt beschriften</h2>
<form id="map-shape-form">
<div>
<label>Beschriftung <span class="text-muted" id="map-shape-label-hint">(optional)</span></label>
<input type="text" name="label" maxlength="120" placeholder="z. B. Sammelpunkt">
</div>
<div>
<label>Farbe</label>
<input type="color" name="color" value="#c9a227">
</div>
<div class="actions">
<button type="submit">Übernehmen</button>
<button type="button" class="button-secondary" id="map-shape-cancel">Abbrechen</button>
<span class="map-feedback text-muted"></span>
</div>
</form>
</div>
</div>
<!-- Taktik anlegen/bearbeiten -->
<div class="modal-overlay" id="map-tactic-modal" hidden>
<div class="modal">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2 id="map-tactic-modal-title">Taktik anlegen</h2>
<form id="map-tactic-form">
<input type="hidden" name="tactic_id" value="">
<div>
<label>Name</label>
<input type="text" name="name" maxlength="120" placeholder="z. B. Festung Verteron - Angriff Süd">
</div>
<div>
<label>Beschreibung <span class="text-muted">(optional)</span></label>
<textarea name="description" rows="3" placeholder="Ablauf, Rollenverteilung, Timings …"></textarea>
</div>
<div class="actions">
<button type="submit">Speichern &amp; bearbeiten</button>
<button type="button" class="button-secondary" id="map-tactic-cancel">Abbrechen</button>
<button type="button" class="icon-button icon-button-danger" id="map-tactic-delete" title="Taktik löschen" hidden><?= icon('trash') ?></button>
<span class="map-feedback text-muted"></span>
</div>
</form>
</div>
</div>
<script id="map-data" type="application/json"><?= json_encode([
'manifest' => [
'width' => (int) $manifest['width'],
'height' => (int) $manifest['height'],
'tile_size' => (int) ($manifest['tile_size'] ?? 256),
'min_zoom' => (int) ($manifest['min_zoom'] ?? 0),
'max_zoom' => (int) ($manifest['max_zoom'] ?? 0),
'url_template' => (string) $manifest['url_template'],
'name' => (string) $manifest['name'],
],
'categories' => $flatCategories,
'markers' => $markers,
'tactics' => $tactics,
], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?></script>
<script src="/assets/vendor/leaflet/leaflet.js"></script>
<script src="/assets/js/map.js"></script>
<?php endif; ?>
<?php include __DIR__ . '/includes/footer.php'; ?>

294
map_action.php Normal file
View file

@ -0,0 +1,294 @@
<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/map.php';
require_permission('map.view');
$input = read_json_body();
verify_csrf_token($input['csrf_token'] ?? '');
$action = (string) ($input['action'] ?? '');
$user = current_user();
$userId = (int) $user['id'];
$canManage = user_has_permission('map.manage');
$canTactics = user_has_permission('map.tactics');
$mapKey = trim((string) ($input['map_key'] ?? ''));
if ($mapKey === '' || !array_key_exists($mapKey, map_available())) {
json_response(false, 'Unbekannte Karte.');
}
/** Bricht mit einer Fehlermeldung ab, wenn die noetige Berechtigung fehlt. */
function map_require(bool $allowed, string $message): void
{
if (!$allowed) {
json_response(false, $message);
}
}
try {
switch ($action) {
// ---- Marker ----
case 'marker_save':
map_require($canManage, 'Du darfst keine Marker verwalten.');
$markerId = (int) ($input['marker_id'] ?? 0);
$categoryId = (int) ($input['category_id'] ?? 0);
$name = trim((string) ($input['name'] ?? ''));
$description = trim((string) ($input['description'] ?? ''));
$x = $input['x'] ?? null;
$y = $input['y'] ?? null;
if ($name === '') {
json_response(false, 'Bitte einen Namen für den Marker angeben.');
}
if (mb_strlen($name) > 120) {
json_response(false, 'Der Name darf höchstens 120 Zeichen lang sein.');
}
if (!map_valid_coordinate($x) || !map_valid_coordinate($y)) {
json_response(false, 'Die Position liegt außerhalb der Karte.');
}
// Nur Kategorien der zweiten Ebene koennen Marker tragen - eine Gruppe
// ("Ressourcen") ist nur eine Ueberschrift in der Sidebar.
$catStmt = db()->prepare('SELECT parent_id FROM map_categories WHERE id = ?');
$catStmt->execute([$categoryId]);
$category = $catStmt->fetch();
if (!$category) {
json_response(false, 'Bitte eine Kategorie auswählen.');
}
if ($category['parent_id'] === null) {
json_response(false, 'Bitte eine Unterkategorie auswählen, keine Gruppe.');
}
if ($markerId > 0) {
$stmt = db()->prepare(
'UPDATE map_markers SET category_id = ?, name = ?, description = ?, pos_x = ?, pos_y = ?, updated_at = NOW()
WHERE id = ? AND map_key = ?'
);
$stmt->execute([$categoryId, $name, $description, (float) $x, (float) $y, $markerId, $mapKey]);
json_response(true, 'Marker gespeichert.', ['marker_id' => $markerId]);
}
$stmt = db()->prepare(
'INSERT INTO map_markers (map_key, category_id, name, description, pos_x, pos_y, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?)'
);
$stmt->execute([$mapKey, $categoryId, $name, $description, (float) $x, (float) $y, $userId]);
json_response(true, 'Marker angelegt.', ['marker_id' => (int) db()->lastInsertId()]);
// no break - json_response() beendet den Request
case 'marker_move':
map_require($canManage, 'Du darfst keine Marker verwalten.');
$markerId = (int) ($input['marker_id'] ?? 0);
$x = $input['x'] ?? null;
$y = $input['y'] ?? null;
if ($markerId <= 0 || !map_valid_coordinate($x) || !map_valid_coordinate($y)) {
json_response(false, 'Ungültige Position.');
}
$stmt = db()->prepare('UPDATE map_markers SET pos_x = ?, pos_y = ?, updated_at = NOW() WHERE id = ? AND map_key = ?');
$stmt->execute([(float) $x, (float) $y, $markerId, $mapKey]);
json_response(true, 'Marker verschoben.');
case 'marker_delete':
map_require($canManage, 'Du darfst keine Marker verwalten.');
$markerId = (int) ($input['marker_id'] ?? 0);
if ($markerId <= 0) {
json_response(false, 'Ungültiger Marker.');
}
$stmt = db()->prepare('DELETE FROM map_markers WHERE id = ? AND map_key = ?');
$stmt->execute([$markerId, $mapKey]);
json_response(true, 'Marker gelöscht.');
// ---- Kategorien ----
case 'category_save':
map_require($canManage, 'Du darfst keine Kategorien verwalten.');
$categoryId = (int) ($input['category_id'] ?? 0);
$parentId = (int) ($input['parent_id'] ?? 0);
$name = trim((string) ($input['name'] ?? ''));
$icon = trim((string) ($input['icon'] ?? ''));
$color = trim((string) ($input['color'] ?? '#c9a227'));
if ($name === '' || mb_strlen($name) > 80) {
json_response(false, 'Bitte einen Namen mit höchstens 80 Zeichen angeben.');
}
if (mb_strlen($icon) > 4) {
json_response(false, 'Das Symbol darf höchstens 4 Zeichen lang sein (z.B. ein Emoji).');
}
if (!map_valid_color($color)) {
json_response(false, 'Ungültige Farbe.');
}
// Nur zwei Ebenen: eine Gruppe darf keine Gruppe als Elternteil haben.
if ($parentId > 0) {
$parentStmt = db()->prepare('SELECT parent_id FROM map_categories WHERE id = ?');
$parentStmt->execute([$parentId]);
$parent = $parentStmt->fetch();
if (!$parent || $parent['parent_id'] !== null) {
json_response(false, 'Ungültige Gruppe ausgewählt.');
}
}
if ($categoryId > 0) {
$stmt = db()->prepare('UPDATE map_categories SET parent_id = ?, name = ?, icon = ?, color = ? WHERE id = ?');
$stmt->execute([$parentId > 0 ? $parentId : null, $name, $icon, $color, $categoryId]);
json_response(true, 'Kategorie gespeichert.');
}
$sortStmt = db()->prepare('SELECT COALESCE(MAX(sort_order), 0) + 10 FROM map_categories WHERE parent_id <=> ?');
$sortStmt->execute([$parentId > 0 ? $parentId : null]);
$sortOrder = (int) $sortStmt->fetchColumn();
$stmt = db()->prepare('INSERT INTO map_categories (parent_id, name, icon, color, sort_order) VALUES (?, ?, ?, ?, ?)');
$stmt->execute([$parentId > 0 ? $parentId : null, $name, $icon, $color, $sortOrder]);
json_response(true, 'Kategorie angelegt.', ['category_id' => (int) db()->lastInsertId()]);
case 'category_delete':
map_require($canManage, 'Du darfst keine Kategorien verwalten.');
$categoryId = (int) ($input['category_id'] ?? 0);
if ($categoryId <= 0) {
json_response(false, 'Ungültige Kategorie.');
}
// Loescht per ON DELETE CASCADE auch Unterkategorien und deren Marker.
$stmt = db()->prepare('DELETE FROM map_categories WHERE id = ?');
$stmt->execute([$categoryId]);
json_response(true, 'Kategorie gelöscht.');
case 'category_seed':
map_require($canManage, 'Du darfst keine Kategorien verwalten.');
$existing = (int) db()->query('SELECT COUNT(*) FROM map_categories')->fetchColumn();
if ($existing > 0) {
json_response(false, 'Es gibt bereits Kategorien - die Startbestückung ist nur für eine leere Liste gedacht.');
}
$created = map_seed_default_categories();
json_response(true, $created . ' Kategorien wurden angelegt.');
// ---- Taktiken ----
case 'tactic_save':
map_require($canTactics, 'Du darfst keine Taktiken verwalten.');
$tacticId = (int) ($input['tactic_id'] ?? 0);
$name = trim((string) ($input['name'] ?? ''));
$description = trim((string) ($input['description'] ?? ''));
if ($name === '' || mb_strlen($name) > 120) {
json_response(false, 'Bitte einen Namen mit höchstens 120 Zeichen angeben.');
}
if ($tacticId > 0) {
$stmt = db()->prepare('UPDATE map_tactics SET name = ?, description = ?, updated_at = NOW() WHERE id = ? AND map_key = ?');
$stmt->execute([$name, $description, $tacticId, $mapKey]);
json_response(true, 'Taktik gespeichert.', ['tactic_id' => $tacticId]);
}
$stmt = db()->prepare('INSERT INTO map_tactics (map_key, name, description, created_by) VALUES (?, ?, ?, ?)');
$stmt->execute([$mapKey, $name, $description, $userId]);
json_response(true, 'Taktik angelegt.', ['tactic_id' => (int) db()->lastInsertId()]);
case 'tactic_delete':
map_require($canTactics, 'Du darfst keine Taktiken verwalten.');
$tacticId = (int) ($input['tactic_id'] ?? 0);
if ($tacticId <= 0) {
json_response(false, 'Ungültige Taktik.');
}
$stmt = db()->prepare('DELETE FROM map_tactics WHERE id = ? AND map_key = ?');
$stmt->execute([$tacticId, $mapKey]);
json_response(true, 'Taktik gelöscht.');
case 'shape_save':
map_require($canTactics, 'Du darfst keine Taktiken verwalten.');
$tacticId = (int) ($input['tactic_id'] ?? 0);
$shapeId = (int) ($input['shape_id'] ?? 0);
$type = (string) ($input['type'] ?? '');
$label = trim((string) ($input['label'] ?? ''));
$color = trim((string) ($input['color'] ?? '#c9a227'));
$points = $input['points'] ?? null;
if (!in_array($type, ['point', 'route', 'area', 'text'], true)) {
json_response(false, 'Unbekannter Objekttyp.');
}
if (!map_valid_color($color)) {
json_response(false, 'Ungültige Farbe.');
}
if (mb_strlen($label) > 120) {
json_response(false, 'Die Beschriftung darf höchstens 120 Zeichen lang sein.');
}
if (!is_array($points) || empty($points)) {
json_response(false, 'Dem Objekt fehlen Punkte.');
}
// Routen/Flaechen brauchen mehrere Stuetzpunkte, Punkte/Texte genau einen.
$minPoints = in_array($type, ['route', 'area'], true) ? 2 : 1;
if (count($points) < $minPoints) {
json_response(false, 'Bitte mindestens ' . $minPoints . ' Punkte setzen.');
}
$clean = [];
foreach ($points as $point) {
if (!is_array($point) || count($point) !== 2
|| !map_valid_coordinate($point[0]) || !map_valid_coordinate($point[1])) {
json_response(false, 'Ein Punkt liegt außerhalb der Karte.');
}
$clean[] = [round((float) $point[0], 6), round((float) $point[1], 6)];
}
$ownerStmt = db()->prepare('SELECT id FROM map_tactics WHERE id = ? AND map_key = ?');
$ownerStmt->execute([$tacticId, $mapKey]);
if (!$ownerStmt->fetch()) {
json_response(false, 'Die Taktik wurde nicht gefunden.');
}
$encoded = json_encode($clean, JSON_UNESCAPED_UNICODE);
if ($shapeId > 0) {
$stmt = db()->prepare(
'UPDATE map_tactic_shapes SET shape_type = ?, label = ?, color = ?, points = ?
WHERE id = ? AND tactic_id = ?'
);
$stmt->execute([$type, $label, $color, $encoded, $shapeId, $tacticId]);
} else {
$sortStmt = db()->prepare('SELECT COALESCE(MAX(sort_order), 0) + 10 FROM map_tactic_shapes WHERE tactic_id = ?');
$sortStmt->execute([$tacticId]);
$sortOrder = (int) $sortStmt->fetchColumn();
$stmt = db()->prepare(
'INSERT INTO map_tactic_shapes (tactic_id, shape_type, label, color, points, sort_order)
VALUES (?, ?, ?, ?, ?, ?)'
);
$stmt->execute([$tacticId, $type, $label, $color, $encoded, $sortOrder]);
$shapeId = (int) db()->lastInsertId();
}
db()->prepare('UPDATE map_tactics SET updated_at = NOW() WHERE id = ?')->execute([$tacticId]);
json_response(true, 'Objekt gespeichert.', ['shape_id' => $shapeId]);
case 'shape_delete':
map_require($canTactics, 'Du darfst keine Taktiken verwalten.');
$shapeId = (int) ($input['shape_id'] ?? 0);
if ($shapeId <= 0) {
json_response(false, 'Ungültiges Objekt.');
}
// Ueber den Join sicherstellen, dass das Objekt wirklich zu dieser Karte gehoert.
$stmt = db()->prepare(
'DELETE s FROM map_tactic_shapes s
JOIN map_tactics t ON t.id = s.tactic_id
WHERE s.id = ? AND t.map_key = ?'
);
$stmt->execute([$shapeId, $mapKey]);
json_response(true, 'Objekt gelöscht.');
default:
json_response(false, 'Unbekannte Aktion.');
}
} catch (Throwable $e) {
json_response(false, 'Aktion fehlgeschlagen: ' . $e->getMessage());
}

View file

@ -55,3 +55,69 @@ CREATE TABLE IF NOT EXISTS user_roles (
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------------------------
-- Taktikkarte
-- --------------------------------------------------------------------------
-- Kategorien sind zweistufig: Zeilen ohne parent_id sind Gruppen ("Ressourcen"),
-- Zeilen mit parent_id die eigentlichen Marker-Kategorien ("Orihalum-Erz").
CREATE TABLE IF NOT EXISTS map_categories (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
parent_id INT UNSIGNED NULL,
name VARCHAR(80) NOT NULL,
-- Kurzes Zeichen (Emoji) fuer die Marker-Nadel, z.B. "⛏" oder "🐉".
icon VARCHAR(16) NOT NULL DEFAULT '',
color VARCHAR(7) NOT NULL DEFAULT '#c9a227',
sort_order INT NOT NULL DEFAULT 0,
FOREIGN KEY (parent_id) REFERENCES map_categories(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- pos_x/pos_y sind auf 0..1 normiert (Anteil der Kartenbreite/-hoehe), damit die
-- Marker unabhaengig von Zoomstufe, Kachelgroesse und Bildaufloesung sitzen und ein
-- spaeter neu gekacheltes Kartenbild sie nicht verschiebt.
CREATE TABLE IF NOT EXISTS map_markers (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
map_key VARCHAR(50) NOT NULL DEFAULT 'verteron',
category_id INT UNSIGNED NOT NULL,
name VARCHAR(120) NOT NULL,
description TEXT NULL,
pos_x DECIMAL(9,6) NOT NULL,
pos_y DECIMAL(9,6) NOT NULL,
created_by INT UNSIGNED NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NULL,
FOREIGN KEY (category_id) REFERENCES map_categories(id) ON DELETE CASCADE,
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
INDEX idx_map_markers_map (map_key),
INDEX idx_map_markers_category (category_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Eine Taktik ist eine eigene Zeichenebene ueber der Karte (Sammelpunkte, Routen,
-- Zonen, Notizen), die sich ein- und ausblenden laesst.
CREATE TABLE IF NOT EXISTS map_tactics (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
map_key VARCHAR(50) NOT NULL DEFAULT 'verteron',
name VARCHAR(120) NOT NULL,
description TEXT NULL,
created_by INT UNSIGNED NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NULL,
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
INDEX idx_map_tactics_map (map_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- points enthaelt die Stuetzpunkte als JSON-Array [[x,y], ...] mit denselben
-- normierten Koordinaten wie map_markers (TEXT statt JSON, damit auch aeltere
-- MySQL-/MariaDB-Versionen ohne JSON-Typ funktionieren).
CREATE TABLE IF NOT EXISTS map_tactic_shapes (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
tactic_id INT UNSIGNED NOT NULL,
shape_type ENUM('point', 'route', 'area', 'text') NOT NULL,
label VARCHAR(120) NOT NULL DEFAULT '',
color VARCHAR(7) NOT NULL DEFAULT '#c9a227',
points TEXT NOT NULL,
sort_order INT NOT NULL DEFAULT 0,
FOREIGN KEY (tactic_id) REFERENCES map_tactics(id) ON DELETE CASCADE,
INDEX idx_map_shapes_tactic (tactic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

193
tools/make_map_tiles.php Normal file
View file

@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
/**
* Zerlegt ein grosses Kartenbild in eine Kachel-Pyramide fuer die Taktikkarte (map.php).
*
* Aufruf (lokal, nicht auf dem Webspace noetig):
*
* php tools/make_map_tiles.php <kartenschluessel> <bilddatei> [--name="Anzeigename"]
* [--tile-size=256] [--quality=82] [--out=<zielordner>]
*
* Beispiel:
*
* php -d memory_limit=2G tools/make_map_tiles.php verteron "C:\Bilder\verteron.png" --name="Verteron"
*
* Ergebnis landet in assets/uploads/maps/<kartenschluessel>/ und besteht aus einem Ordner
* je Zoomstufe plus einer tiles.json, ueber die sich die Karte selbst beschreibt. Diesen
* Ordner danach einfach per FTP hochladen - map.php findet ihn von allein.
*
* Die oberste Zoomstufe zeigt das Bild in Originalaufloesung, jede Stufe darunter ist halb
* so gross, bis die ganze Karte in eine einzige Kachel passt. Randkacheln werden auf die
* volle Kachelgroesse aufgefuellt (mit der Hintergrundfarbe der Website), damit Leaflet sie
* nicht verzerrt.
*/
if (PHP_SAPI !== 'cli') {
fwrite(STDERR, "Dieses Script laeuft nur auf der Kommandozeile.\n");
exit(1);
}
if (!extension_loaded('gd')) {
fwrite(STDERR, "Die PHP-Erweiterung GD wird benoetigt (php.ini: extension=gd).\n");
exit(1);
}
$args = array_slice($argv, 1);
$positional = [];
$options = ['name' => null, 'tile-size' => 256, 'quality' => 82, 'out' => null];
foreach ($args as $arg) {
if (str_starts_with($arg, '--')) {
[$key, $value] = array_pad(explode('=', substr($arg, 2), 2), 2, '');
if (!array_key_exists($key, $options)) {
fwrite(STDERR, "Unbekannte Option: --$key\n");
exit(1);
}
$options[$key] = $value;
} else {
$positional[] = $arg;
}
}
if (count($positional) < 2) {
fwrite(STDERR, "Aufruf: php tools/make_map_tiles.php <kartenschluessel> <bilddatei> [--name=\"Anzeigename\"]\n");
exit(1);
}
[$mapKey, $sourcePath] = $positional;
if (preg_match('/^[a-z0-9_-]+$/', $mapKey) !== 1) {
fwrite(STDERR, "Der Kartenschluessel darf nur Kleinbuchstaben, Ziffern, - und _ enthalten (z.B. 'verteron').\n");
exit(1);
}
if (!is_file($sourcePath)) {
fwrite(STDERR, "Bilddatei nicht gefunden: $sourcePath\n");
exit(1);
}
$tileSize = max(64, (int) $options['tile-size']);
$quality = min(100, max(40, (int) $options['quality']));
$displayName = $options['name'] !== null && $options['name'] !== '' ? (string) $options['name'] : ucfirst($mapKey);
$outputRoot = $options['out'] !== null && $options['out'] !== ''
? rtrim((string) $options['out'], '/\\')
: __DIR__ . '/../assets/uploads/maps/' . $mapKey;
echo "Lade Bild …\n";
$source = load_image($sourcePath);
$width = imagesx($source);
$height = imagesy($source);
echo "Quellbild: {$width} x {$height} Pixel\n";
// Hoechste Zoomstufe = Originalgroesse. Kleinste Stufe = das ganze Bild passt in eine Kachel.
$maxZoom = (int) max(0, ceil(log(max($width, $height) / $tileSize, 2)));
$minZoom = 0;
echo "Zoomstufen: {$minZoom} bis {$maxZoom} (Kachelgroesse {$tileSize}px)\n";
if (!is_dir($outputRoot) && !mkdir($outputRoot, 0775, true) && !is_dir($outputRoot)) {
fwrite(STDERR, "Zielordner konnte nicht angelegt werden: $outputRoot\n");
exit(1);
}
$totalTiles = 0;
for ($zoom = $maxZoom; $zoom >= $minZoom; $zoom--) {
$scale = 2 ** ($zoom - $maxZoom);
$levelWidth = max(1, (int) round($width * $scale));
$levelHeight = max(1, (int) round($height * $scale));
echo "Zoom {$zoom}: {$levelWidth} x {$levelHeight} … ";
$level = $zoom === $maxZoom ? $source : resize_image($source, $levelWidth, $levelHeight);
$cols = (int) ceil($levelWidth / $tileSize);
$rows = (int) ceil($levelHeight / $tileSize);
$zoomDir = $outputRoot . '/' . $zoom;
if (!is_dir($zoomDir) && !mkdir($zoomDir, 0775, true) && !is_dir($zoomDir)) {
fwrite(STDERR, "\nOrdner konnte nicht angelegt werden: $zoomDir\n");
exit(1);
}
// Kein imagedestroy() noetig: GD-Bilder raeumt PHP seit 8.0 selbst auf, und seit 8.5
// ist die Funktion als deprecated markiert.
for ($x = 0; $x < $cols; $x++) {
for ($y = 0; $y < $rows; $y++) {
$tile = imagecreatetruecolor($tileSize, $tileSize);
// Randkacheln auf volle Groesse auffuellen - in der Hintergrundfarbe der
// Website, damit der Uebergang am Kartenrand nicht auffaellt.
imagefill($tile, 0, 0, imagecolorallocate($tile, 0x14, 0x16, 0x1a));
$srcX = $x * $tileSize;
$srcY = $y * $tileSize;
$copyWidth = min($tileSize, $levelWidth - $srcX);
$copyHeight = min($tileSize, $levelHeight - $srcY);
imagecopy($tile, $level, 0, 0, $srcX, $srcY, $copyWidth, $copyHeight);
imagejpeg($tile, $zoomDir . '/' . $x . '_' . $y . '.jpg', $quality);
$totalTiles++;
}
}
echo $cols * $rows . " Kacheln\n";
}
$manifest = [
'name' => $displayName,
'width' => $width,
'height' => $height,
'tile_size' => $tileSize,
'min_zoom' => $minZoom,
'max_zoom' => $maxZoom,
'extension' => 'jpg',
'generated_at' => date('c'),
];
file_put_contents(
$outputRoot . '/tiles.json',
json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);
echo "\nFertig: {$totalTiles} Kacheln in {$outputRoot}\n";
echo "Diesen Ordner nach assets/uploads/maps/{$mapKey}/ auf den Webspace hochladen.\n";
/**
* Laedt JPEG, PNG oder WebP als GD-Bild.
*
* @return GdImage
*/
function load_image(string $path)
{
$info = @getimagesize($path);
if ($info === false) {
fwrite(STDERR, "Datei ist kein unterstuetztes Bild: $path\n");
exit(1);
}
$image = match ($info[2]) {
IMAGETYPE_JPEG => @imagecreatefromjpeg($path),
IMAGETYPE_PNG => @imagecreatefrompng($path),
IMAGETYPE_WEBP => @imagecreatefromwebp($path),
default => false,
};
if ($image === false) {
fwrite(STDERR, "Bild konnte nicht geladen werden (JPEG, PNG und WebP werden unterstuetzt).\n");
fwrite(STDERR, "Bei sehr grossen Bildern hilft ein hoeheres Speicherlimit: php -d memory_limit=2G ...\n");
exit(1);
}
return $image;
}
/**
* @param GdImage $source
* @return GdImage
*/
function resize_image($source, int $width, int $height)
{
$resized = imagecreatetruecolor($width, $height);
imagecopyresampled($resized, $source, 0, 0, 0, 0, $width, $height, imagesx($source), imagesy($source));
return $resized;
}