LuminaWebsite/includes/raid_templates.php

149 lines
6 KiB
PHP

<?php
declare(strict_types=1);
/**
* Raid-Vorlagen (raids.php, raid_template_action.php): ein gespeicherter Stand des Formulars "Neuen Raid
* erstellen" - Titel, Uhrzeit, Plaetze, Gearscore, Anforderungen, Lumipunkte und die Gruppen samt Sperren.
* Je Bereich (Legion / Elyos Allianz) gemeinsam fuer alle, die dort Raids erstellen duerfen. Aendern und
* loeschen darf, wer sie angelegt hat, und wer im Bereich alle Raids verwalten darf.
* Premades gehoeren nicht dazu - die wechseln von Raid zu Raid.
*/
require_once __DIR__ . '/raids_api.php';
require_once __DIR__ . '/raid_attendance.php';
const RAID_TEMPLATE_NAME_MAX = 60;
const RAID_TEMPLATE_MAX_PER_AREA = 30;
/**
* Vorlagen eines Bereichs, nach Namen sortiert.
*
* @return list<array{id: int, name: string, data: array<string, mixed>, can_edit: bool}>
*/
function raid_templates_for_area(string $area): array
{
$stmt = db()->prepare('SELECT id, name, data, created_by FROM raid_templates WHERE area = ? ORDER BY name');
$stmt->execute([$area]);
$templates = [];
foreach ($stmt->fetchAll() as $row) {
$data = json_decode((string) $row['data'], true);
$templates[] = [
'id' => (int) $row['id'],
'name' => (string) $row['name'],
'data' => is_array($data) ? $data : [],
'can_edit' => raid_template_can_edit($row, $area),
];
}
return $templates;
}
/** Darf der aktuelle Nutzer diese Vorlage ueberschreiben oder loeschen? */
function raid_template_can_edit(array $row, string $area): bool
{
$createdBy = (int) ($row['created_by'] ?? 0);
return ($createdBy > 0 && $createdBy === (int) (current_user()['id'] ?? 0)) || raid_area_can_manage_all($area);
}
/**
* Prueft die Formularwerte einer Vorlage und bringt sie in eine feste Form.
* Leere Felder bleiben leer - beim Laden werden sie dann nicht ueberschrieben.
*
* @return array{0: array<string, mixed>|null, 1: string|null} [Daten, Fehlermeldung]
*/
function raid_template_clean(array $input): array
{
$text = static fn (string $key): string => trim((string) preg_replace('/\s+/u', ' ', (string) ($input[$key] ?? '')));
$title = $text('title');
$requirements = trim((string) ($input['requirements'] ?? ''));
$gearscore = $text('gearscore');
$time = $text('time');
if ($time !== '' && !preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time)) {
return [null, 'Die Uhrzeit der Vorlage ist ungültig.'];
}
foreach (['title' => $title, 'requirements' => $requirements] as $key => $value) {
[$label, $max] = RAID_FIELD_LIMITS[$key];
if (mb_strlen($value, 'UTF-8') > $max) {
return [null, $label . ': höchstens ' . $max . ' Zeichen.'];
}
}
if (mb_strlen($gearscore, 'UTF-8') > 6) {
return [null, 'Gearscore: höchstens 6 Zeichen.'];
}
$groups = [];
foreach (array_slice((array) ($input['groups'] ?? []), 0, RAID_MAX_GROUPS) as $group) {
// Gruppennamen gehen kommagetrennt an die API - Kommas wuerden sie aufteilen
$name = trim((string) preg_replace('/\s+/u', ' ', str_replace(',', ' ', (string) ($group['name'] ?? ''))));
if ($name === '') {
continue;
}
$groups[] = ['name' => mb_substr($name, 0, 60, 'UTF-8'), 'locked' => !empty($group['locked'])];
}
if ($groups === []) {
return [null, 'Eine Vorlage braucht mindestens eine Gruppe.'];
}
$maxSlots = (int) ($input['max_slots'] ?? 0);
$data = [
'title' => $title,
'time' => $time,
'max_slots' => $maxSlots >= 1 ? min($maxSlots, count($groups) * RAID_GROUP_SIZE) : count($groups) * RAID_GROUP_SIZE,
'gearscore' => $gearscore,
'requirements' => $requirements,
'groups' => $groups,
];
// Lumipunkte nur, wenn das Formular sie hatte (raids.points) - sonst gelten beim Erstellen die festen Werte
if (isset($input['points_present'], $input['points_absent'])) {
$data['points_present'] = max(0, min(RAID_POINTS_MAX, (int) $input['points_present']));
$data['points_absent'] = max(0, min(RAID_POINTS_MAX, (int) $input['points_absent']));
}
return [$data, null];
}
/**
* Speichert eine Vorlage. Gibt es im Bereich schon eine mit dem Namen, wird sie ueberschrieben -
* sofern der Nutzer das darf.
*
* @return string|null Fehlermeldung oder null
*/
function raid_template_save(string $area, string $name, array $data): ?string
{
$existing = db()->prepare('SELECT id, created_by FROM raid_templates WHERE area = ? AND name = ?');
$existing->execute([$area, $name]);
$row = $existing->fetch();
$json = (string) json_encode($data, JSON_UNESCAPED_UNICODE);
if ($row) {
if (!raid_template_can_edit($row, $area)) {
return 'Eine Vorlage „' . $name . '“ gibt es schon - und die darfst du nicht ändern. Bitte einen anderen Namen wählen.';
}
db()->prepare('UPDATE raid_templates SET data = ?, updated_at = NOW() WHERE id = ?')->execute([$json, (int) $row['id']]);
return null;
}
$count = db()->prepare('SELECT COUNT(*) FROM raid_templates WHERE area = ?');
$count->execute([$area]);
if ((int) $count->fetchColumn() >= RAID_TEMPLATE_MAX_PER_AREA) {
return 'Es gibt schon ' . RAID_TEMPLATE_MAX_PER_AREA . ' Vorlagen - bitte erst eine alte löschen.';
}
db()->prepare('INSERT INTO raid_templates (area, name, data, created_by) VALUES (?, ?, ?, ?)')
->execute([$area, $name, $json, (int) current_user()['id']]);
return null;
}
/** @return string|null Fehlermeldung oder null */
function raid_template_delete(string $area, int $id): ?string
{
$stmt = db()->prepare('SELECT id, created_by FROM raid_templates WHERE id = ? AND area = ?');
$stmt->execute([$id, $area]);
$row = $stmt->fetch();
if (!$row) {
return 'Diese Vorlage gibt es nicht (mehr).';
}
if (!raid_template_can_edit($row, $area)) {
return 'Löschen darf nur, wer die Vorlage angelegt hat, oder die Raid-Leitung.';
}
db()->prepare('DELETE FROM raid_templates WHERE id = ?')->execute([$id]);
return null;
}