270 lines
9.2 KiB
PHP
270 lines
9.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Datenschicht der Taktiken auf der Karte. Die Karte selbst ist ein statischer Viewer
|
|
* (assets/map/), nur die Taktiken liegen in der Website-Datenbank - der Discord-Bot ist
|
|
* daran nicht beteiligt.
|
|
*/
|
|
|
|
// Die Tabellen in Anlegereihenfolge (Fremdschluessel!).
|
|
const TACTIC_TABLES = ['tactics', 'tactic_steps', 'tactic_shapes'];
|
|
|
|
const TACTIC_SHAPE_TYPES = ['pen', 'line', 'arrow', 'area', 'circle', 'point', 'text'];
|
|
|
|
// Die Weltkoordinaten der Karte laufen von 0 bis 4096. Etwas Luft rundherum, damit ein
|
|
// Pfeil auch knapp ueber den Kartenrand hinaus zeigen darf.
|
|
const TACTIC_COORD_MIN = -512.0;
|
|
const TACTIC_COORD_MAX = 4608.0;
|
|
|
|
// Freihandlinien werden im Browser vereinfacht - mehr Punkte kommen normal nicht zusammen.
|
|
const TACTIC_MAX_POINTS = 4000;
|
|
|
|
/**
|
|
* Welche der Taktik-Tabellen fehlen noch? Bestehende Installationen kennen sie nicht -
|
|
* ohne diese Pruefung wuerde die erste Abfrage mit einer PDOException aussteigen.
|
|
*
|
|
* @return array<int, string>
|
|
*/
|
|
function tactics_missing_tables(): array
|
|
{
|
|
$placeholders = implode(',', array_fill(0, count(TACTIC_TABLES), '?'));
|
|
$stmt = db()->prepare(
|
|
"SELECT table_name FROM information_schema.tables
|
|
WHERE table_schema = DATABASE() AND table_name IN ($placeholders)"
|
|
);
|
|
$stmt->execute(TACTIC_TABLES);
|
|
|
|
$existing = array_map('strtolower', $stmt->fetchAll(PDO::FETCH_COLUMN));
|
|
|
|
return array_values(array_filter(
|
|
TACTIC_TABLES,
|
|
static fn (string $table): bool => !in_array(strtolower($table), $existing, true)
|
|
));
|
|
}
|
|
|
|
/**
|
|
* Legt die fehlenden Tabellen an. Die Befehle kommen aus sql/schema.sql, damit es genau
|
|
* eine Quelle fuer die Struktur gibt. Alle sind "IF NOT EXISTS" - ein zweiter Aufruf
|
|
* richtet keinen Schaden an.
|
|
*
|
|
* @throws RuntimeException
|
|
*/
|
|
function tactics_create_tables(): void
|
|
{
|
|
$path = __DIR__ . '/../sql/schema.sql';
|
|
$schema = is_file($path) ? (string) file_get_contents($path) : '';
|
|
|
|
$statements = [];
|
|
foreach (TACTIC_TABLES as $table) {
|
|
$pattern = '/CREATE TABLE IF NOT EXISTS\s+' . preg_quote($table, '/') . '\s*\(.*?\)\s*ENGINE[^;]*;/s';
|
|
if (preg_match($pattern, $schema, $match) === 1) {
|
|
$statements[] = $match[0];
|
|
}
|
|
}
|
|
|
|
if (count($statements) !== count(TACTIC_TABLES)) {
|
|
throw new RuntimeException(
|
|
'sql/schema.sql wurde nicht gefunden oder enthält nicht alle Taktik-Tabellen - '
|
|
. 'bitte den Abschnitt "Taktiken auf der Karte" aus sql/schema.sql von Hand ausführen.'
|
|
);
|
|
}
|
|
|
|
foreach ($statements as $sql) {
|
|
db()->exec($sql);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Die Regionen der Karte, wie sie der Viewer kennt (assets/map/data/maps.json).
|
|
* Fehlt die Datei - etwa weil der Datenordner noch nicht hochgeladen ist - wird nur
|
|
* das Format des Kartennamens geprueft.
|
|
*/
|
|
function tactics_valid_map(string $slug): bool
|
|
{
|
|
if (preg_match('/^[a-z0-9-]{1,60}$/', $slug) !== 1) {
|
|
return false;
|
|
}
|
|
|
|
static $slugs = null;
|
|
if ($slugs === null) {
|
|
$slugs = [];
|
|
$path = __DIR__ . '/../assets/map/data/maps.json';
|
|
$data = is_file($path) ? json_decode((string) file_get_contents($path), true) : null;
|
|
foreach ((is_array($data) ? ($data['maps'] ?? []) : []) as $map) {
|
|
if (isset($map['slug'])) {
|
|
$slugs[] = (string) $map['slug'];
|
|
}
|
|
}
|
|
}
|
|
|
|
return empty($slugs) || in_array($slug, $slugs, true);
|
|
}
|
|
|
|
const TACTIC_VISIBILITIES = ['private', 'public'];
|
|
const TACTIC_HIGHLIGHTS = ['none' => '', 'recommended' => 'Empfohlen', 'official' => 'Offiziell'];
|
|
|
|
/**
|
|
* Darf das aktuelle Konto diese Taktik bearbeiten (Name, Schritte, Zeichnungen, Loeschen)?
|
|
* Die eigene immer; fremde nur, wenn sie oeffentlich ist und man map.tactics hat. Private
|
|
* Taktiken anderer bleiben auch fuer die Leitung unsichtbar.
|
|
*
|
|
* @param array{created_by: mixed, visibility: string} $tactic
|
|
*/
|
|
function tactic_can_edit(array $tactic, int $userId): bool
|
|
{
|
|
if ((int) ($tactic['created_by'] ?? 0) === $userId) {
|
|
return true;
|
|
}
|
|
return ($tactic['visibility'] ?? '') === 'public' && user_has_permission('map.tactics');
|
|
}
|
|
|
|
/** Darf das aktuelle Konto die Taktik sehen? Oeffentliche alle, private nur der Ersteller. */
|
|
function tactic_can_view(array $tactic, int $userId): bool
|
|
{
|
|
return ($tactic['visibility'] ?? '') === 'public' || (int) ($tactic['created_by'] ?? 0) === $userId;
|
|
}
|
|
|
|
/**
|
|
* Alle Taktiken einer Region, die das Konto sehen darf, samt Schritten und Zeichnungen:
|
|
* oeffentliche und die eigenen privaten. Offizielle und empfohlene stehen vorn.
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
function tactics_for_map(string $slug, int $userId): array
|
|
{
|
|
$stmt = db()->prepare(
|
|
"SELECT t.id, t.name, t.description, t.visibility, t.highlight, t.created_by, t.created_at, t.updated_at,
|
|
COALESCE(NULLIF(u.display_name, ''), u.username) AS author,
|
|
COALESCE(NULLIF(h.display_name, ''), h.username) AS highlighted_by_name
|
|
FROM tactics t
|
|
LEFT JOIN users u ON u.id = t.created_by
|
|
LEFT JOIN users h ON h.id = t.highlighted_by
|
|
WHERE t.map_slug = ? AND (t.visibility = 'public' OR t.created_by = ?)
|
|
ORDER BY FIELD(t.highlight, 'official', 'recommended', 'none'), t.name, t.id"
|
|
);
|
|
$stmt->execute([$slug, $userId]);
|
|
|
|
$tactics = [];
|
|
foreach ($stmt->fetchAll() as $row) {
|
|
$isMine = (int) ($row['created_by'] ?? 0) === $userId;
|
|
$tactics[(int) $row['id']] = [
|
|
'id' => (int) $row['id'],
|
|
'name' => (string) $row['name'],
|
|
'description' => (string) ($row['description'] ?? ''),
|
|
'author' => (string) ($row['author'] ?? ''),
|
|
'is_mine' => $isMine,
|
|
'visibility' => (string) $row['visibility'],
|
|
'highlight' => (string) $row['highlight'],
|
|
'highlighted_by' => (string) ($row['highlighted_by_name'] ?? ''),
|
|
'can_edit' => tactic_can_edit($row, $userId),
|
|
'updated_at' => (string) ($row['updated_at'] ?? $row['created_at']),
|
|
'steps' => [],
|
|
];
|
|
}
|
|
if (empty($tactics)) {
|
|
return [];
|
|
}
|
|
|
|
$ids = array_keys($tactics);
|
|
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
|
|
|
$stepStmt = db()->prepare(
|
|
"SELECT id, tactic_id, title, description FROM tactic_steps
|
|
WHERE tactic_id IN ($placeholders) ORDER BY sort_order, id"
|
|
);
|
|
$stepStmt->execute($ids);
|
|
|
|
$steps = [];
|
|
foreach ($stepStmt->fetchAll() as $row) {
|
|
$steps[(int) $row['id']] = [
|
|
'id' => (int) $row['id'],
|
|
'tactic_id' => (int) $row['tactic_id'],
|
|
'title' => (string) $row['title'],
|
|
'description' => (string) ($row['description'] ?? ''),
|
|
'shapes' => [],
|
|
];
|
|
}
|
|
|
|
if (!empty($steps)) {
|
|
$stepIds = array_keys($steps);
|
|
$stepPlaceholders = implode(',', array_fill(0, count($stepIds), '?'));
|
|
$shapeStmt = db()->prepare(
|
|
"SELECT id, step_id, shape_type, label, color, width, points FROM tactic_shapes
|
|
WHERE step_id IN ($stepPlaceholders) ORDER BY id"
|
|
);
|
|
$shapeStmt->execute($stepIds);
|
|
|
|
foreach ($shapeStmt->fetchAll() as $row) {
|
|
$steps[(int) $row['step_id']]['shapes'][] = tactic_shape_row($row);
|
|
}
|
|
}
|
|
|
|
foreach ($steps as $step) {
|
|
$tacticId = $step['tactic_id'];
|
|
unset($step['tactic_id']);
|
|
$tactics[$tacticId]['steps'][] = $step;
|
|
}
|
|
|
|
return array_values($tactics);
|
|
}
|
|
|
|
/** @return array<string, mixed> */
|
|
function tactic_shape_row(array $row): array
|
|
{
|
|
$points = json_decode((string) $row['points'], true);
|
|
|
|
return [
|
|
'id' => (int) $row['id'],
|
|
'type' => (string) $row['shape_type'],
|
|
'label' => (string) $row['label'],
|
|
'color' => (string) $row['color'],
|
|
'width' => (int) $row['width'],
|
|
'points' => is_array($points) ? $points : [],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Prueft die Stuetzpunkte einer Zeichnung und gibt sie gerundet zurueck, oder null, wenn
|
|
* sie nicht zur Form passen.
|
|
*
|
|
* @return array<int, array{0: float, 1: float}>|null
|
|
*/
|
|
function tactic_clean_points($points, string $type): ?array
|
|
{
|
|
if (!is_array($points)) {
|
|
return null;
|
|
}
|
|
|
|
$clean = [];
|
|
foreach ($points as $point) {
|
|
if (!is_array($point) || count($point) !== 2) {
|
|
return null;
|
|
}
|
|
[$x, $y] = array_values($point);
|
|
if ((!is_int($x) && !is_float($x)) || (!is_int($y) && !is_float($y))) {
|
|
return null;
|
|
}
|
|
if ($x < TACTIC_COORD_MIN || $x > TACTIC_COORD_MAX || $y < TACTIC_COORD_MIN || $y > TACTIC_COORD_MAX) {
|
|
return null;
|
|
}
|
|
$clean[] = [round((float) $x, 2), round((float) $y, 2)];
|
|
}
|
|
|
|
$count = count($clean);
|
|
$valid = match ($type) {
|
|
'point', 'text' => $count === 1,
|
|
'line', 'arrow', 'circle' => $count === 2,
|
|
'pen' => $count >= 2 && $count <= TACTIC_MAX_POINTS,
|
|
'area' => $count >= 3 && $count <= TACTIC_MAX_POINTS,
|
|
default => false,
|
|
};
|
|
|
|
return $valid ? $clean : null;
|
|
}
|
|
|
|
/** Aktualisiert den Zeitstempel einer Taktik, damit die Liste zeigt, wann zuletzt gezeichnet wurde. */
|
|
function tactic_touch(int $tacticId): void
|
|
{
|
|
db()->prepare('UPDATE tactics SET updated_at = NOW() WHERE id = ?')->execute([$tacticId]);
|
|
}
|