LuminaWebsite/includes/sanctuary.php

432 lines
19 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
/**
* Refugien-Planer (sanctuary.php): Wer hat an welchem Refugium (Sanctuary-Raid) Interesse und kann wann? Jedes
* Mitglied der Legion traegt seine wiederkehrenden Zeitfenster (Wochentag + von-bis) ein und waehlt je Charakter
* die Refugien - auch fuer Twinks. Gearscore und Kampfkraft kommen bei verknuepften Charakteren aus dem Spiel
* (includes/armory.php), sonst von Hand. Die Uebersicht filtert nach Refugium, Tag, Uhrzeit, Rolle/Klasse und
* Mindest-Gearscore; wer Raids anlegen darf, uebernimmt den Filter in "Neuer Raid" (raids.php).
*
* Eintraege verfallen: Wer SANCTUARY_EXPIRE_DAYS Tage nichts bestaetigt oder geaendert hat, steht nicht mehr in
* der Uebersicht (ein Klick auf "Stimmt noch" holt ihn zurueck); nach SANCTUARY_PURGE_DAYS wird geloescht.
* Nur fuer die Legion (dashboard.view + raids.view) - Verbuendete sehen den Planer nicht.
*
* Tabellen: sanctuary_entries (je Charakter: Refugien, Werte von Hand, Notiz, zuletzt bestaetigt) und
* sanctuary_times (je Mitglied: Wochentag, Beginn und Ende in Minuten seit Mitternacht).
*/
// Schluessel => Name im Spiel, Kurzname (Chips, Abzeichen). Gespeichert werden nur die Schluessel.
const SANCTUARY_RAIDS = [
'ludra' => ['label' => 'Abgrundsveredelung: Ludra', 'short' => 'Ludra'],
'korrosion' => ['label' => 'Läuterungsstätte der Korrosion', 'short' => 'Korrosion'],
'muspel' => ['label' => 'Kelch von Muspel', 'short' => 'Muspel'],
];
// Wochentage wie date('N'): 1 = Montag ... 7 = Sonntag
const SANCTUARY_WEEKDAYS = [1 => 'Mo', 2 => 'Di', 3 => 'Mi', 4 => 'Do', 5 => 'Fr', 6 => 'Sa', 7 => 'So'];
const SANCTUARY_WEEKDAY_NAMES = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag'];
// Rolle je Klasse fuer den Rollenfilter
const SANCTUARY_ROLES = ['tank' => 'Tank', 'heal' => 'Heiler', 'support' => 'Support', 'dd' => 'DD'];
const SANCTUARY_CLASS_ROLES = ['Templer' => 'tank', 'Kleriker' => 'heal', 'Kantor' => 'support'];
// Ohne Bestaetigung so viele Tage sichtbar, davor so viele Tage lang der Hinweis; danach wird irgendwann geloescht
const SANCTUARY_EXPIRE_DAYS = 28;
const SANCTUARY_WARN_DAYS = 7;
const SANCTUARY_PURGE_DAYS = 90;
// Zeilen im Formular (eine Zeile = mehrere Tage mit derselben Uhrzeit)
const SANCTUARY_MAX_WINDOWS = 10;
const SANCTUARY_NOTE_MAX = 120;
const SANCTUARY_GEARSCORE_MAX = 99999;
const SANCTUARY_POWER_MAX = 9999999;
/** Darf das angemeldete Konto den Planer nutzen? Nur die Legion, mit Blick auf die Raids. */
function sanctuary_can_use(): bool
{
return is_legion_member() && user_has_permission('raids.view');
}
/** Rolle einer Klasse (tank, heal, support, dd) - unbekannte Klasse: dd. */
function sanctuary_class_role(?string $className): string
{
return SANCTUARY_CLASS_ROLES[(string) $className] ?? 'dd';
}
/** "17:30" -> 1050 (Minuten seit Mitternacht), ungueltig: null. */
function sanctuary_time_parse(string $value): ?int
{
if (!preg_match('/^([01]?\d|2[0-3]):([0-5]\d)$/', trim($value), $m)) {
return null;
}
return (int) $m[1] * 60 + (int) $m[2];
}
/** 1050 -> "17:30" */
function sanctuary_time_text(int $minutes): string
{
return sprintf('%02d:%02d', intdiv($minutes, 60) % 24, $minutes % 60);
}
/** Refugien aus der Spalte raids ("ludra,muspel"): nur gueltige Schluessel, in fester Reihenfolge. */
function sanctuary_raids_parse(?string $value): array
{
$given = explode(',', (string) $value);
return array_values(array_filter(array_keys(SANCTUARY_RAIDS), static fn (string $key): bool => in_array($key, $given, true)));
}
/**
* Zeitfenster eines Mitglieds: [['weekday' => 1-7, 'start' => Minuten, 'end' => Minuten], ...] nach Tag und Beginn.
* Liegt das Ende nicht nach dem Beginn, geht das Fenster ueber Mitternacht.
*/
function sanctuary_windows(int $userId): array
{
return sanctuary_windows_for([$userId])[$userId] ?? [];
}
/**
* @param int[] $userIds
* @return array<int, array<int, array{weekday: int, start: int, end: int}>> je Mitglied
*/
function sanctuary_windows_for(array $userIds): array
{
$userIds = array_values(array_unique(array_filter(array_map('intval', $userIds))));
if (!$userIds) {
return [];
}
try {
$stmt = db()->prepare(
'SELECT user_id, weekday, start_min, end_min FROM sanctuary_times
WHERE user_id IN (' . implode(',', array_fill(0, count($userIds), '?')) . ')
ORDER BY weekday, start_min, end_min'
);
$stmt->execute($userIds);
} catch (PDOException $e) {
return []; // Tabelle entsteht erst beim naechsten Schema-Abgleich
}
$out = [];
foreach ($stmt->fetchAll() as $row) {
$out[(int) $row['user_id']][] = ['weekday' => (int) $row['weekday'], 'start' => (int) $row['start_min'], 'end' => (int) $row['end_min']];
}
return $out;
}
/**
* Zeitfenster mit derselben Uhrzeit zusammenfassen (fuers Formular und die Anzeige):
* [['days' => [1, 2, 3], 'start' => 1080, 'end' => 1320], ...] in der Reihenfolge des ersten Tages.
*/
function sanctuary_windows_grouped(array $windows): array
{
$groups = [];
foreach ($windows as $window) {
$key = $window['start'] . '-' . $window['end'];
$groups[$key] ??= ['days' => [], 'start' => $window['start'], 'end' => $window['end']];
$groups[$key]['days'][] = $window['weekday'];
}
foreach ($groups as &$group) {
$group['days'] = array_values(array_unique($group['days']));
sort($group['days']);
}
unset($group);
usort($groups, static fn (array $a, array $b): int => [$a['days'][0], $a['start']] <=> [$b['days'][0], $b['start']]);
return $groups;
}
/** Tage als Text: [1,2,3,4,5] -> "Mo–Fr", [3,7] -> "Mi, So", [1,2,6] -> "Mo, Di, Sa". */
function sanctuary_days_text(array $days): string
{
$parts = [];
$count = count($days);
for ($i = 0; $i < $count; $i++) {
$from = $days[$i];
$to = $from;
while ($i + 1 < $count && $days[$i + 1] === $to + 1) {
$to = $days[++$i];
}
if ($to - $from >= 2) {
$parts[] = SANCTUARY_WEEKDAYS[$from] . '–' . SANCTUARY_WEEKDAYS[$to];
} else {
for ($day = $from; $day <= $to; $day++) {
$parts[] = SANCTUARY_WEEKDAYS[$day];
}
}
}
return implode(', ', $parts);
}
/** Zeitfenster als Liste von Texten: ["Mo–Fr 18:00–22:00", "So 15:00–20:00"]. */
function sanctuary_windows_text(array $windows): array
{
return array_map(
static fn (array $group): string => sanctuary_days_text($group['days']) . ' ' . sanctuary_time_text($group['start']) . '–' . sanctuary_time_text($group['end']),
sanctuary_windows_grouped($windows)
);
}
/**
* Zeitfenster aus dem Formular: win_days[i][] = Wochentage, win_from[i] / win_to[i] = "HH:MM". Leere Zeilen zaehlen
* nicht, halb ausgefuellte sind ein Fehler.
*
* @return array{0: array<int, array{weekday: int, start: int, end: int}>, 1: string[]} Zeitfenster, Fehler
*/
function sanctuary_windows_from_input(array $input): array
{
$daysInput = is_array($input['win_days'] ?? null) ? $input['win_days'] : [];
$fromInput = is_array($input['win_from'] ?? null) ? $input['win_from'] : [];
$toInput = is_array($input['win_to'] ?? null) ? $input['win_to'] : [];
$indexes = array_slice(array_unique(array_merge(array_keys($daysInput), array_keys($fromInput), array_keys($toInput))), 0, SANCTUARY_MAX_WINDOWS * 3);
$windows = [];
$errors = [];
$rows = 0;
foreach ($indexes as $index) {
$days = array_values(array_intersect(array_keys(SANCTUARY_WEEKDAYS), array_map('intval', is_array($daysInput[$index] ?? null) ? $daysInput[$index] : [])));
$fromRaw = is_string($fromInput[$index] ?? null) ? trim($fromInput[$index]) : '';
$toRaw = is_string($toInput[$index] ?? null) ? trim($toInput[$index]) : '';
if (!$days && $fromRaw === '' && $toRaw === '') {
continue;
}
$from = sanctuary_time_parse($fromRaw);
$to = sanctuary_time_parse($toRaw);
if (!$days || $from === null || $to === null) {
$errors['incomplete'] = 'Ein Zeitfenster braucht mindestens einen Wochentag sowie Beginn und Ende.';
continue;
}
if ($from === $to) {
$errors['same'] = 'Beginn und Ende eines Zeitfensters dürfen nicht gleich sein.';
continue;
}
if (++$rows > SANCTUARY_MAX_WINDOWS) {
$errors['max'] = 'Höchstens ' . SANCTUARY_MAX_WINDOWS . ' Zeitfenster.';
break;
}
foreach ($days as $day) {
$windows[$day . '-' . $from . '-' . $to] = ['weekday' => $day, 'start' => $from, 'end' => $to];
}
}
return [array_values($windows), array_values($errors)];
}
/** Zahl aus einem Feld wie "2.450" oder "98 986": nur die Ziffern; leer = null, zu gross oder Unsinn = false. */
function sanctuary_number_input($value, int $max)
{
$raw = is_string($value) ? trim($value) : '';
if ($raw === '') {
return null;
}
$digits = preg_replace('/[.\s\x{00A0}\']/u', '', $raw);
if (!preg_match('/^\d{1,9}$/', (string) $digits) || (int) $digits > $max) {
return false;
}
return (int) $digits === 0 ? null : (int) $digits;
}
/**
* Eigene Eintraege je Charakter: [Charakter-ID => ['raids' => [...], 'gearscore' => ?int, 'combat_power' => ?int,
* 'note' => string, 'confirmed_at' => string]].
*/
function sanctuary_entries_for_user(int $userId): array
{
try {
$stmt = db()->prepare('SELECT character_id, raids, gearscore, combat_power, note, confirmed_at FROM sanctuary_entries WHERE user_id = ?');
$stmt->execute([$userId]);
} catch (PDOException $e) {
return [];
}
$out = [];
foreach ($stmt->fetchAll() as $row) {
$out[(int) $row['character_id']] = [
'raids' => sanctuary_raids_parse($row['raids']),
'gearscore' => $row['gearscore'] !== null ? (int) $row['gearscore'] : null,
'combat_power' => $row['combat_power'] !== null ? (int) $row['combat_power'] : null,
'note' => (string) $row['note'],
'confirmed_at' => (string) $row['confirmed_at'],
];
}
return $out;
}
/**
* Stand des eigenen Eintrags: 'none' (nichts eingetragen), 'active', 'expiring' (laeuft in days_left Tagen ab)
* oder 'expired' (steht nicht mehr in der Uebersicht).
*
* @return array{state: string, days_left: int, confirmed_at: ?string}
*/
function sanctuary_state(int $userId): array
{
try {
$stmt = db()->prepare('SELECT MAX(confirmed_at) FROM sanctuary_entries WHERE user_id = ?');
$stmt->execute([$userId]);
$confirmedAt = $stmt->fetchColumn();
} catch (PDOException $e) {
$confirmedAt = null;
}
if (!$confirmedAt) {
return ['state' => 'none', 'days_left' => 0, 'confirmed_at' => null];
}
$expires = (int) strtotime((string) $confirmedAt) + SANCTUARY_EXPIRE_DAYS * 86400;
$daysLeft = (int) ceil(($expires - time()) / 86400);
$state = $expires <= time() ? 'expired' : ($daysLeft <= SANCTUARY_WARN_DAYS ? 'expiring' : 'active');
return ['state' => $state, 'days_left' => max(0, $daysLeft), 'confirmed_at' => (string) $confirmedAt];
}
/** Hinweis am Menuepunkt: der eigene Eintrag laeuft bald ab oder ist abgelaufen - sonst null. */
function sanctuary_nav_badge(int $userId): ?array
{
$state = sanctuary_state($userId);
if ($state['state'] === 'expiring') {
return ['text' => '!', 'class' => 'sidebar-badge', 'title' => 'Dein Eintrag im Refugien-Planer läuft '
. ($state['days_left'] <= 1 ? 'morgen' : 'in ' . $state['days_left'] . ' Tagen') . ' ab – bitte bestätigen'];
}
if ($state['state'] === 'expired') {
return ['text' => '!', 'class' => 'sidebar-badge', 'title' => 'Dein Eintrag im Refugien-Planer ist abgelaufen – bestätige ihn, um wieder gelistet zu werden'];
}
return null;
}
/**
* Eintrag speichern: ersetzt die Zeitfenster und die Eintraege je Charakter (nur eigene Charaktere, die die
* Aufrufer geprueft haben) und gilt als frisch bestaetigt.
*
* @param array<int, array{weekday: int, start: int, end: int}> $windows
* @param array<int, array{raids: string[], gearscore: ?int, combat_power: ?int, note: string}> $entries je Charakter-ID
*/
function sanctuary_save(int $userId, array $windows, array $entries): void
{
$pdo = db();
$pdo->beginTransaction();
try {
$pdo->prepare('DELETE FROM sanctuary_times WHERE user_id = ?')->execute([$userId]);
$insertTime = $pdo->prepare('INSERT INTO sanctuary_times (user_id, weekday, start_min, end_min) VALUES (?, ?, ?, ?)');
foreach ($windows as $window) {
$insertTime->execute([$userId, $window['weekday'], $window['start'], $window['end']]);
}
$pdo->prepare('DELETE FROM sanctuary_entries WHERE user_id = ?')->execute([$userId]);
$insertEntry = $pdo->prepare(
'INSERT INTO sanctuary_entries (character_id, user_id, raids, gearscore, combat_power, note, confirmed_at) VALUES (?, ?, ?, ?, ?, ?, NOW())'
);
foreach ($entries as $characterId => $entry) {
$insertEntry->execute([
(int) $characterId, $userId, implode(',', $entry['raids']), $entry['gearscore'], $entry['combat_power'],
$entry['note'] !== '' ? $entry['note'] : null,
]);
}
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
}
/** "Stimmt noch": alle eigenen Eintraege gelten wieder als frisch. Gibt zurueck, ob es welche gab. */
function sanctuary_confirm(int $userId): bool
{
$stmt = db()->prepare('UPDATE sanctuary_entries SET confirmed_at = NOW() WHERE user_id = ?');
$stmt->execute([$userId]);
return $stmt->rowCount() > 0;
}
/** Eigenen Eintrag samt Zeitfenstern entfernen. */
function sanctuary_remove(int $userId): void
{
db()->prepare('DELETE FROM sanctuary_entries WHERE user_id = ?')->execute([$userId]);
db()->prepare('DELETE FROM sanctuary_times WHERE user_id = ?')->execute([$userId]);
}
/** Lange abgelaufene Eintraege loeschen, dazu Zeitfenster ohne Eintrag (laeuft beim Oeffnen des Planers). */
function sanctuary_purge(): void
{
try {
$pdo = db();
$pdo->prepare('DELETE FROM sanctuary_entries WHERE confirmed_at < ?')
->execute([date('Y-m-d H:i:s', time() - SANCTUARY_PURGE_DAYS * 86400)]);
$pdo->exec('DELETE t FROM sanctuary_times t LEFT JOIN sanctuary_entries e ON e.user_id = t.user_id WHERE e.user_id IS NULL');
} catch (PDOException $e) {
// Dann beim naechsten Mal
}
}
/**
* Gearscore und Kampfkraft eines Eintrags: aus dem Spiel, wenn der Charakter verknuepft ist und Daten da sind,
* sonst die von Hand eingetragenen. $row braucht live_gearscore/live_power (aus aion_data), gearscore, combat_power.
*
* @return array{gearscore: ?int, combat_power: ?int, live: bool}
*/
function sanctuary_stats(array $row): array
{
$liveScore = (int) ($row['live_gearscore'] ?? 0);
$livePower = (int) ($row['live_power'] ?? 0);
$live = !empty($row['aion_char_id']) && ($liveScore > 0 || $livePower > 0);
$manualScore = isset($row['gearscore']) ? (int) $row['gearscore'] : 0;
$manualPower = isset($row['combat_power']) ? (int) $row['combat_power'] : 0;
$score = $liveScore > 0 ? $liveScore : $manualScore;
$power = $livePower > 0 ? $livePower : $manualPower;
return ['gearscore' => $score > 0 ? $score : null, 'combat_power' => $power > 0 ? $power : null, 'live' => $live];
}
/** SQL-Ausdruecke fuer Gearscore und Kampfkraft aus den gespeicherten Spieldaten (member_characters als $alias). */
function sanctuary_live_columns(string $alias = 'c'): string
{
return "JSON_VALUE($alias.aion_data, '$.item_level') AS live_gearscore, JSON_VALUE($alias.aion_data, '$.combat_power') AS live_power";
}
/**
* Alle gueltigen (nicht abgelaufenen) Eintraege der Legion mit Charakter, Mitglied, Werten und Zeitfenstern -
* die Zeilen der Uebersicht. Sortiert nach Gearscore (hoch zuerst), ohne Angabe zuletzt.
*
* @return array<int, array<string, mixed>>
*/
function sanctuary_overview(): array
{
try {
$stmt = db()->prepare(
'SELECT e.character_id, e.user_id, e.raids, e.gearscore, e.combat_power, e.note, e.confirmed_at,
c.name AS character_name, c.class_name, c.is_main, c.aion_char_id, c.aion_fetched_at, ' . sanctuary_live_columns('c') . ",
u.username, u.display_name, u.avatar_filename
FROM sanctuary_entries e
JOIN member_characters c ON c.id = e.character_id
JOIN users u ON u.id = e.user_id
WHERE u.status = 'active' AND e.confirmed_at >= ? AND " . sql_is_legion_member('u')
);
$stmt->execute([date('Y-m-d H:i:s', time() - SANCTUARY_EXPIRE_DAYS * 86400)]);
$rows = $stmt->fetchAll();
} catch (PDOException $e) {
return [];
}
$windows = sanctuary_windows_for(array_column($rows, 'user_id'));
$out = [];
foreach ($rows as $row) {
$raids = sanctuary_raids_parse($row['raids']);
$userWindows = $windows[(int) $row['user_id']] ?? [];
if (!$raids || !$userWindows) {
continue;
}
$stats = sanctuary_stats($row);
$out[] = [
'character_id' => (int) $row['character_id'],
'user_id' => (int) $row['user_id'],
'member' => $row['display_name'] !== '' ? (string) $row['display_name'] : (string) $row['username'],
'user' => ['id' => (int) $row['user_id'], 'username' => $row['username'], 'display_name' => $row['display_name'], 'avatar_filename' => $row['avatar_filename']],
'character' => (string) $row['character_name'],
'class' => (string) $row['class_name'],
'role' => sanctuary_class_role($row['class_name']),
'is_main' => (int) $row['is_main'] === 1,
'raids' => $raids,
'note' => (string) $row['note'],
'gearscore' => $stats['gearscore'],
'combat_power' => $stats['combat_power'],
'live' => $stats['live'],
'stats_at' => $stats['live'] ? (string) $row['aion_fetched_at'] : (string) $row['confirmed_at'],
'confirmed_at' => (string) $row['confirmed_at'],
'windows' => $userWindows,
];
}
usort($out, static fn (array $a, array $b): int => [$b['gearscore'] ?? -1, $b['combat_power'] ?? -1, mb_strtolower($a['member'])]
<=> [$a['gearscore'] ?? -1, $a['combat_power'] ?? -1, mb_strtolower($b['member'])]);
return $out;
}
/** Kampfkraft kurz ("98,9k"), wie auf den Charakterkarten (armory_power_label). */
function sanctuary_power_label(int $power): string
{
return $power < 1000 ? (string) $power : number_format(floor($power / 100) / 10, 1, ',', '.') . 'k';
}