LuminaWebsite/includes/schema.php
Maaxxs 5f25e20900 Kina in the warehouse, Lumipunkte, new logo, versioned assets
Warehouse: Kina (the game currency) can be paid in and out, shown in its own
box with the in-game coin icon (Icon_Currency_Coin_GoldNonbinding from the
game client via aion2.app, since the wiki has none). It is a catalog item in
the new "Währung" category, kept out of the item cards and totals, and
allows up to a trillion per entry; warehouse_movements.quantity becomes
BIGINT for that. A leftover "Kinah" entry is merged into "Kina".

Beitragspunkte are renamed to Lumipunkte in every visible text, the coin is
now lumipunkt.svg, and the schema sync also updates the descriptions of
existing core permissions so the new name reaches the role editor.

The sidebar, login page and mobile top bar show the new Lumina Ascendens
logo, cropped and with its dark background made transparent.

Scripts and the stylesheet are included with a ?v=<mtime> query
(asset_url()), so browsers pick up new versions after an upload instead of
running stale JavaScript - the cause of raid points not being saved.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 10:25:28 +02:00

266 lines
12 KiB
PHP

<?php
declare(strict_types=1);
/**
* Bringt eine bestehende Datenbank auf den Stand, den der Code erwartet. Frueher standen
* dafuer ALTER-Befehle in der README, die von Hand in phpMyAdmin auszufuehren waren - fuer
* den Discord-Login geht das nicht mehr, weil schon die Login-Seite die neuen Spalten
* braucht (ohne sie koennte sich niemand mehr anmelden, auch kein Administrator).
*
* Geprueft wird einmal pro Sitzung; ist alles da, kostet das eine einzige Abfrage.
*/
// Hochzaehlen, sobald unten eine Aenderung dazukommt - dann pruefen alle Sitzungen neu.
const SCHEMA_VERSION = 8;
/**
* Tabellen, die nachtraeglich dazugekommen sind: Tabelle => CREATE-Befehl (wie in sql/schema.sql).
*/
function schema_table_upgrades(): array
{
return [
'warehouse_items' => <<<'SQL'
CREATE TABLE IF NOT EXISTS warehouse_items (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(150) NOT NULL,
-- Schluessel aus WAREHOUSE_CATEGORIES in includes/warehouse.php (sword, boots, ...)
category VARCHAR(30) NOT NULL,
-- Dateiname des Bildes unter assets/images/warehouse/ (NULL = Platzhalter)
icon VARCHAR(120) NULL,
-- wiki = aus includes/data/warehouse_items.json, custom = in der Oberflaeche angelegt
source ENUM('wiki', 'custom') NOT NULL DEFAULT 'wiki',
created_by INT UNSIGNED NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uq_warehouse_items_name (name),
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'warehouse_movements' => <<<'SQL'
CREATE TABLE IF NOT EXISTS warehouse_movements (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
item_id INT UNSIGNED NOT NULL,
-- in = eingelagert, out = entnommen
direction ENUM('in', 'out') NOT NULL,
-- BIGINT wegen Kina (Betraege weit ueber 4 Milliarden moeglich)
quantity BIGINT UNSIGNED NOT NULL,
-- Wann uebergeben/entnommen (wie eingegeben, deutsche Zeit)
occurred_at DATETIME NOT NULL,
-- Von wem (in) bzw. an wen (out): ein Konto der Website oder ein frei eingetragener Name
counterpart_user_id INT UNSIGNED NULL,
counterpart_name VARCHAR(100) NULL,
note VARCHAR(255) NULL,
created_by INT UNSIGNED NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (item_id) REFERENCES warehouse_items(id) ON DELETE RESTRICT,
FOREIGN KEY (counterpart_user_id) REFERENCES users(id) ON DELETE SET NULL,
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
INDEX idx_warehouse_movements_item (item_id),
INDEX idx_warehouse_movements_time (occurred_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'contribution_awards' => <<<'SQL'
CREATE TABLE IF NOT EXISTS contribution_awards (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
-- raid, event, other (CONTRIBUTION_CATEGORIES in includes/contributions.php)
category VARCHAR(20) NOT NULL,
title VARCHAR(150) NOT NULL,
note VARCHAR(255) NULL,
-- Raid aus der Raid-API, wenn die Punkte fuer einen Raid vergeben wurden
raid_id BIGINT UNSIGNED NULL,
awarded_at DATETIME NOT NULL,
created_by INT UNSIGNED NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
INDEX idx_contribution_awards_time (awarded_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'contribution_entries' => <<<'SQL'
CREATE TABLE IF NOT EXISTS contribution_entries (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
award_id INT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
-- Negativ = Abzug
points INT NOT NULL,
UNIQUE KEY uq_contribution_entry (award_id, user_id),
FOREIGN KEY (award_id) REFERENCES contribution_awards(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
INDEX idx_contribution_entries_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'raid_settings' => <<<'SQL'
CREATE TABLE IF NOT EXISTS raid_settings (
-- Discord-Nachrichten-ID des Raids (wie in der Raid-API), 19-stellig
raid_id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
-- Automatische Lumipunkte beim Archivieren: fuer Anwesende bzw. Abzug fuer Abwesende
points_present INT NOT NULL DEFAULT 0,
points_absent INT NOT NULL DEFAULT 0,
-- Wann die Automatik gelaufen ist (oder uebersprungen wurde, weil schon Punkte vergeben waren)
auto_processed_at DATETIME NULL,
auto_result VARCHAR(255) NULL,
-- Anwesenheitsliste als kontrolliert bestaetigt
attendance_checked_at DATETIME NULL,
attendance_checked_by INT UNSIGNED NULL,
FOREIGN KEY (attendance_checked_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'raid_attendance' => <<<'SQL'
CREATE TABLE IF NOT EXISTS raid_attendance (
raid_id BIGINT UNSIGNED NOT NULL,
-- Discord-ID wie in den Raid-Anmeldungen; zugeordnet zu Website-Konten ueber users.discord_id
discord_id BIGINT UNSIGNED NOT NULL,
name VARCHAR(100) NOT NULL DEFAULT '',
status ENUM('present', 'absent', 'excused') NOT NULL,
updated_by INT UNSIGNED NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (raid_id, discord_id),
FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'settings' => <<<'SQL'
CREATE TABLE IF NOT EXISTS settings (
`key` VARCHAR(100) NOT NULL PRIMARY KEY,
value TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
];
}
/**
* Spalten, die nachtraeglich dazugekommen sind: Tabelle => [Spalte => ALTER-Befehl].
* Die Befehle muessen zu sql/schema.sql passen (dort stehen sie fuer Neuinstallationen).
*/
function schema_column_upgrades(): array
{
return [
'users' => [
'password_login' => "ALTER TABLE users ADD COLUMN password_login TINYINT(1) NOT NULL DEFAULT 1 AFTER must_change_password",
'discord_access_token' => "ALTER TABLE users ADD COLUMN discord_access_token VARCHAR(255) NULL AFTER discord_username",
'discord_refresh_token' => "ALTER TABLE users ADD COLUMN discord_refresh_token VARCHAR(255) NULL AFTER discord_access_token",
'discord_token_expires' => "ALTER TABLE users ADD COLUMN discord_token_expires DATETIME NULL AFTER discord_refresh_token",
'discord_synced_at' => "ALTER TABLE users ADD COLUMN discord_synced_at DATETIME NULL AFTER discord_token_expires",
],
'roles' => [
'discord_role_id' => "ALTER TABLE roles ADD COLUMN discord_role_id BIGINT UNSIGNED NULL AFTER roster_order",
],
];
}
function ensure_schema(): void
{
if (($_SESSION['schema_version'] ?? 0) === SCHEMA_VERSION) {
return;
}
$pdo = db();
$upgrades = schema_column_upgrades();
$stmt = $pdo->query(
"SELECT LOWER(table_name) AS t, LOWER(column_name) AS c FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name IN ('users', 'roles')"
);
$existing = [];
foreach ($stmt->fetchAll() as $row) {
$existing[$row['t']][$row['c']] = true;
}
// Noch gar keine Tabellen: frische Installation, schema.sql ist noch nicht importiert.
if (empty($existing['users'])) {
return;
}
$statements = [];
$tables = $pdo->query(
"SELECT LOWER(table_name) FROM information_schema.tables WHERE table_schema = DATABASE()"
)->fetchAll(PDO::FETCH_COLUMN);
foreach (schema_table_upgrades() as $table => $sql) {
if (!in_array($table, $tables, true)) {
$statements[] = $sql;
}
}
foreach ($upgrades as $table => $columns) {
foreach ($columns as $column => $sql) {
if (empty($existing[$table][$column])) {
$statements[] = $sql;
}
}
}
// Der Status "pending" (Freischaltung ausstehend) kam mit dem Discord-Login dazu.
$enum = $pdo->query(
"SELECT column_type FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'users' AND column_name = 'status'"
)->fetchColumn();
if (is_string($enum) && strpos($enum, "'pending'") === false) {
$statements[] = "ALTER TABLE users MODIFY status ENUM('active', 'disabled', 'pending') NOT NULL DEFAULT 'active'";
}
// Spalten, deren Typ nachtraeglich korrigiert wurde: [Tabelle, Spalte, erwarteter Typ-Anfang, Befehl].
// raid_id sind Discord-Nachrichten-IDs (19-stellig) - ein INT war dafuer zu klein.
$typeFixes = [
['contribution_awards', 'raid_id', 'bigint', 'ALTER TABLE contribution_awards MODIFY raid_id BIGINT UNSIGNED NULL'],
['warehouse_movements', 'quantity', 'bigint', 'ALTER TABLE warehouse_movements MODIFY quantity BIGINT UNSIGNED NOT NULL'],
];
foreach ($typeFixes as [$table, $column, $expected, $sql]) {
if (!in_array($table, $tables, true)) {
continue; // Tabelle wird oben frisch (schon richtig) angelegt
}
$typeStmt = $pdo->prepare(
'SELECT LOWER(column_type) FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?'
);
$typeStmt->execute([$table, $column]);
$type = (string) $typeStmt->fetchColumn();
if ($type !== '' && strpos($type, $expected) !== 0) {
$statements[] = $sql;
}
}
try {
foreach ($statements as $sql) {
$pdo->exec($sql);
}
} catch (Throwable $e) {
http_response_code(500);
header('Content-Type: text/plain; charset=UTF-8');
echo "Die Datenbank konnte nicht automatisch aktualisiert werden:\n" . $e->getMessage()
. "\n\nBitte diese Befehle einmal in phpMyAdmin ausfuehren und die Seite neu laden:\n\n"
. implode(";\n", $statements) . ";\n";
exit;
}
schema_sync_core_permissions();
$_SESSION['schema_version'] = SCHEMA_VERSION;
}
/**
* Traegt neu hinzugekommene Kern-Berechtigungen (CORE_PERMISSIONS) in die Datenbank ein und
* aktualisiert die Beschreibungen der vorhandenen -
* bisher musste man sie nach einem Update von Hand anlegen. Neue Rechte bekommt die
* Administrator-Gruppe gleich mit, weil sie laut Installation alle Rechte hat.
*/
function schema_sync_core_permissions(): void
{
$pdo = db();
$existing = $pdo->query('SELECT `key`, description FROM permissions')->fetchAll(PDO::FETCH_KEY_PAIR);
$adminRoleId = (int) $pdo->query("SELECT id FROM roles WHERE name = 'Administrator'")->fetchColumn();
foreach (CORE_PERMISSIONS as $permission) {
if (array_key_exists($permission['key'], $existing)) {
// Beschreibung nachziehen, falls sie im Code geaendert wurde (z.B. Umbenennungen).
if ($existing[$permission['key']] !== $permission['description']) {
$pdo->prepare('UPDATE permissions SET description = ? WHERE `key` = ?')
->execute([$permission['description'], $permission['key']]);
}
continue;
}
$pdo->prepare('INSERT INTO permissions (`key`, description) VALUES (?, ?)')
->execute([$permission['key'], $permission['description']]);
if ($adminRoleId > 0) {
$pdo->prepare('INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?, ?)')
->execute([$adminRoleId, (int) $pdo->lastInsertId()]);
}
}
}