LuminaWebsite/includes/schema.php
Maaxxs 3e025b811e Lagerhaus: stock and history of the legion's items
A new page records items handed in (item, quantity, when, and from whom -
a website account or a free-text name) and taken out (when, now or entered
by hand, and optionally to whom). Stock is always computed from the
movements, withdrawals can't exceed it, and a deposit can only be deleted
once nothing of it has been taken out. Stock is shown as cards with the item
picture and quantity, name and category below, plus search and a category
filter; the history lists every movement with who entered it.

The item list holds 2,301 weapons, armor pieces, accessories and consumables
read from the Aion 2 wiki's MediaWiki API, with each item's icon downscaled
to 128px under assets/images/warehouse/. It is loaded into the database on
first visit and again whenever the JSON changes. Unknown names can be added
as custom items after a confirmation, since the wiki lists no materials.

warehouse.view and warehouse.manage are new permissions. Missing core
permissions are now created automatically and granted to the Administrator
group, and the two tables are created like the other schema additions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 08:46:40 +02:00

180 lines
7.2 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 = 3;
/**
* 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,
quantity INT 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,
'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'";
}
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 -
* 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` FROM permissions')->fetchAll(PDO::FETCH_COLUMN);
$adminRoleId = (int) $pdo->query("SELECT id FROM roles WHERE name = 'Administrator'")->fetchColumn();
foreach (CORE_PERMISSIONS as $permission) {
if (in_array($permission['key'], $existing, true)) {
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()]);
}
}
}