Charakterverwalter (westreiche_website) ergänzen, Website-Nav "Charaktere"
This commit is contained in:
parent
d107f90c93
commit
01dae01c7c
84 changed files with 8915 additions and 17 deletions
7
westreiche_website/app/.htaccess
Normal file
7
westreiche_website/app/.htaccess
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<IfModule mod_authz_core.c>
|
||||
Require all denied
|
||||
</IfModule>
|
||||
<IfModule !mod_authz_core.c>
|
||||
Order allow,deny
|
||||
Deny from all
|
||||
</IfModule>
|
||||
337
westreiche_website/app/auth.php
Normal file
337
westreiche_website/app/auth.php
Normal file
|
|
@ -0,0 +1,337 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Westreiche – Anmeldung, Sessions, "Angemeldet bleiben", Ratenbegrenzung.
|
||||
*
|
||||
* Angemeldet wird mit Benutzername **oder** E-Mail-Adresse und Passwort.
|
||||
* Konten entstehen ausschließlich durch den Admin (direkt oder per Einladung);
|
||||
* eine Selbstregistrierung gibt es nicht.
|
||||
*/
|
||||
|
||||
const WS_DUMMY_HASH = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.';
|
||||
const WS_REMEMBER_COOKIE = 'WESTREICHE_REMEMBER';
|
||||
|
||||
function hash_password(string $password): string
|
||||
{
|
||||
if (defined('PASSWORD_ARGON2ID')) {
|
||||
return password_hash($password, PASSWORD_ARGON2ID, [
|
||||
'memory_cost' => 32768,
|
||||
'time_cost' => 3,
|
||||
'threads' => 1,
|
||||
]);
|
||||
}
|
||||
return password_hash($password, PASSWORD_DEFAULT);
|
||||
}
|
||||
|
||||
function password_needs_upgrade(string $hash): bool
|
||||
{
|
||||
if (defined('PASSWORD_ARGON2ID')) {
|
||||
return password_needs_rehash($hash, PASSWORD_ARGON2ID, [
|
||||
'memory_cost' => 32768,
|
||||
'time_cost' => 3,
|
||||
'threads' => 1,
|
||||
]);
|
||||
}
|
||||
return password_needs_rehash($hash, PASSWORD_DEFAULT);
|
||||
}
|
||||
|
||||
function auth_user(): ?array
|
||||
{
|
||||
static $loaded = false;
|
||||
static $user = null;
|
||||
if ($loaded) {
|
||||
return $user;
|
||||
}
|
||||
$loaded = true;
|
||||
|
||||
$uid = $_SESSION['uid'] ?? null;
|
||||
if (!is_int($uid) && !ctype_digit((string) $uid)) {
|
||||
auth_restore_from_remember();
|
||||
$uid = $_SESSION['uid'] ?? null;
|
||||
if (!is_int($uid) && !ctype_digit((string) $uid)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([(int) $uid]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row || $row['status'] !== 'active') {
|
||||
auth_clear_session();
|
||||
return null;
|
||||
}
|
||||
if ((int) ($_SESSION['epoch'] ?? 0) !== (int) $row['auth_epoch']) {
|
||||
auth_clear_session();
|
||||
return null;
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$idleLimit = (int) config('app.session_idle_seconds', 2592000);
|
||||
$absoluteLimit = (int) config('app.session_absolute_seconds', 7776000);
|
||||
$created = (int) ($_SESSION['created'] ?? 0);
|
||||
$lastSeen = (int) ($_SESSION['last_seen'] ?? 0);
|
||||
if ($created === 0 || $lastSeen === 0
|
||||
|| $now - $lastSeen > $idleLimit
|
||||
|| $now - $created > $absoluteLimit
|
||||
) {
|
||||
auth_clear_session();
|
||||
return null;
|
||||
}
|
||||
if ($now - $lastSeen > 300) {
|
||||
$_SESSION['last_seen'] = $now;
|
||||
}
|
||||
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['auth_epoch'] = (int) $row['auth_epoch'];
|
||||
$row['must_change_password'] = (int) $row['must_change_password'];
|
||||
$user = $row;
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_user_by_id(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['auth_epoch'] = (int) $row['auth_epoch'];
|
||||
$row['must_change_password'] = (int) $row['must_change_password'];
|
||||
return $row;
|
||||
}
|
||||
|
||||
function auth_login(array $user, bool $remember = false): void
|
||||
{
|
||||
session_regenerate_id(true);
|
||||
$_SESSION['uid'] = (int) $user['id'];
|
||||
$_SESSION['epoch'] = (int) $user['auth_epoch'];
|
||||
$_SESSION['created'] = time();
|
||||
$_SESSION['last_seen'] = time();
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
|
||||
db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?')
|
||||
->execute([utc_now(), (int) $user['id']]);
|
||||
db()->prepare('DELETE FROM login_attempts WHERE login_key = ?')
|
||||
->execute([auth_login_key((string) $user['username'])]);
|
||||
|
||||
if ($remember) {
|
||||
auth_issue_remember((int) $user['id']);
|
||||
}
|
||||
}
|
||||
|
||||
function auth_clear_session(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
session_regenerate_id(true);
|
||||
}
|
||||
}
|
||||
|
||||
function auth_logout(): void
|
||||
{
|
||||
auth_forget_remember();
|
||||
auth_clear_session();
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
session_destroy();
|
||||
}
|
||||
}
|
||||
|
||||
function auth_require_login(): array
|
||||
{
|
||||
$user = auth_user();
|
||||
if ($user === null) {
|
||||
$target = current_path();
|
||||
$query = (string) ($_SERVER['QUERY_STRING'] ?? '');
|
||||
if ($query !== '') {
|
||||
$target .= '?' . $query;
|
||||
}
|
||||
redirect('/login?next=' . rawurlencode($target));
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_require_admin(): array
|
||||
{
|
||||
$user = auth_require_login();
|
||||
if (($user['role'] ?? '') !== 'admin') {
|
||||
abort_page(403, 'Diese Seite ist nur für den Spielleiter bestimmt.');
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_login_key(string $identifier): string
|
||||
{
|
||||
return mb_strtolower(trim($identifier), 'UTF-8');
|
||||
}
|
||||
|
||||
function auth_find_by_login(string $identifier): ?array
|
||||
{
|
||||
$needle = trim($identifier);
|
||||
if ($needle === '') {
|
||||
return null;
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'SELECT * FROM users WHERE username = ? OR (email IS NOT NULL AND email <> \'\' AND email = ?) LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$needle, $needle]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
function auth_username_taken(string $username, int $ignoreId = 0): bool
|
||||
{
|
||||
$stmt = db()->prepare('SELECT id FROM users WHERE username = ? AND id <> ? LIMIT 1');
|
||||
$stmt->execute([$username, $ignoreId]);
|
||||
return (bool) $stmt->fetchColumn();
|
||||
}
|
||||
|
||||
function auth_email_taken(string $email, int $ignoreId = 0): bool
|
||||
{
|
||||
if ($email === '') {
|
||||
return false;
|
||||
}
|
||||
$stmt = db()->prepare('SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1');
|
||||
$stmt->execute([$email, $ignoreId]);
|
||||
return (bool) $stmt->fetchColumn();
|
||||
}
|
||||
|
||||
function auth_is_locked_out(string $identifier): bool
|
||||
{
|
||||
$window = (int) config('app.login_window_seconds', 900);
|
||||
$maxIp = (int) config('app.login_max_per_ip', 15);
|
||||
$maxUser = (int) config('app.login_max_per_user', 5);
|
||||
|
||||
$stmt = db()->prepare('SELECT COUNT(*) FROM login_attempts WHERE ip = ? AND attempted_at >= ?');
|
||||
$stmt->execute([client_ip(), utc_after(-$window)]);
|
||||
if ((int) $stmt->fetchColumn() >= $maxIp) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('SELECT COUNT(*) FROM login_attempts WHERE login_key = ? AND attempted_at >= ?');
|
||||
$stmt->execute([auth_login_key($identifier), utc_after(-$window)]);
|
||||
return (int) $stmt->fetchColumn() >= $maxUser;
|
||||
}
|
||||
|
||||
function auth_record_failure(string $identifier): void
|
||||
{
|
||||
db()->prepare('INSERT INTO login_attempts (ip, login_key, attempted_at) VALUES (?, ?, ?)')
|
||||
->execute([client_ip(), auth_login_key($identifier), utc_now()]);
|
||||
|
||||
$window = (int) config('app.login_window_seconds', 900);
|
||||
db()->prepare('DELETE FROM login_attempts WHERE attempted_at < ?')
|
||||
->execute([utc_after(-max($window * 8, 86400))]);
|
||||
}
|
||||
|
||||
function auth_verify_login(string $identifier, string $password): array
|
||||
{
|
||||
if (auth_is_locked_out($identifier)) {
|
||||
throw new RuntimeException('locked');
|
||||
}
|
||||
|
||||
$user = auth_find_by_login($identifier);
|
||||
$hash = $user['password_hash'] ?? WS_DUMMY_HASH;
|
||||
$ok = password_verify($password, $hash);
|
||||
if (!$user || !$ok) {
|
||||
auth_record_failure($identifier);
|
||||
throw new RuntimeException('invalid');
|
||||
}
|
||||
if ($user['status'] !== 'active') {
|
||||
auth_record_failure($identifier);
|
||||
throw new RuntimeException('disabled');
|
||||
}
|
||||
if (password_needs_upgrade($hash)) {
|
||||
db()->prepare('UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?')
|
||||
->execute([hash_password($password), utc_now(), (int) $user['id']]);
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_invalidate_sessions(int $userId): void
|
||||
{
|
||||
db()->prepare('UPDATE users SET auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?')
|
||||
->execute([utc_now(), $userId]);
|
||||
db()->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
|
||||
}
|
||||
|
||||
function auth_can_manage(?array $user): bool
|
||||
{
|
||||
return is_array($user) && ($user['role'] ?? '') === 'admin';
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ Angemeldet bleiben */
|
||||
|
||||
function auth_issue_remember(int $userId): void
|
||||
{
|
||||
$selector = bin2hex(random_bytes(12));
|
||||
$validator = bin2hex(random_bytes(32));
|
||||
$lifetime = (int) config('app.remember_seconds', 7776000);
|
||||
|
||||
db()->prepare('DELETE FROM auth_tokens WHERE expires_at < ?')->execute([utc_now()]);
|
||||
db()->prepare('INSERT INTO auth_tokens (user_id, selector, validator_hash, created_at, expires_at) VALUES (?, ?, ?, ?, ?)')
|
||||
->execute([$userId, $selector, hash('sha256', $validator), utc_now(), utc_after($lifetime)]);
|
||||
|
||||
setcookie(WS_REMEMBER_COOKIE, $selector . '.' . $validator, [
|
||||
'expires' => time() + $lifetime,
|
||||
'path' => '/',
|
||||
'secure' => is_https(),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
}
|
||||
|
||||
function auth_forget_remember(): void
|
||||
{
|
||||
$raw = $_COOKIE[WS_REMEMBER_COOKIE] ?? '';
|
||||
if (is_string($raw) && str_contains($raw, '.')) {
|
||||
[$selector] = explode('.', $raw, 2);
|
||||
if ($selector !== '') {
|
||||
db()->prepare('DELETE FROM auth_tokens WHERE selector = ?')->execute([$selector]);
|
||||
}
|
||||
}
|
||||
if (isset($_COOKIE[WS_REMEMBER_COOKIE])) {
|
||||
setcookie(WS_REMEMBER_COOKIE, '', [
|
||||
'expires' => time() - 3600,
|
||||
'path' => '/',
|
||||
'secure' => is_https(),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
unset($_COOKIE[WS_REMEMBER_COOKIE]);
|
||||
}
|
||||
}
|
||||
|
||||
function auth_restore_from_remember(): void
|
||||
{
|
||||
$raw = $_COOKIE[WS_REMEMBER_COOKIE] ?? '';
|
||||
if (!is_string($raw) || preg_match('/^([a-f0-9]{24})\.([a-f0-9]{64})$/', $raw, $m) !== 1) {
|
||||
return;
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'SELECT t.*, u.auth_epoch, u.status
|
||||
FROM auth_tokens t JOIN users u ON u.id = t.user_id
|
||||
WHERE t.selector = ? AND t.expires_at >= ? LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$m[1], utc_now()]);
|
||||
$token = $stmt->fetch();
|
||||
if (!$token || !hash_equals((string) $token['validator_hash'], hash('sha256', $m[2]))) {
|
||||
auth_forget_remember();
|
||||
return;
|
||||
}
|
||||
if ($token['status'] !== 'active') {
|
||||
auth_forget_remember();
|
||||
return;
|
||||
}
|
||||
|
||||
// Token rotieren, damit ein gestohlenes Cookie nur einmal nutzbar ist.
|
||||
db()->prepare('DELETE FROM auth_tokens WHERE id = ?')->execute([(int) $token['id']]);
|
||||
session_regenerate_id(true);
|
||||
$_SESSION['uid'] = (int) $token['user_id'];
|
||||
$_SESSION['epoch'] = (int) $token['auth_epoch'];
|
||||
$_SESSION['created'] = time();
|
||||
$_SESSION['last_seen'] = time();
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
auth_issue_remember((int) $token['user_id']);
|
||||
}
|
||||
62
westreiche_website/app/bootstrap.php
Normal file
62
westreiche_website/app/bootstrap.php
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Westreiche – Bootstrap.
|
||||
*
|
||||
* Lädt Konfiguration, Datenbank, Session und Helfer. Zugangsdaten liegen in
|
||||
* app/config.local.php (gitignored, wird beim Deployment erzeugt).
|
||||
*/
|
||||
|
||||
define('WS_ROOT', dirname(__DIR__));
|
||||
define('WS_APP', __DIR__);
|
||||
|
||||
$configFile = WS_APP . '/config.local.php';
|
||||
if (!is_file($configFile)) {
|
||||
http_response_code(500);
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo "Die Anwendung ist noch nicht konfiguriert (app/config.local.php fehlt).\n";
|
||||
exit;
|
||||
}
|
||||
|
||||
$GLOBALS['ws_config'] = require $configFile;
|
||||
|
||||
date_default_timezone_set('Europe/Berlin');
|
||||
ini_set('display_errors', '0');
|
||||
ini_set('log_errors', '1');
|
||||
|
||||
require WS_APP . '/util.php';
|
||||
require WS_APP . '/rules.php';
|
||||
require WS_APP . '/db.php';
|
||||
require WS_APP . '/migrations.php';
|
||||
require WS_APP . '/auth.php';
|
||||
require WS_APP . '/character.php';
|
||||
require WS_APP . '/portrait.php';
|
||||
require WS_APP . '/invite.php';
|
||||
require WS_APP . '/mailer.php';
|
||||
require WS_APP . '/pdf.php';
|
||||
require WS_APP . '/sheet.php';
|
||||
require WS_APP . '/pages.php';
|
||||
|
||||
$storage = (string) config('app.storage_path', WS_ROOT . '/storage');
|
||||
if (is_dir($storage . '/logs') && is_writable($storage . '/logs')) {
|
||||
ini_set('error_log', $storage . '/logs/php.log');
|
||||
}
|
||||
|
||||
set_exception_handler(static function (Throwable $error): void {
|
||||
error_log('Westreiche: ' . $error::class . ': ' . $error->getMessage() . ' in ' . $error->getFile() . ':' . $error->getLine());
|
||||
http_response_code(500);
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
echo '<!doctype html><meta charset="utf-8"><title>Fehler 500</title>'
|
||||
. '<body style="font-family:Georgia,serif;background:#0a0d16;color:#efe3c8;padding:3rem">'
|
||||
. '<h1 style="color:#e8c766">Die Sterne stehen ungünstig</h1>'
|
||||
. '<p>Es ist ein interner Fehler aufgetreten. Bitte später erneut versuchen.</p>'
|
||||
. '<p><a style="color:#c9a227" href="' . e(url('/')) . '">Zurück</a></p></body>';
|
||||
});
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
security_headers();
|
||||
if (current_path() !== '/health') {
|
||||
start_session();
|
||||
}
|
||||
}
|
||||
700
westreiche_website/app/character.php
Normal file
700
westreiche_website/app/character.php
Normal file
|
|
@ -0,0 +1,700 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Westreiche – Datenzugriff für Charaktere, Fertigkeiten, Zauber und Inventar. */
|
||||
|
||||
/* ------------------------------------------------------------- Charaktere */
|
||||
|
||||
function characters_all(array $user): array
|
||||
{
|
||||
if (auth_can_manage($user)) {
|
||||
return db()->query(
|
||||
'SELECT c.*, u.username AS owner_name
|
||||
FROM characters c JOIN users u ON u.id = c.user_id
|
||||
ORDER BY u.username, c.sort_order, c.name'
|
||||
)->fetchAll();
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'SELECT c.*, u.username AS owner_name
|
||||
FROM characters c JOIN users u ON u.id = c.user_id
|
||||
WHERE c.user_id = ?
|
||||
ORDER BY c.sort_order, c.name'
|
||||
);
|
||||
$stmt->execute([(int) $user['id']]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function character_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT c.*, u.username AS owner_name FROM characters c JOIN users u ON u.id = c.user_id WHERE c.id = ? LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
/** Charakter laden und Zugriff prüfen: eigener Charakter oder Admin. */
|
||||
function character_require(int $id, array $user): array
|
||||
{
|
||||
$character = character_find($id);
|
||||
if ($character === null) {
|
||||
abort_page(404, 'Diesen Charakter gibt es nicht (mehr).');
|
||||
}
|
||||
if (!auth_can_manage($user) && (int) $character['user_id'] !== (int) $user['id']) {
|
||||
abort_page(403, 'Dieser Charakter gehört zu einem anderen Konto.');
|
||||
}
|
||||
return $character;
|
||||
}
|
||||
|
||||
function character_status_label(string $status): string
|
||||
{
|
||||
return WS_CHARACTER_STATUS[$status] ?? $status;
|
||||
}
|
||||
|
||||
function character_create(int $userId, array $data): int
|
||||
{
|
||||
// Rettungswürfe starten auf dem Klassenwert der Stufe 1
|
||||
// (Hausregel: Klasse + Stufe bestimmen den Grundwert).
|
||||
$data = array_merge($data, saving_throws_for((string) ($data['class_name'] ?? 'Kämpfer'), (int) ($data['level'] ?? 1)));
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO characters (user_id, name, title, class_name, level, xp, hp_max, hp_current, ac, attack_bonus,
|
||||
attr_str, attr_dex, attr_con, attr_int, attr_wis, attr_cha,
|
||||
save_death, save_wand, save_paralysis, save_breath, save_spell,
|
||||
alignment, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$userId,
|
||||
$data['name'],
|
||||
$data['title'] ?? '',
|
||||
$data['class_name'] ?? 'Kämpfer',
|
||||
$data['level'] ?? 1,
|
||||
$data['xp'] ?? 0,
|
||||
$data['hp_max'] ?? 1,
|
||||
$data['hp_current'] ?? $data['hp_max'] ?? 1,
|
||||
character_ac_value($data['ac'] ?? null),
|
||||
$data['attack_bonus'] ?? 0,
|
||||
$data['attr_str'] ?? 10,
|
||||
$data['attr_dex'] ?? 10,
|
||||
$data['attr_con'] ?? 10,
|
||||
$data['attr_int'] ?? 10,
|
||||
$data['attr_wis'] ?? 10,
|
||||
$data['attr_cha'] ?? 10,
|
||||
$data['save_death'] ?? null,
|
||||
$data['save_wand'] ?? null,
|
||||
$data['save_paralysis'] ?? null,
|
||||
$data['save_breath'] ?? null,
|
||||
$data['save_spell'] ?? null,
|
||||
$data['alignment'] ?? '',
|
||||
utc_now(),
|
||||
utc_now(),
|
||||
]);
|
||||
$id = (int) db()->lastInsertId();
|
||||
character_seed_skills($id);
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trägt alle Katalog-Fertigkeiten mit ihrem Startwert ein
|
||||
* (Fertigkeitsstufe = Attributsbonus des zugeordneten Attributs).
|
||||
*/
|
||||
/**
|
||||
* Gleicht den Fertigkeitenkatalog mit WS_SKILL_CATALOG ab: fehlende Einträge
|
||||
* anlegen, Attribut/Gruppe nachziehen, alte Einträge in „Sonstiges“ parken.
|
||||
*/
|
||||
function skills_sync_catalog(): array
|
||||
{
|
||||
$existing = [];
|
||||
foreach (skills_catalog() as $skill) {
|
||||
$existing[(string) $skill['name']] = $skill;
|
||||
}
|
||||
$insert = db()->prepare('INSERT INTO skills (name, attribute, category, sort_order) VALUES (?, ?, ?, ?)');
|
||||
$update = db()->prepare('UPDATE skills SET attribute = ?, category = ?, sort_order = ? WHERE id = ?');
|
||||
$order = 0;
|
||||
$created = 0;
|
||||
$updated = 0;
|
||||
foreach (WS_SKILL_CATALOG as $name => [$attribute, $group]) {
|
||||
$order += 10;
|
||||
if (!isset($existing[$name])) {
|
||||
$insert->execute([$name, $attribute, $group, $order]);
|
||||
$created++;
|
||||
continue;
|
||||
}
|
||||
$skill = $existing[$name];
|
||||
if ((string) $skill['attribute'] !== $attribute || (string) $skill['category'] !== $group) {
|
||||
$update->execute([$attribute, $group, $order, (int) $skill['id']]);
|
||||
$updated++;
|
||||
}
|
||||
unset($existing[$name]);
|
||||
}
|
||||
// Nicht mehr im Bogen geführte Fertigkeiten bleiben erhalten, aber gruppiert.
|
||||
$park = db()->prepare("UPDATE skills SET category = 'Sonstiges' WHERE id = ? AND category <> 'Sonstiges'");
|
||||
foreach ($existing as $skill) {
|
||||
$park->execute([(int) $skill['id']]);
|
||||
}
|
||||
return ['created' => $created, 'updated' => $updated];
|
||||
}
|
||||
|
||||
function character_seed_skills(int $characterId): int
|
||||
{
|
||||
$character = character_find($characterId);
|
||||
if ($character === null) {
|
||||
return 0;
|
||||
}
|
||||
$insert = db()->prepare(
|
||||
'INSERT INTO character_skills (character_id, skill_id, name, bonus, note) VALUES (?, ?, ?, ?, \'\')
|
||||
ON DUPLICATE KEY UPDATE skill_id = VALUES(skill_id)'
|
||||
);
|
||||
$count = 0;
|
||||
foreach (skills_catalog() as $skill) {
|
||||
$attribute = trim((string) ($skill['attribute'] ?? ''));
|
||||
$bonus = $attribute === '' ? 0 : attribute_bonus((int) ($character['attr_' . strtolower($attribute)] ?? 10));
|
||||
$insert->execute([$characterId, (int) $skill['id'], (string) $skill['name'], $bonus]);
|
||||
$count++;
|
||||
}
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Startwerte der Fertigkeiten auf die aktuellen Attributsboni zurücksetzen.
|
||||
* Manuell erhöhte Werte (Bonus weicht vom Startwert ab) bleiben unberührt,
|
||||
* außer bei $force = true.
|
||||
*/
|
||||
function character_reset_skills(int $characterId, bool $force = false): int
|
||||
{
|
||||
$character = character_find($characterId);
|
||||
if ($character === null) {
|
||||
return 0;
|
||||
}
|
||||
$catalog = [];
|
||||
foreach (skills_catalog() as $skill) {
|
||||
$catalog[(int) $skill['id']] = $skill;
|
||||
}
|
||||
$changed = 0;
|
||||
$update = db()->prepare('UPDATE character_skills SET bonus = ? WHERE id = ?');
|
||||
foreach (character_skills($characterId) as $row) {
|
||||
$skill = $catalog[(int) ($row['skill_id'] ?? 0)] ?? null;
|
||||
if ($skill === null) {
|
||||
continue;
|
||||
}
|
||||
$attribute = trim((string) ($skill['attribute'] ?? ''));
|
||||
if ($attribute === '') {
|
||||
continue;
|
||||
}
|
||||
$target = attribute_bonus((int) ($character['attr_' . strtolower($attribute)] ?? 10));
|
||||
if ($force || (int) $row['bonus'] === $target) {
|
||||
$update->execute([$target, (int) $row['id']]);
|
||||
$changed++;
|
||||
}
|
||||
}
|
||||
return $changed;
|
||||
}
|
||||
|
||||
/** Basisdaten aktualisieren (Name, Klasse, Werte, Rettungswürfe, Notizen). */
|
||||
function character_update(int $id, array $d): void
|
||||
{
|
||||
$before = character_find($id);
|
||||
|
||||
// Stufe oder Klasse geändert? Dann kommen die Rettungswürfe aus der Tabelle.
|
||||
if ($before !== null) {
|
||||
$levelChanged = (int) $before['level'] !== (int) ($d['level'] ?? 1);
|
||||
$classChanged = (string) $before['class_name'] !== (string) ($d['class_name'] ?? '');
|
||||
if ($levelChanged || $classChanged) {
|
||||
$d = array_merge($d, saving_throws_for((string) ($d['class_name'] ?? 'Kämpfer'), (int) ($d['level'] ?? 1)));
|
||||
}
|
||||
}
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'UPDATE characters SET name = ?, title = ?, class_name = ?, level = ?, xp = ?, hp_max = ?, hp_current = ?,
|
||||
ac = ?, attack_bonus = ?, attr_str = ?, attr_dex = ?, attr_con = ?, attr_int = ?, attr_wis = ?, attr_cha = ?,
|
||||
save_death = ?, save_wand = ?, save_paralysis = ?, save_breath = ?, save_spell = ?,
|
||||
alignment = ?, deity = ?, age = ?, height = ?, weight = ?, gold_coins = ?,
|
||||
appearance = ?, background = ?, notes = ?, status = ?, updated_at = ?
|
||||
WHERE id = ?'
|
||||
);
|
||||
$stmt->execute([
|
||||
$d['name'],
|
||||
$d['title'] ?? '',
|
||||
$d['class_name'] ?? 'Kämpfer',
|
||||
$d['level'] ?? 1,
|
||||
$d['xp'] ?? 0,
|
||||
$d['hp_max'] ?? 1,
|
||||
$d['hp_current'] ?? 1,
|
||||
character_ac_value($d['ac'] ?? null),
|
||||
$d['attack_bonus'] ?? 0,
|
||||
$d['attr_str'] ?? 10,
|
||||
$d['attr_dex'] ?? 10,
|
||||
$d['attr_con'] ?? 10,
|
||||
$d['attr_int'] ?? 10,
|
||||
$d['attr_wis'] ?? 10,
|
||||
$d['attr_cha'] ?? 10,
|
||||
$d['save_death'] ?? null,
|
||||
$d['save_wand'] ?? null,
|
||||
$d['save_paralysis'] ?? null,
|
||||
$d['save_breath'] ?? null,
|
||||
$d['save_spell'] ?? null,
|
||||
$d['alignment'] ?? '',
|
||||
$d['deity'] ?? '',
|
||||
$d['age'] ?? '',
|
||||
$d['height'] ?? '',
|
||||
$d['weight'] ?? '',
|
||||
$d['gold_coins'] ?? 0,
|
||||
$d['appearance'] ?? '',
|
||||
$d['background'] ?? '',
|
||||
$d['notes'] ?? '',
|
||||
$d['status'] ?? 'active',
|
||||
utc_now(),
|
||||
$id,
|
||||
]);
|
||||
|
||||
// Attributsänderungen ziehen die Startwerte der Fertigkeiten mit,
|
||||
// solange sie nicht manuell verändert wurden.
|
||||
if ($before !== null) {
|
||||
$attributes = ['str', 'dex', 'con', 'int', 'wis', 'cha'];
|
||||
$shifted = false;
|
||||
foreach ($attributes as $attribute) {
|
||||
if ((int) ($before['attr_' . $attribute] ?? 10) !== (int) ($d['attr_' . $attribute] ?? 10)) {
|
||||
$shifted = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($shifted) {
|
||||
character_reset_skills($id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Rüstungsklasse: leer/0 bedeutet „automatisch aus der Rüstung“. */
|
||||
function character_ac_value(mixed $value): ?int
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
$int = (int) $value;
|
||||
return $int > 0 ? $int : null;
|
||||
}
|
||||
|
||||
function character_delete(int $id): void
|
||||
{
|
||||
db()->prepare('DELETE FROM characters WHERE id = ?')->execute([$id]);
|
||||
}
|
||||
|
||||
/** Abgeleitete Anzeigewerte (Boni, Trefferpunkte-Status, Zauberplätze-Gruppe). */
|
||||
function character_derived(array $c): array
|
||||
{
|
||||
$bonuses = [];
|
||||
foreach (WS_ATTRIBUTES as $field => [, $label]) {
|
||||
$bonuses[$field] = attribute_bonus((int) ($c[$field] ?? 10));
|
||||
}
|
||||
$hp = max(0, (int) $c['hp_current']);
|
||||
$hpMax = max(1, (int) $c['hp_max']);
|
||||
return [
|
||||
'bonuses' => $bonuses,
|
||||
'hp_ratio' => min(1.0, $hp / $hpMax),
|
||||
'hp_state' => $hp <= 0 ? 'unconscious' : ($hp <= $hpMax / 4 ? 'critical' : ($hp < $hpMax / 2 ? 'wounded' : 'healthy')),
|
||||
'str_damage' => $bonuses['attr_str'],
|
||||
];
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- Fertigkeiten */
|
||||
|
||||
function skills_catalog(): array
|
||||
{
|
||||
return db()->query('SELECT * FROM skills ORDER BY sort_order, name')->fetchAll();
|
||||
}
|
||||
|
||||
function skills_catalog_add(string $name, string $attribute, string $category): void
|
||||
{
|
||||
$max = (int) db()->query('SELECT COALESCE(MAX(sort_order), 0) FROM skills')->fetchColumn();
|
||||
db()->prepare('INSERT INTO skills (name, attribute, category, sort_order) VALUES (?, ?, ?, ?)')
|
||||
->execute([$name, $attribute, $category, $max + 10]);
|
||||
}
|
||||
|
||||
function skills_catalog_delete(int $id): void
|
||||
{
|
||||
db()->prepare('DELETE FROM skills WHERE id = ?')->execute([$id]);
|
||||
}
|
||||
|
||||
function character_skills(int $characterId): array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT cs.*, s.attribute, s.category FROM character_skills cs
|
||||
LEFT JOIN skills s ON s.id = cs.skill_id
|
||||
WHERE cs.character_id = ? ORDER BY cs.name'
|
||||
);
|
||||
$stmt->execute([$characterId]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function character_skill_add(int $characterId, ?int $skillId, string $name, int $bonus, string $note): void
|
||||
{
|
||||
if ($skillId !== null && $name === '') {
|
||||
$stmt = db()->prepare('SELECT name FROM skills WHERE id = ?');
|
||||
$stmt->execute([$skillId]);
|
||||
$name = (string) ($stmt->fetchColumn() ?: '');
|
||||
}
|
||||
if ($name === '') {
|
||||
return;
|
||||
}
|
||||
db()->prepare(
|
||||
'INSERT INTO character_skills (character_id, skill_id, name, bonus, note) VALUES (?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE bonus = VALUES(bonus), note = VALUES(note), skill_id = VALUES(skill_id)'
|
||||
)->execute([$characterId, $skillId, shorten($name, 80), $bonus, shorten($note, 255)]);
|
||||
}
|
||||
|
||||
function character_skill_delete(int $characterId, int $id): void
|
||||
{
|
||||
db()->prepare('DELETE FROM character_skills WHERE id = ? AND character_id = ?')->execute([$id, $characterId]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- Zauber/Liturgien */
|
||||
|
||||
function spells_search(string $school, int $grade, string $needle = '', int $limit = 60): array
|
||||
{
|
||||
$sql = 'SELECT * FROM spells WHERE school = ?';
|
||||
$args = [$school];
|
||||
if ($grade > 0) {
|
||||
$sql .= ' AND grade = ?';
|
||||
$args[] = $grade;
|
||||
}
|
||||
if ($needle !== '') {
|
||||
$sql .= ' AND name LIKE ?';
|
||||
$args[] = '%' . $needle . '%';
|
||||
}
|
||||
$sql .= ' ORDER BY grade, name LIMIT ' . max(1, $limit);
|
||||
$stmt = db()->prepare($sql);
|
||||
$stmt->execute($args);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function spell_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM spells WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
function character_spells(int $characterId): array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT cs.*, s.classes, s.duration, s.range_text, s.summary, s.body
|
||||
FROM character_spells cs LEFT JOIN spells s ON s.id = cs.spell_id
|
||||
WHERE cs.character_id = ? ORDER BY cs.school, cs.grade, cs.name'
|
||||
);
|
||||
$stmt->execute([$characterId]);
|
||||
$rows = $stmt->fetchAll();
|
||||
return ['arkan' => array_values(array_filter($rows, static fn ($r) => $r['school'] === 'arkan')),
|
||||
'klerikal' => array_values(array_filter($rows, static fn ($r) => $r['school'] === 'klerikal'))];
|
||||
}
|
||||
|
||||
/** Zauber sind in Westreiche nicht vorbereitungspflichtig – prepared wird nicht mehr geführt. */
|
||||
function character_spell_add(int $characterId, ?int $spellId, string $name, string $school, int $grade, string $note): void
|
||||
{
|
||||
if ($spellId !== null) {
|
||||
$spell = spell_find($spellId);
|
||||
if ($spell !== null) {
|
||||
$name = $name !== '' ? $name : (string) $spell['name'];
|
||||
$school = (string) $spell['school'];
|
||||
$grade = (int) $spell['grade'];
|
||||
}
|
||||
}
|
||||
if ($name === '') {
|
||||
return;
|
||||
}
|
||||
if (!in_array($school, ['arkan', 'klerikal'], true)) {
|
||||
$school = 'arkan';
|
||||
}
|
||||
$grade = max(1, min(9, $grade));
|
||||
db()->prepare(
|
||||
'INSERT INTO character_spells (character_id, spell_id, name, school, grade, note)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE grade = VALUES(grade), note = VALUES(note)'
|
||||
)->execute([$characterId, $spellId, shorten($name, 120), $school, $grade, shorten($note, 255)]);
|
||||
}
|
||||
|
||||
function character_spell_delete(int $characterId, int $id): void
|
||||
{
|
||||
db()->prepare('DELETE FROM character_spells WHERE id = ? AND character_id = ?')->execute([$id, $characterId]);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- Inventar */
|
||||
|
||||
function character_items(int $characterId): array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM character_items WHERE character_id = ? ORDER BY category, sort_order, name');
|
||||
$stmt->execute([$characterId]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function character_item_add(int $characterId, array $d): void
|
||||
{
|
||||
$name = trim((string) ($d['name'] ?? ''));
|
||||
if ($name === '') {
|
||||
return;
|
||||
}
|
||||
$category = (string) ($d['category'] ?? 'Ausrüstung');
|
||||
if (!in_array($category, WS_ITEM_CATEGORIES, true)) {
|
||||
$category = 'Sonstiges';
|
||||
}
|
||||
db()->prepare(
|
||||
'INSERT INTO character_items (character_id, name, qty, category, weight, value, equipped, note)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
)->execute([
|
||||
$characterId,
|
||||
shorten($name, 120),
|
||||
max(1, (int) ($d['qty'] ?? 1)),
|
||||
$category,
|
||||
shorten((string) ($d['weight'] ?? ''), 40),
|
||||
shorten((string) ($d['value'] ?? ''), 40),
|
||||
!empty($d['equipped']) ? 1 : 0,
|
||||
shorten((string) ($d['note'] ?? ''), 255),
|
||||
]);
|
||||
}
|
||||
|
||||
function character_item_delete(int $characterId, int $id): void
|
||||
{
|
||||
db()->prepare('DELETE FROM character_items WHERE id = ? AND character_id = ?')->execute([$id, $characterId]);
|
||||
}
|
||||
|
||||
function character_item_toggle(int $characterId, int $id): void
|
||||
{
|
||||
db()->prepare('UPDATE character_items SET equipped = 1 - equipped WHERE id = ? AND character_id = ?')
|
||||
->execute([$id, $characterId]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- Waffen & Rüstungen */
|
||||
|
||||
function weapons_catalog(): array
|
||||
{
|
||||
return db()->query('SELECT * FROM weapons ORDER BY sort_order, name')->fetchAll();
|
||||
}
|
||||
|
||||
function armors_catalog(): array
|
||||
{
|
||||
return db()->query('SELECT * FROM armors ORDER BY sort_order, name')->fetchAll();
|
||||
}
|
||||
|
||||
function weapon_catalog_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM weapons WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
function armor_catalog_find(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM armors WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
return $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
function character_weapons(int $characterId): array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM character_weapons WHERE character_id = ? ORDER BY sort_order, name');
|
||||
$stmt->execute([$characterId]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function character_armors(int $characterId): array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM character_armors WHERE character_id = ? ORDER BY sort_order, name');
|
||||
$stmt->execute([$characterId]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
/** Waffe hinzufügen: aus dem Katalog (Werte übernehmen) oder frei eingetragen. */
|
||||
function character_weapon_add(int $characterId, int $weaponId, array $d = []): void
|
||||
{
|
||||
$name = trim((string) ($d['name'] ?? ''));
|
||||
$damage = trim((string) ($d['damage'] ?? ''));
|
||||
$bonus = (int) ($d['attack_bonus'] ?? 0);
|
||||
$category = (string) ($d['category'] ?? 'Nahkampf');
|
||||
|
||||
if ($weaponId > 0 && ($weapon = weapon_catalog_find($weaponId)) !== null) {
|
||||
$name = $name !== '' ? $name : (string) $weapon['name'];
|
||||
$damage = $damage !== '' ? $damage : (string) $weapon['damage'];
|
||||
$category = $category !== '' ? $category : (string) $weapon['category'];
|
||||
$bonus = $bonus !== 0 ? $bonus : (int) $weapon['attack_bonus'];
|
||||
}
|
||||
if ($name === '') {
|
||||
return;
|
||||
}
|
||||
if (!in_array($category, ['Nahkampf', 'Fernkampf'], true)) {
|
||||
$category = 'Nahkampf';
|
||||
}
|
||||
db()->prepare(
|
||||
'INSERT INTO character_weapons (character_id, weapon_id, name, damage, attack_bonus, category, note, equipped)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
)->execute([
|
||||
$characterId,
|
||||
$weaponId > 0 ? $weaponId : null,
|
||||
shorten($name, 80),
|
||||
shorten($damage === '' ? '1W6' : $damage, 20),
|
||||
max(-10, min(10, $bonus)),
|
||||
$category,
|
||||
shorten((string) ($d['note'] ?? ''), 255),
|
||||
!empty($d['equipped']) ? 1 : 0,
|
||||
]);
|
||||
}
|
||||
|
||||
function character_weapon_update(int $characterId, int $id, array $d): void
|
||||
{
|
||||
$name = trim((string) ($d['name'] ?? ''));
|
||||
if ($name === '') {
|
||||
return;
|
||||
}
|
||||
$category = (string) ($d['category'] ?? 'Nahkampf');
|
||||
if (!in_array($category, ['Nahkampf', 'Fernkampf'], true)) {
|
||||
$category = 'Nahkampf';
|
||||
}
|
||||
db()->prepare(
|
||||
'UPDATE character_weapons SET name = ?, damage = ?, attack_bonus = ?, category = ?, note = ?, equipped = ?
|
||||
WHERE id = ? AND character_id = ?'
|
||||
)->execute([
|
||||
shorten($name, 80),
|
||||
shorten((string) ($d['damage'] ?? ''), 20),
|
||||
max(-10, min(10, (int) ($d['attack_bonus'] ?? 0))),
|
||||
$category,
|
||||
shorten((string) ($d['note'] ?? ''), 255),
|
||||
!empty($d['equipped']) ? 1 : 0,
|
||||
$id,
|
||||
$characterId,
|
||||
]);
|
||||
}
|
||||
|
||||
function character_weapon_delete(int $characterId, int $id): void
|
||||
{
|
||||
db()->prepare('DELETE FROM character_weapons WHERE id = ? AND character_id = ?')->execute([$id, $characterId]);
|
||||
}
|
||||
|
||||
function character_weapon_toggle(int $characterId, int $id): void
|
||||
{
|
||||
db()->prepare('UPDATE character_weapons SET equipped = 1 - equipped WHERE id = ? AND character_id = ?')
|
||||
->execute([$id, $characterId]);
|
||||
}
|
||||
|
||||
function character_armor_add(int $characterId, int $armorId, array $d = []): void
|
||||
{
|
||||
$name = trim((string) ($d['name'] ?? ''));
|
||||
$bonus = isset($d['ac_bonus']) && $d['ac_bonus'] !== '' ? (int) $d['ac_bonus'] : null;
|
||||
$kind = (string) ($d['kind'] ?? 'Rüstung');
|
||||
|
||||
if ($armorId > 0 && ($armor = armor_catalog_find($armorId)) !== null) {
|
||||
$name = $name !== '' ? $name : (string) $armor['name'];
|
||||
$bonus = $bonus !== null ? $bonus : (int) $armor['ac_bonus'];
|
||||
$kind = $kind !== '' ? $kind : (string) $armor['kind'];
|
||||
}
|
||||
if ($name === '') {
|
||||
return;
|
||||
}
|
||||
if (!in_array($kind, ['Rüstung', 'Schild'], true)) {
|
||||
$kind = 'Rüstung';
|
||||
}
|
||||
db()->prepare(
|
||||
'INSERT INTO character_armors (character_id, armor_id, name, ac_bonus, kind, note, equipped)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||||
)->execute([
|
||||
$characterId,
|
||||
$armorId > 0 ? $armorId : null,
|
||||
shorten($name, 80),
|
||||
max(-5, min(15, $bonus ?? 0)),
|
||||
$kind,
|
||||
shorten((string) ($d['note'] ?? ''), 255),
|
||||
!empty($d['equipped']) ? 1 : 0,
|
||||
]);
|
||||
}
|
||||
|
||||
function character_armor_update(int $characterId, int $id, array $d): void
|
||||
{
|
||||
$name = trim((string) ($d['name'] ?? ''));
|
||||
if ($name === '') {
|
||||
return;
|
||||
}
|
||||
$kind = (string) ($d['kind'] ?? 'Rüstung');
|
||||
if (!in_array($kind, ['Rüstung', 'Schild'], true)) {
|
||||
$kind = 'Rüstung';
|
||||
}
|
||||
db()->prepare(
|
||||
'UPDATE character_armors SET name = ?, ac_bonus = ?, kind = ?, note = ?, equipped = ?
|
||||
WHERE id = ? AND character_id = ?'
|
||||
)->execute([
|
||||
shorten($name, 80),
|
||||
max(-5, min(15, (int) ($d['ac_bonus'] ?? 0))),
|
||||
$kind,
|
||||
shorten((string) ($d['note'] ?? ''), 255),
|
||||
!empty($d['equipped']) ? 1 : 0,
|
||||
$id,
|
||||
$characterId,
|
||||
]);
|
||||
}
|
||||
|
||||
function character_armor_delete(int $characterId, int $id): void
|
||||
{
|
||||
db()->prepare('DELETE FROM character_armors WHERE id = ? AND character_id = ?')->execute([$id, $characterId]);
|
||||
}
|
||||
|
||||
function character_armor_toggle(int $characterId, int $id): void
|
||||
{
|
||||
db()->prepare('UPDATE character_armors SET equipped = 1 - equipped WHERE id = ? AND character_id = ?')
|
||||
->execute([$id, $characterId]);
|
||||
}
|
||||
|
||||
function character_skill_update(int $characterId, int $id, int $bonus, string $note): void
|
||||
{
|
||||
db()->prepare('UPDATE character_skills SET bonus = ?, note = ? WHERE id = ? AND character_id = ?')
|
||||
->execute([max(-10, min(30, $bonus)), shorten($note, 255), $id, $characterId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fertigkeiten nach Gruppen des Charakterbogens sortieren.
|
||||
*
|
||||
* @param list<array> $skills
|
||||
* @return array<string, list<array>>
|
||||
*/
|
||||
function skills_grouped(array $skills): array
|
||||
{
|
||||
$groups = [];
|
||||
foreach (WS_SKILL_GROUPS as $group) {
|
||||
$groups[$group] = [];
|
||||
}
|
||||
foreach ($skills as $skill) {
|
||||
$group = trim((string) ($skill['category'] ?? ''));
|
||||
if ($group === '') {
|
||||
$group = 'Sonstiges';
|
||||
}
|
||||
$groups[$group][] = $skill;
|
||||
}
|
||||
// Feste Reihenfolge des Charakterbogens, unbekannte Gruppen danach.
|
||||
$ordered = [];
|
||||
$sequence = WS_SKILL_GROUPS;
|
||||
$sequence[] = 'Sonstiges';
|
||||
foreach ($sequence as $group) {
|
||||
if (empty($groups[$group])) {
|
||||
continue;
|
||||
}
|
||||
$rows = $groups[$group];
|
||||
usort($rows, static fn ($a, $b) => strcasecmp((string) $a['name'], (string) $b['name']));
|
||||
$ordered[$group] = $rows;
|
||||
unset($groups[$group]);
|
||||
}
|
||||
foreach ($groups as $group => $rows) {
|
||||
if ($rows === []) {
|
||||
continue;
|
||||
}
|
||||
usort($rows, static fn ($a, $b) => strcasecmp((string) $a['name'], (string) $b['name']));
|
||||
$ordered[$group] = $rows;
|
||||
}
|
||||
return $ordered;
|
||||
}
|
||||
|
||||
/** Attributsbonus (MOD) einer Fertigkeit für einen Charakter. */
|
||||
function skill_attribute_modifier(array $character, array $skill): ?int
|
||||
{
|
||||
$attribute = strtolower(trim((string) ($skill['attribute'] ?? '')));
|
||||
if ($attribute === '') {
|
||||
return null;
|
||||
}
|
||||
return attribute_bonus((int) ($character['attr_' . $attribute] ?? 10));
|
||||
}
|
||||
40
westreiche_website/app/config.example.php
Normal file
40
westreiche_website/app/config.example.php
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
/**
|
||||
* Beispielkonfiguration. Wird nicht ausgeliefert; beim Deployment erzeugt
|
||||
* tools/deploy_app.sh daraus app/config.local.php (Werte aus credentials.txt).
|
||||
*/
|
||||
return [
|
||||
'db' => [
|
||||
'host' => 'DB_HOST',
|
||||
'port' => 3306,
|
||||
'name' => 'DB_NAME',
|
||||
'user' => 'DB_USER',
|
||||
'password' => 'DB_PASSWORD',
|
||||
'charset' => 'utf8mb4',
|
||||
],
|
||||
'mail' => [
|
||||
// Leer = kein Versand (Einladungslinks werden nur angezeigt).
|
||||
'host' => 'MAIL_HOST',
|
||||
'port' => 587,
|
||||
// 'tls' = STARTTLS (587), 'ssl' = implizites TLS (465)
|
||||
'secure' => 'tls',
|
||||
'user' => 'MAIL_USER',
|
||||
'password' => 'MAIL_PASSWORD',
|
||||
'from' => 'MAIL_FROM',
|
||||
'from_name' => 'MAIL_FROM_NAME',
|
||||
'timeout' => 15,
|
||||
],
|
||||
'app' => [
|
||||
// Leer, wenn die App direkt im Zielverzeichnis liegt; sonst z. B. '/westreiche_website'.
|
||||
'base_path' => '',
|
||||
'public_url' => 'https://zauberturm.de',
|
||||
'storage_path' => dirname(__DIR__) . '/storage',
|
||||
'install_token' => 'wird-beim-deployment-erzeugt',
|
||||
'session_idle_seconds' => 30 * 86400,
|
||||
'session_absolute_seconds' => 90 * 86400,
|
||||
'remember_seconds' => 90 * 86400,
|
||||
'login_window_seconds' => 900,
|
||||
'login_max_per_user' => 5,
|
||||
'login_max_per_ip' => 15,
|
||||
],
|
||||
];
|
||||
33
westreiche_website/app/db.php
Normal file
33
westreiche_website/app/db.php
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Westreiche – Datenbankverbindung (PDO, MariaDB/MySQL). */
|
||||
|
||||
function db(): PDO
|
||||
{
|
||||
static $pdo = null;
|
||||
if ($pdo instanceof PDO) {
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
$db = (array) config('db', []);
|
||||
$dsn = sprintf(
|
||||
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
|
||||
(string) ($db['host'] ?? 'localhost'),
|
||||
(int) ($db['port'] ?? 3306),
|
||||
(string) ($db['name'] ?? ''),
|
||||
(string) ($db['charset'] ?? 'utf8mb4')
|
||||
);
|
||||
|
||||
$pdo = new PDO($dsn, (string) ($db['user'] ?? ''), (string) ($db['password'] ?? ''), [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||
]);
|
||||
$pdo->exec("SET time_zone = '+00:00'");
|
||||
if (function_exists('ws_migrations_apply')) {
|
||||
ws_migrations_apply($pdo);
|
||||
}
|
||||
return $pdo;
|
||||
}
|
||||
123
westreiche_website/app/invite.php
Normal file
123
westreiche_website/app/invite.php
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Einladungen für die geschlossene Benutzergruppe.
|
||||
*
|
||||
* Der Admin legt das Konto an und erzeugt dabei einen einmaligen Link. Über
|
||||
* diesen Link vergibt der Eingeladene sein Passwort selbst. Gespeichert wird
|
||||
* nur der SHA-256-Hash des Tokens; der Link ist sieben Tage gültig.
|
||||
*
|
||||
* Ist der Mailversand eingerichtet (app/mailer.php), geht der Link zusätzlich
|
||||
* per E-Mail an die hinterlegte Adresse; sonst zeigt das Benutzerformular den
|
||||
* Link zum Kopieren an.
|
||||
*/
|
||||
|
||||
const WS_INVITE_SECONDS = 7 * 86400;
|
||||
|
||||
function invite_url(string $token): string
|
||||
{
|
||||
$base = rtrim((string) config('app.public_url', ''), '/');
|
||||
$path = rtrim((string) config('app.base_path', ''), '/');
|
||||
// public_url darf mit oder ohne base_path hinterlegt sein – doppelte Pfade vermeiden.
|
||||
if ($path !== '' && str_ends_with($base, $path)) {
|
||||
$base = rtrim(substr($base, 0, -strlen($path)), '/');
|
||||
}
|
||||
return $base . url('/invite/' . $token);
|
||||
}
|
||||
|
||||
/** Legt einen neuen Einladungslink an; ein älterer Link wird ungültig. */
|
||||
function invite_create(int $userId, ?int $createdBy): array
|
||||
{
|
||||
$token = bin2hex(random_bytes(32));
|
||||
$expiresAt = utc_after(WS_INVITE_SECONDS);
|
||||
|
||||
db()->prepare('DELETE FROM user_invites WHERE user_id = ?')->execute([$userId]);
|
||||
db()->prepare(
|
||||
'INSERT INTO user_invites (user_id, token_hash, created_by, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?)'
|
||||
)->execute([$userId, hash('sha256', $token), $createdBy, utc_now(), $expiresAt]);
|
||||
|
||||
return ['token' => $token, 'url' => invite_url($token), 'expires_at' => $expiresAt];
|
||||
}
|
||||
|
||||
/** Sucht eine offene, noch gültige Einladung zum Token. */
|
||||
function invite_find(string $token): ?array
|
||||
{
|
||||
if (preg_match('/^[a-f0-9]{64}$/', $token) !== 1) {
|
||||
return null;
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'SELECT i.*, u.username, u.email, u.display_name, u.status
|
||||
FROM user_invites i JOIN users u ON u.id = i.user_id
|
||||
WHERE i.token_hash = ? AND i.used_at IS NULL AND i.expires_at >= ? LIMIT 1'
|
||||
);
|
||||
$stmt->execute([hash('sha256', $token), utc_now()]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['user_id'] = (int) $row['user_id'];
|
||||
return $row;
|
||||
}
|
||||
|
||||
function invite_active_for_user(int $userId): ?array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT * FROM user_invites WHERE user_id = ? AND used_at IS NULL AND expires_at >= ?
|
||||
ORDER BY id DESC LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$userId, utc_now()]);
|
||||
return $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
function invite_redeem(string $token, string $password): void
|
||||
{
|
||||
$invite = invite_find($token);
|
||||
if ($invite === null) {
|
||||
throw new RuntimeException('invalid');
|
||||
}
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
$pdo->prepare(
|
||||
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 0,
|
||||
auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?'
|
||||
)->execute([hash_password($password), utc_now(), utc_now(), (int) $invite['user_id']]);
|
||||
$pdo->prepare('UPDATE user_invites SET used_at = ? WHERE id = ?')
|
||||
->execute([utc_now(), (int) $invite['id']]);
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
$pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt das Passwort zurück, sperrt alte Sitzungen und erzeugt einen neuen
|
||||
* Einladungslink (Rückgabe: URL zum Weitergeben).
|
||||
*/
|
||||
function invite_provision(int $userId, ?int $createdBy): array
|
||||
{
|
||||
$user = auth_user_by_id($userId);
|
||||
if (!$user) {
|
||||
throw new RuntimeException('Benutzer nicht gefunden.');
|
||||
}
|
||||
|
||||
$pdo = db();
|
||||
$pdo->beginTransaction();
|
||||
try {
|
||||
$pdo->prepare(
|
||||
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 1,
|
||||
auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?'
|
||||
)->execute([hash_password(bin2hex(random_bytes(24))), utc_now(), utc_now(), $userId]);
|
||||
$pdo->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
$pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
|
||||
return invite_create($userId, $createdBy);
|
||||
}
|
||||
393
westreiche_website/app/mailer.php
Normal file
393
westreiche_website/app/mailer.php
Normal file
|
|
@ -0,0 +1,393 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Westreiche – minimaler SMTP-Client (ohne Composer, ohne externe Dienste).
|
||||
*
|
||||
* Verschickt reine Text-Mails über den Hetzner-Mailserver: STARTTLS auf Port
|
||||
* 587 oder SSL auf 465, Anmeldung per AUTH PLAIN/LOGIN. Konfiguriert wird der
|
||||
* Abschnitt 'mail' in app/config.local.php; die Werte stammen aus MAIL_* in
|
||||
* credentials.txt (siehe tools/deploy_app.sh).
|
||||
*
|
||||
* Ist dort nichts hinterlegt, gilt der Versand als nicht eingerichtet:
|
||||
* mail_ready() liefert false, die App zeigt den Einladungslink wie bisher zum
|
||||
* Kopieren an.
|
||||
*/
|
||||
|
||||
/** SMTP-Mindestclient: EHLO/STARTTLS/AUTH/DATA, alles andere übernimmt der Aufrufer. */
|
||||
final class WsSmtp
|
||||
{
|
||||
/** @var resource|null */
|
||||
private $socket = null;
|
||||
|
||||
/** @var array<string,string> */
|
||||
private array $features = [];
|
||||
|
||||
private string $lastError = '';
|
||||
|
||||
public function __construct(
|
||||
private string $host,
|
||||
private int $port,
|
||||
private string $secure,
|
||||
private float $timeout = 15.0,
|
||||
) {
|
||||
}
|
||||
|
||||
public function connect(): void
|
||||
{
|
||||
$socket = $this->open($this->host);
|
||||
if ($socket === false) {
|
||||
// Manche Netze haben kein IPv6, der Name liefert aber eine AAAA-Adresse:
|
||||
// zweiter Versuch über die IPv4-Adresse, Zertifikat bleibt an den Namen gebunden.
|
||||
$ipv4 = gethostbyname($this->host);
|
||||
if ($ipv4 !== $this->host && filter_var($ipv4, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
|
||||
$socket = $this->open($ipv4);
|
||||
}
|
||||
}
|
||||
if ($socket === false) {
|
||||
throw new RuntimeException(sprintf('SMTP-Verbindung zu %s:%d fehlgeschlagen (%s)', $this->host, $this->port, $this->lastError !== '' ? $this->lastError : 'Grund unbekannt'));
|
||||
}
|
||||
stream_set_timeout($socket, (int) max(1, (int) ceil($this->timeout)));
|
||||
$this->socket = $socket;
|
||||
$this->expect(220);
|
||||
$this->ehlo();
|
||||
|
||||
if ($this->secure === 'tls') {
|
||||
if (!array_key_exists('starttls', $this->features)) {
|
||||
throw new RuntimeException('Server bietet kein STARTTLS an.');
|
||||
}
|
||||
$this->cmd('STARTTLS', 220);
|
||||
$ok = @stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
|
||||
if ($ok !== true) {
|
||||
throw new RuntimeException('TLS-Aushandlung fehlgeschlagen (Zertifikat oder Protokoll).');
|
||||
}
|
||||
$this->ehlo();
|
||||
}
|
||||
}
|
||||
|
||||
public function authenticate(string $user, string $password): void {
|
||||
$mechanisms = strtoupper($this->features['auth'] ?? '');
|
||||
if (str_contains($mechanisms, 'PLAIN')) {
|
||||
$this->cmd('AUTH PLAIN ' . base64_encode("\0" . $user . "\0" . $password), 235);
|
||||
return;
|
||||
}
|
||||
if (str_contains($mechanisms, 'LOGIN')) {
|
||||
$this->cmd('AUTH LOGIN', 334);
|
||||
$this->cmd(base64_encode($user), 334);
|
||||
$this->cmd(base64_encode($password), 235);
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException('Server bietet weder AUTH PLAIN noch AUTH LOGIN an.');
|
||||
}
|
||||
|
||||
public function sendMail(string $from, string $to, string $raw): void
|
||||
{
|
||||
$this->cmd('MAIL FROM:<' . $from . '>', 250);
|
||||
$this->cmd('RCPT TO:<' . $to . '>', 250);
|
||||
$this->cmd('DATA', 354);
|
||||
// Dot-Stuffing nach RFC 5321: eine Zeile, die mit "." beginnt, wird verdoppelt.
|
||||
$stuffed = preg_replace('/^\./m', '..', str_replace(["\r\n", "\r"], "\n", $raw));
|
||||
$this->writeRaw(str_replace("\n", "\r\n", (string) $stuffed) . "\r\n.\r\n");
|
||||
$this->expect(250);
|
||||
}
|
||||
|
||||
/** @return resource */
|
||||
private function context()
|
||||
{
|
||||
return stream_context_create(['ssl' => [
|
||||
'verify_peer' => true,
|
||||
'verify_peer_name' => true,
|
||||
'peer_name' => $this->host,
|
||||
'SNI_enabled' => true,
|
||||
'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
|
||||
]]);
|
||||
}
|
||||
|
||||
/** @return resource|false */
|
||||
private function open(string $target)
|
||||
{
|
||||
$scheme = $this->secure === 'ssl' ? 'ssl' : 'tcp';
|
||||
$errno = 0;
|
||||
$errstr = '';
|
||||
$socket = @stream_socket_client(
|
||||
$scheme . '://' . $target . ':' . $this->port,
|
||||
$errno,
|
||||
$errstr,
|
||||
$this->timeout,
|
||||
STREAM_CLIENT_CONNECT,
|
||||
$this->context()
|
||||
);
|
||||
if ($socket === false) {
|
||||
$this->lastError = $errstr !== '' ? $errstr : 'Fehler ' . $errno;
|
||||
return false;
|
||||
}
|
||||
return $socket;
|
||||
}
|
||||
|
||||
public function quit(): void
|
||||
{
|
||||
if ($this->socket === null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@fwrite($this->socket, "QUIT\r\n");
|
||||
} catch (Throwable) {
|
||||
// Abschluss ist nicht kritisch.
|
||||
}
|
||||
@fclose($this->socket);
|
||||
$this->socket = null;
|
||||
}
|
||||
|
||||
private function ehlo(): void
|
||||
{
|
||||
$name = gethostname();
|
||||
$response = $this->cmd('EHLO ' . ($name !== false && $name !== '' ? $name : 'localhost'), 250);
|
||||
$this->features = [];
|
||||
foreach (array_slice($response, 1) as $line) {
|
||||
$parts = preg_split('/[\s=]+/', trim($line), 2);
|
||||
if (!is_array($parts) || $parts[0] === '') {
|
||||
continue;
|
||||
}
|
||||
$this->features[strtolower($parts[0])] = $parts[1] ?? '';
|
||||
}
|
||||
if (!array_key_exists('auth', $this->features)) {
|
||||
// Manche Server liefern "AUTH=LOGIN PLAIN" – oben bereits normalisiert.
|
||||
$this->features['auth'] = $this->features['auth'] ?? '';
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<string> Antwortzeilen ohne Statuscode */
|
||||
private function cmd(string $line, int $expected): array
|
||||
{
|
||||
$this->writeRaw($line . "\r\n");
|
||||
return $this->expect($expected);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function expect(int $expected): array
|
||||
{
|
||||
[$code, $lines] = $this->read();
|
||||
if ($code !== $expected) {
|
||||
throw new RuntimeException(sprintf('SMTP-Dialog: Code %d statt %d (%s)', $code, $expected, implode(' ', $lines)));
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/** @return array{0:int,1:list<string>} */
|
||||
private function read(): array
|
||||
{
|
||||
if ($this->socket === null) {
|
||||
throw new RuntimeException('Keine SMTP-Verbindung.');
|
||||
}
|
||||
$lines = [];
|
||||
while (true) {
|
||||
$line = fgets($this->socket, 2048);
|
||||
if ($line === false) {
|
||||
throw new RuntimeException('SMTP-Antwort blieb aus (Zeitüberschreitung).');
|
||||
}
|
||||
$line = rtrim($line, "\r\n");
|
||||
if (preg_match('/^(\d{3})([ -])(.*)$/', $line, $m) !== 1) {
|
||||
throw new RuntimeException('Unerwartete SMTP-Antwort: ' . substr($line, 0, 80));
|
||||
}
|
||||
$lines[] = $m[3];
|
||||
if ($m[2] === ' ') {
|
||||
return [(int) $m[1], $lines];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function writeRaw(string $data): void
|
||||
{
|
||||
if ($this->socket === null) {
|
||||
throw new RuntimeException('Keine SMTP-Verbindung.');
|
||||
}
|
||||
$remaining = $data;
|
||||
while ($remaining !== '') {
|
||||
$written = @fwrite($this->socket, $remaining);
|
||||
if ($written === false || $written === 0) {
|
||||
throw new RuntimeException('Schreiben auf die SMTP-Verbindung fehlgeschlagen.');
|
||||
}
|
||||
$remaining = substr($remaining, $written);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
function mail_settings(): array
|
||||
{
|
||||
$mail = config('mail', []);
|
||||
return is_array($mail) ? $mail : [];
|
||||
}
|
||||
|
||||
/** Ist der Versand eingerichtet und vollständig konfiguriert? */
|
||||
function mail_ready(): bool
|
||||
{
|
||||
$settings = mail_settings();
|
||||
return trim((string) ($settings['host'] ?? '')) !== ''
|
||||
&& trim((string) ($settings['from'] ?? '')) !== ''
|
||||
&& trim((string) ($settings['user'] ?? '')) !== ''
|
||||
&& (string) ($settings['password'] ?? '') !== '';
|
||||
}
|
||||
|
||||
function mail_log(string $message): void
|
||||
{
|
||||
error_log('Westreiche-Mail: ' . $message);
|
||||
}
|
||||
|
||||
/** Kodiert einen Header-Wert als RFC-2047-Wort (mit Folding für lange Betreffs). */
|
||||
function mail_encode_header(string $value): string
|
||||
{
|
||||
if (preg_match('/^[\x20-\x7E]*$/', $value) === 1) {
|
||||
return $value;
|
||||
}
|
||||
$encoded = base64_encode($value);
|
||||
$words = str_split($encoded, 60);
|
||||
return implode("\r\n ", array_map(static fn (string $chunk): string => '=?UTF-8?B?' . $chunk . '?=', $words));
|
||||
}
|
||||
|
||||
function mail_display_name(string $name): string
|
||||
{
|
||||
if ($name === '') {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/^[\x20-\x7E]+$/', $name) === 1) {
|
||||
return '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], $name) . '"';
|
||||
}
|
||||
return mail_encode_header($name);
|
||||
}
|
||||
|
||||
/** Baut die vollständige Nachricht (Header + base64-Textkörper) mit CRLF-Zeilen. */
|
||||
function mail_build(string $from, string $fromName, string $to, string $subject, string $text): string
|
||||
{
|
||||
$address = (string) substr((string) strrchr($from, '@'), 1);
|
||||
$domain = $address !== '' ? $address : 'zauberturm.de';
|
||||
$name = mail_display_name($fromName);
|
||||
|
||||
$headers = [
|
||||
'Date: ' . date('r'),
|
||||
'From: ' . ($name !== '' ? $name . ' <' . $from . '>' : $from),
|
||||
'To: ' . $to,
|
||||
'Subject: ' . mail_encode_header($subject),
|
||||
'Message-ID: <' . bin2hex(random_bytes(12)) . '@' . $domain . '>',
|
||||
'MIME-Version: 1.0',
|
||||
'Content-Type: text/plain; charset=UTF-8',
|
||||
'Content-Transfer-Encoding: base64',
|
||||
'X-Mailer: Westreiche Charakterverwaltung',
|
||||
];
|
||||
|
||||
$normalized = str_replace(["\r\n", "\r"], "\n", $text);
|
||||
$body = rtrim(chunk_split(base64_encode($normalized), 76, "\r\n"), "\r\n");
|
||||
|
||||
return implode("\r\n", $headers) . "\r\n\r\n" . $body;
|
||||
}
|
||||
|
||||
/** Verschickt eine reine Textmail; wirft bei Fehlern RuntimeException. */
|
||||
function mail_send(string $to, string $subject, string $text): void
|
||||
{
|
||||
if (!mail_ready()) {
|
||||
throw new RuntimeException('Mailversand ist nicht eingerichtet.');
|
||||
}
|
||||
if (filter_var($to, FILTER_VALIDATE_EMAIL) === false) {
|
||||
throw new RuntimeException('Ungültige Empfängeradresse: ' . $to);
|
||||
}
|
||||
|
||||
$settings = mail_settings();
|
||||
$secure = strtolower(trim((string) ($settings['secure'] ?? 'tls')));
|
||||
if (!in_array($secure, ['tls', 'ssl'], true)) {
|
||||
$secure = 'tls';
|
||||
}
|
||||
$port = (int) ($settings['port'] ?? 0);
|
||||
$from = trim((string) $settings['from']);
|
||||
|
||||
$client = new WsSmtp(
|
||||
trim((string) $settings['host']),
|
||||
$port > 0 ? $port : ($secure === 'ssl' ? 465 : 587),
|
||||
$secure,
|
||||
(float) ($settings['timeout'] ?? 15)
|
||||
);
|
||||
|
||||
try {
|
||||
$client->connect();
|
||||
$client->authenticate(trim((string) $settings['user']), (string) $settings['password']);
|
||||
$client->sendMail(
|
||||
$from,
|
||||
$to,
|
||||
mail_build($from, trim((string) ($settings['from_name'] ?? '')), $to, $subject, $text)
|
||||
);
|
||||
} finally {
|
||||
$client->quit();
|
||||
}
|
||||
}
|
||||
|
||||
/** Text der Einladungsmail (auch für Passwort-Zurücksetzen passend). */
|
||||
function mail_invite_text(array $user, array $invite): string
|
||||
{
|
||||
$name = trim((string) ($user['display_name'] ?? ''));
|
||||
if ($name === '') {
|
||||
$name = trim((string) ($user['username'] ?? ''));
|
||||
}
|
||||
$salutation = $name !== '' ? 'Hallo ' . $name . ',' : 'Hallo,';
|
||||
|
||||
$base = rtrim((string) config('app.public_url', ''), '/');
|
||||
$path = rtrim((string) config('app.base_path', ''), '/');
|
||||
$start = $base . ($path !== '' && !str_ends_with($base, $path) ? $path : '');
|
||||
$expires = (new DateTimeImmutable((string) $invite['expires_at'], new DateTimeZone('UTC')))
|
||||
->setTimezone(new DateTimeZone('Europe/Berlin'))
|
||||
->format('d.m.Y H:i');
|
||||
|
||||
return implode("\n", [
|
||||
$salutation,
|
||||
'',
|
||||
'für dich gibt es einen Zugang zur Westreiche-Chronik, dem Charakterverwalter',
|
||||
'unserer Runde: ' . $start . '/',
|
||||
'',
|
||||
'Bitte vergib dein Passwort über diesen Link – er ist einmal verwendbar und',
|
||||
'gültig bis ' . $expires . ' Uhr:',
|
||||
'',
|
||||
$invite['url'],
|
||||
'',
|
||||
'Danach kannst du dich mit deinem Benutzernamen oder dieser Adresse anmelden.',
|
||||
'Wenn du nichts davon erwartest, ignoriere die Nachricht – ohne den Link',
|
||||
'lässt sich nichts ändern.',
|
||||
'',
|
||||
'Mögen die Sterne günstig stehen',
|
||||
'die Chronik der Zauberturm-Runde',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verschickt die Einladung, wenn möglich, und liefert den Status für die
|
||||
* Rückmeldung im Admin-Formular.
|
||||
*
|
||||
* @return array{sent:bool, to:string|null, reason:string}
|
||||
*/
|
||||
function mail_invite_result(array $user, array $invite): array
|
||||
{
|
||||
if (!mail_ready()) {
|
||||
return ['sent' => false, 'to' => null, 'reason' => 'not_configured'];
|
||||
}
|
||||
$to = trim((string) ($user['email'] ?? ''));
|
||||
if ($to === '') {
|
||||
return ['sent' => false, 'to' => null, 'reason' => 'no_address'];
|
||||
}
|
||||
try {
|
||||
mail_send($to, 'Dein Zugang zur Westreiche-Chronik', mail_invite_text($user, $invite));
|
||||
return ['sent' => true, 'to' => $to, 'reason' => 'ok'];
|
||||
} catch (Throwable $error) {
|
||||
mail_log('Einladung an ' . $to . ' fehlgeschlagen: ' . $error->getMessage());
|
||||
return ['sent' => false, 'to' => $to, 'reason' => 'error'];
|
||||
}
|
||||
}
|
||||
|
||||
/** Zusatz für die Flash-Meldung nach dem Erzeugen einer Einladung. */
|
||||
function mail_invite_note(array $result): string
|
||||
{
|
||||
if (($result['sent'] ?? false) === true) {
|
||||
return ' Einladung per E-Mail an ' . (string) $result['to'] . ' gesendet.';
|
||||
}
|
||||
return match ($result['reason'] ?? '') {
|
||||
'no_address' => ' Keine E-Mail-Adresse hinterlegt – Link bitte kopieren und weitergeben.',
|
||||
'error' => ' E-Mail-Versand fehlgeschlagen – Link bitte kopieren und weitergeben.',
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
57
westreiche_website/app/migrations.php
Normal file
57
westreiche_website/app/migrations.php
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Westreiche – Schema-Migrationen.
|
||||
*
|
||||
* Wird bei jedem Verbindungsaufbau (db()) einmal pro Request angewendet: Die
|
||||
* Tabelle schema_migrations merkt sich, was bereits gelaufen ist. Damit
|
||||
* erreichen Spalten-Erweiterungen auch Installationen, die vor der Änderung
|
||||
* angelegt wurden (der Installer läuft nur einmal).
|
||||
*
|
||||
* Regeln:
|
||||
* - Jede Migration bekommt eine neue, fortlaufende Version.
|
||||
* - Statements müssen in sich abgeschlossen und wiederholbar formuliert sein
|
||||
* (IF NOT EXISTS), damit ein abgebrochener Lauf nachholbar bleibt.
|
||||
* - Bestehende Einträge nie ändern – nur hinten anhängen.
|
||||
*/
|
||||
|
||||
const WS_MIGRATIONS = [
|
||||
// 1: Vollständiger Regeltext der Zauber für den Detail-Schirm im Bogen.
|
||||
1 => [
|
||||
'ALTER TABLE spells ADD COLUMN IF NOT EXISTS body LONGTEXT NULL AFTER summary',
|
||||
],
|
||||
];
|
||||
|
||||
function ws_migrations_apply(PDO $pdo): void
|
||||
{
|
||||
static $applied = false;
|
||||
if ($applied) {
|
||||
return;
|
||||
}
|
||||
$applied = true;
|
||||
|
||||
try {
|
||||
$pdo->exec(
|
||||
'CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INT UNSIGNED NOT NULL,
|
||||
applied_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
|
||||
);
|
||||
$done = array_map('intval', $pdo->query('SELECT version FROM schema_migrations')->fetchAll(PDO::FETCH_COLUMN));
|
||||
foreach (WS_MIGRATIONS as $version => $statements) {
|
||||
if (in_array((int) $version, $done, true)) {
|
||||
continue;
|
||||
}
|
||||
foreach ((array) $statements as $sql) {
|
||||
$pdo->exec($sql);
|
||||
}
|
||||
$pdo->prepare('INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)')
|
||||
->execute([(int) $version, gmdate('Y-m-d H:i:s')]);
|
||||
}
|
||||
} catch (Throwable $error) {
|
||||
// Migration darf die Seite nicht lahmlegen; Fehler landet im Log.
|
||||
error_log('Westreiche-Migration: ' . $error->getMessage());
|
||||
}
|
||||
}
|
||||
838
westreiche_website/app/pages.php
Normal file
838
westreiche_website/app/pages.php
Normal file
|
|
@ -0,0 +1,838 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Westreiche – Router und Controller aller Seiten. */
|
||||
|
||||
function render_page(string $template, array $vars, string $pageTitle): void
|
||||
{
|
||||
$user = auth_user();
|
||||
$file = WS_ROOT . '/views/' . $template . '.php';
|
||||
if (!is_file($file)) {
|
||||
throw new RuntimeException('View fehlt: ' . $template);
|
||||
}
|
||||
extract($vars, EXTR_SKIP);
|
||||
$title = $pageTitle;
|
||||
ob_start();
|
||||
require $file;
|
||||
$content = (string) ob_get_clean();
|
||||
require WS_ROOT . '/views/layout.php';
|
||||
}
|
||||
|
||||
function render_standalone(string $template, array $vars, string $pageTitle): void
|
||||
{
|
||||
$file = WS_ROOT . '/views/' . $template . '.php';
|
||||
extract($vars, EXTR_SKIP);
|
||||
$title = $pageTitle;
|
||||
require $file;
|
||||
}
|
||||
|
||||
function safe_next(string $candidate): string
|
||||
{
|
||||
if ($candidate === '' || $candidate[0] !== '/' || str_starts_with($candidate, '//')) {
|
||||
return '/';
|
||||
}
|
||||
return $candidate;
|
||||
}
|
||||
|
||||
function password_problem(string $password): string
|
||||
{
|
||||
if (mb_strlen($password, 'UTF-8') < 8) {
|
||||
return 'Das Passwort braucht mindestens 8 Zeichen.';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Router */
|
||||
|
||||
function page_handle(string $method, string $path): void
|
||||
{
|
||||
$path = '/' . trim($path, '/');
|
||||
if (!in_array($method, ['GET', 'POST'], true)) {
|
||||
abort_page(405, 'Methode nicht erlaubt.');
|
||||
}
|
||||
|
||||
if ($path === '/health') {
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo 'ok';
|
||||
return;
|
||||
}
|
||||
if ($path === '/login') {
|
||||
page_login($method);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/invite/([a-f0-9]{64})$#', $path, $m) === 1) {
|
||||
page_invite($method, $m[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
$user = auth_require_login();
|
||||
|
||||
if ($user['must_change_password'] === 1 && !in_array($path, ['/account', '/logout'], true)) {
|
||||
flash('info', 'Bitte zuerst ein eigenes Passwort setzen.');
|
||||
redirect('/account');
|
||||
}
|
||||
|
||||
if ($path === '/logout') {
|
||||
require_post();
|
||||
auth_logout();
|
||||
redirect('/login');
|
||||
}
|
||||
if ($path === '/account') {
|
||||
page_account($method, $user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/spells.json') {
|
||||
page_spells_json();
|
||||
return;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- Charaktere */
|
||||
if ($path === '/') {
|
||||
render_page('characters', ['characters' => characters_all($user)], 'Meine Charaktere');
|
||||
return;
|
||||
}
|
||||
if ($path === '/characters/new') {
|
||||
page_character_new($method, $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)$#', $path, $m) === 1) {
|
||||
page_character_sheet((int) $m[1], $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/edit$#', $path, $m) === 1) {
|
||||
page_character_edit($method, (int) $m[1], $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/pdf$#', $path, $m) === 1) {
|
||||
page_character_pdf((int) $m[1], $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/portrait(/delete)?$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
if (($m[2] ?? '') === '/delete') {
|
||||
portrait_remove((int) $character['id']);
|
||||
flash('info', 'Porträt entfernt – es gilt wieder das Platzhalterbild.');
|
||||
} else {
|
||||
$result = portrait_upload((int) $character['id'], $_FILES['portrait'] ?? []);
|
||||
$result['ok']
|
||||
? flash('success', 'Porträt gespeichert.')
|
||||
: flash('error', $result['error']);
|
||||
}
|
||||
redirect('/characters/' . $character['id'] . '/edit#portraet');
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/delete$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
if (!auth_can_manage($user) && (int) $character['user_id'] !== (int) $user['id']) {
|
||||
abort_page(403, 'Kein Zugriff.');
|
||||
}
|
||||
portrait_delete_file((string) $character['portrait']);
|
||||
character_delete((int) $character['id']);
|
||||
flash('info', '„' . $character['name'] . '“ wurde gelöscht.');
|
||||
redirect('/');
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/skills/(add|\d+/delete)$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
if ($m[2] === 'add') {
|
||||
$skillId = post_int('skill_id', 0);
|
||||
character_skill_add(
|
||||
(int) $character['id'],
|
||||
$skillId > 0 ? $skillId : null,
|
||||
post_string('name'),
|
||||
post_int('bonus', 0),
|
||||
post_string('note')
|
||||
);
|
||||
flash('success', 'Fertigkeit eingetragen.');
|
||||
} else {
|
||||
character_skill_delete((int) $character['id'], (int) explode('/', $m[2])[0]);
|
||||
flash('info', 'Fertigkeit entfernt.');
|
||||
}
|
||||
redirect('/characters/' . $character['id'] . '/edit#fertigkeiten');
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/skills/reset$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
$count = character_reset_skills((int) $character['id'], post_string('force') === '1');
|
||||
flash('success', $count . ' Fertigkeitswerte auf den Attributsstand gesetzt.');
|
||||
redirect('/characters/' . $character['id'] . '/edit#fertigkeiten');
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/skills/(\d+)$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
character_skill_update((int) $character['id'], (int) $m[2], post_int('bonus', 0), post_string('note'));
|
||||
flash('success', 'Fertigkeit gespeichert.');
|
||||
redirect('/characters/' . $character['id'] . '/edit#fertigkeiten');
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/weapons/(add|\d+(?:/(?:delete|toggle))?)$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
$action = $m[2];
|
||||
if ($action === 'add') {
|
||||
character_weapon_add((int) $character['id'], post_int('weapon_id', 0), [
|
||||
'name' => post_string('name'),
|
||||
'damage' => post_string('damage'),
|
||||
'attack_bonus' => post_int('attack_bonus', 0),
|
||||
'category' => post_string('category', 'Nahkampf'),
|
||||
'note' => post_string('note'),
|
||||
'equipped' => '1',
|
||||
]);
|
||||
flash('success', 'Waffe hinzugefügt.');
|
||||
} else {
|
||||
$parts = explode('/', $action);
|
||||
if (isset($parts[1]) && $parts[1] === 'delete') {
|
||||
character_weapon_delete((int) $character['id'], (int) $parts[0]);
|
||||
flash('info', 'Waffe entfernt.');
|
||||
} elseif (isset($parts[1]) && $parts[1] === 'toggle') {
|
||||
character_weapon_toggle((int) $character['id'], (int) $parts[0]);
|
||||
flash('info', 'Waffe in/aus der Hand genommen.');
|
||||
} else {
|
||||
character_weapon_update((int) $character['id'], (int) $parts[0], [
|
||||
'name' => post_string('name'),
|
||||
'damage' => post_string('damage'),
|
||||
'attack_bonus' => post_int('attack_bonus', 0),
|
||||
'category' => post_string('category', 'Nahkampf'),
|
||||
'note' => post_string('note'),
|
||||
'equipped' => post_string('equipped') === '1',
|
||||
]);
|
||||
flash('success', 'Waffe gespeichert.');
|
||||
}
|
||||
}
|
||||
redirect('/characters/' . $character['id'] . '/edit#bewaffnung');
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/armors/(add|\d+(?:/(?:delete|toggle))?)$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
$action = $m[2];
|
||||
if ($action === 'add') {
|
||||
character_armor_add((int) $character['id'], post_int('armor_id', 0), [
|
||||
'name' => post_string('name'),
|
||||
'ac_bonus' => post_string('ac_bonus'),
|
||||
'kind' => post_string('kind', 'Rüstung'),
|
||||
'note' => post_string('note'),
|
||||
'equipped' => '1',
|
||||
]);
|
||||
flash('success', 'Rüstungsteil hinzugefügt.');
|
||||
} else {
|
||||
$parts = explode('/', $action);
|
||||
if (isset($parts[1]) && $parts[1] === 'delete') {
|
||||
character_armor_delete((int) $character['id'], (int) $parts[0]);
|
||||
flash('info', 'Rüstungsteil entfernt.');
|
||||
} elseif (isset($parts[1]) && $parts[1] === 'toggle') {
|
||||
character_armor_toggle((int) $character['id'], (int) $parts[0]);
|
||||
flash('info', 'Angelegt/abgelegt.');
|
||||
} else {
|
||||
character_armor_update((int) $character['id'], (int) $parts[0], [
|
||||
'name' => post_string('name'),
|
||||
'ac_bonus' => post_int('ac_bonus', 0),
|
||||
'kind' => post_string('kind', 'Rüstung'),
|
||||
'note' => post_string('note'),
|
||||
'equipped' => post_string('equipped') === '1',
|
||||
]);
|
||||
flash('success', 'Rüstungsteil gespeichert.');
|
||||
}
|
||||
}
|
||||
redirect('/characters/' . $character['id'] . '/edit#ruestung');
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/spells/(add|\d+/delete)$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
if ($m[2] === 'add') {
|
||||
$spellId = post_int('spell_id', 0);
|
||||
character_spell_add(
|
||||
(int) $character['id'],
|
||||
$spellId > 0 ? $spellId : null,
|
||||
post_string('name'),
|
||||
post_string('school', 'arkan'),
|
||||
post_int('grade', 1),
|
||||
post_string('note')
|
||||
);
|
||||
flash('success', 'Zauber/Liturgie eingetragen.');
|
||||
} else {
|
||||
character_spell_delete((int) $character['id'], (int) explode('/', $m[2])[0]);
|
||||
flash('info', 'Zauber entfernt.');
|
||||
}
|
||||
redirect('/characters/' . $character['id'] . '/edit#zauber');
|
||||
}
|
||||
if (preg_match('#^/characters/(\d+)/items/(add|\d+/(?:delete|toggle))$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$character = character_require((int) $m[1], $user);
|
||||
if ($m[2] === 'add') {
|
||||
character_item_add((int) $character['id'], [
|
||||
'name' => post_string('name'),
|
||||
'qty' => post_int('qty', 1),
|
||||
'category' => post_string('category', 'Ausrüstung'),
|
||||
'weight' => post_string('weight'),
|
||||
'value' => post_string('value'),
|
||||
'equipped' => post_string('equipped') === '1',
|
||||
'note' => post_string('note'),
|
||||
]);
|
||||
flash('success', 'Gegenstand eingetragen.');
|
||||
} else {
|
||||
[$id, $action] = explode('/', $m[2]);
|
||||
if ($action === 'delete') {
|
||||
character_item_delete((int) $character['id'], (int) $id);
|
||||
flash('info', 'Gegenstand entfernt.');
|
||||
} else {
|
||||
character_item_toggle((int) $character['id'], (int) $id);
|
||||
flash('info', 'Ausgerüstet-Status umgeschaltet.');
|
||||
}
|
||||
}
|
||||
redirect('/characters/' . $character['id'] . '/edit#inventar');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ Admin */
|
||||
if ($path === '/admin/users') {
|
||||
page_admin_users($user);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/users/new') {
|
||||
page_admin_user_new($method, $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/users/(\d+)$#', $path, $m) === 1) {
|
||||
page_admin_user_edit($method, (int) $m[1], $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/users/(\d+)/invite$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
auth_require_admin();
|
||||
$invite = invite_provision((int) $m[1], (int) $user['id']);
|
||||
$invitee = auth_user_by_id((int) $m[1]);
|
||||
$mail = $invitee !== null
|
||||
? mail_invite_result($invitee, $invite)
|
||||
: ['sent' => false, 'to' => null, 'reason' => ''];
|
||||
$_SESSION['last_invite'] = [
|
||||
'user_id' => (int) $m[1],
|
||||
'url' => $invite['url'],
|
||||
'expires_at' => $invite['expires_at'],
|
||||
'sent' => (bool) $mail['sent'],
|
||||
'to' => $mail['to'],
|
||||
];
|
||||
flash('success', 'Neuer Einladungslink erzeugt – das alte Passwort ist ungültig.' . mail_invite_note($mail));
|
||||
redirect('/admin/users/' . (int) $m[1]);
|
||||
}
|
||||
if (preg_match('#^/admin/users/(\d+)/delete$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
$admin = auth_require_admin();
|
||||
$target = (int) $m[1];
|
||||
if ($target === (int) $admin['id']) {
|
||||
flash('error', 'Das eigene Konto kann nicht gelöscht werden.');
|
||||
redirect('/admin/users');
|
||||
}
|
||||
db()->prepare('DELETE FROM users WHERE id = ?')->execute([$target]);
|
||||
flash('info', 'Konto gelöscht.');
|
||||
redirect('/admin/users');
|
||||
}
|
||||
if ($path === '/admin/skills') {
|
||||
page_admin_skills($method, $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/admin/skills/(\d+)/delete$#', $path, $m) === 1) {
|
||||
require_post();
|
||||
auth_require_admin();
|
||||
skills_catalog_delete((int) $m[1]);
|
||||
flash('info', 'Fertigkeit aus dem Katalog entfernt.');
|
||||
redirect('/admin/skills');
|
||||
}
|
||||
if ($path === '/admin/equipment') {
|
||||
render_page('admin_equipment', [
|
||||
'weapons' => weapons_catalog(),
|
||||
'armors' => armors_catalog(),
|
||||
], 'Waffen & Rüstungen');
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/spells') {
|
||||
page_admin_spells($user);
|
||||
return;
|
||||
}
|
||||
|
||||
abort_page(404, 'Diese Seite gibt es nicht.');
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- Login */
|
||||
|
||||
function page_login(string $method): void
|
||||
{
|
||||
$error = '';
|
||||
$identifier = '';
|
||||
if ($method === 'POST') {
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} else {
|
||||
$identifier = post_string('identifier');
|
||||
$password = post_string('password');
|
||||
try {
|
||||
$user = auth_verify_login($identifier, $password);
|
||||
auth_login($user, post_string('remember') === '1');
|
||||
redirect(safe_next(post_string('next')));
|
||||
} catch (RuntimeException $e) {
|
||||
$error = match ($e->getMessage()) {
|
||||
'locked' => 'Zu viele Fehlversuche. Bitte in 15 Minuten erneut versuchen.',
|
||||
'disabled' => 'Dieses Konto ist deaktiviert. Bitte den Spielleiter fragen.',
|
||||
default => 'Benutzername bzw. E-Mail oder Passwort ist falsch.',
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
render_standalone('login', [
|
||||
'error' => $error,
|
||||
'identifier' => $identifier,
|
||||
'next' => query_string('next'),
|
||||
], 'Anmelden');
|
||||
}
|
||||
|
||||
function page_invite(string $method, string $token): void
|
||||
{
|
||||
$invite = invite_find($token);
|
||||
$error = '';
|
||||
if ($invite === null) {
|
||||
render_standalone('invite', ['invite' => null, 'error' => 'Dieser Einladungslink ist ungültig oder abgelaufen.', 'token' => ''], 'Einladung');
|
||||
return;
|
||||
}
|
||||
if ($method === 'POST') {
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} else {
|
||||
$password = post_string('password');
|
||||
$repeat = post_string('password_repeat');
|
||||
if (($problem = password_problem($password)) !== '') {
|
||||
$error = $problem;
|
||||
} elseif ($password !== $repeat) {
|
||||
$error = 'Die beiden Passwörter stimmen nicht überein.';
|
||||
} else {
|
||||
invite_redeem($token, $password);
|
||||
$user = auth_user_by_id((int) $invite['user_id']);
|
||||
if ($user !== null) {
|
||||
auth_login($user);
|
||||
}
|
||||
flash('success', 'Willkommen in der Westreiche, ' . $invite['username'] . '!');
|
||||
redirect('/');
|
||||
}
|
||||
}
|
||||
}
|
||||
render_standalone('invite', ['invite' => $invite, 'error' => $error, 'token' => $token], 'Einladung annehmen');
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Konto */
|
||||
|
||||
function page_account(string $method, array $user): void
|
||||
{
|
||||
$error = '';
|
||||
if ($method === 'POST') {
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} else {
|
||||
$action = post_string('action', 'password');
|
||||
if ($action === 'profile') {
|
||||
$displayName = shorten(post_string('display_name'), 120);
|
||||
$email = shorten(post_string('email'), 190);
|
||||
if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
$error = 'Diese E-Mail-Adresse sieht nicht gültig aus.';
|
||||
} elseif (auth_email_taken($email, (int) $user['id'])) {
|
||||
$error = 'Diese E-Mail-Adresse wird bereits verwendet.';
|
||||
} else {
|
||||
db()->prepare('UPDATE users SET display_name = ?, email = ?, updated_at = ? WHERE id = ?')
|
||||
->execute([$displayName, $email === '' ? null : $email, utc_now(), (int) $user['id']]);
|
||||
flash('success', 'Profil gespeichert.');
|
||||
redirect('/account');
|
||||
}
|
||||
} else {
|
||||
$current = post_string('current_password');
|
||||
$new = post_string('new_password');
|
||||
$repeat = post_string('new_password_repeat');
|
||||
if (!password_verify($current, (string) $user['password_hash'])) {
|
||||
$error = 'Das aktuelle Passwort stimmt nicht.';
|
||||
} elseif (($problem = password_problem($new)) !== '') {
|
||||
$error = $problem;
|
||||
} elseif ($new !== $repeat) {
|
||||
$error = 'Die beiden neuen Passwörter stimmen nicht überein.';
|
||||
} else {
|
||||
db()->prepare(
|
||||
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 0,
|
||||
auth_epoch = auth_epoch + 1, updated_at = ? WHERE id = ?'
|
||||
)->execute([hash_password($new), utc_now(), utc_now(), (int) $user['id']]);
|
||||
$fresh = auth_user_by_id((int) $user['id']);
|
||||
if ($fresh !== null) {
|
||||
auth_login($fresh);
|
||||
}
|
||||
flash('success', 'Passwort geändert.');
|
||||
redirect('/');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
render_page('account', ['error' => $error, 'account' => $user], 'Mein Konto');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ Charaktere */
|
||||
|
||||
function character_form_values(array $source): array
|
||||
{
|
||||
$values = [];
|
||||
foreach (array_merge(array_keys(WS_ATTRIBUTES), array_keys(WS_SAVES)) as $field) {
|
||||
$values[$field] = post_int($field, (int) ($source[$field] ?? 10));
|
||||
}
|
||||
$values['name'] = post_string('name', (string) ($source['name'] ?? ''));
|
||||
$values['title'] = post_string('title', (string) ($source['title'] ?? ''));
|
||||
$values['class_name'] = post_string('class_name', (string) ($source['class_name'] ?? 'Kämpfer'));
|
||||
$values['level'] = max(1, min(20, post_int('level', (int) ($source['level'] ?? 1))));
|
||||
$values['xp'] = max(0, post_int('xp', (int) ($source['xp'] ?? 0)));
|
||||
$values['hp_max'] = max(1, post_int('hp_max', (int) ($source['hp_max'] ?? 1)));
|
||||
$values['hp_current'] = post_int('hp_current', (int) ($source['hp_current'] ?? $values['hp_max']));
|
||||
$acRaw = post_string('ac', $source['ac'] === null ? '' : (string) $source['ac']);
|
||||
$values['ac'] = $acRaw === '' ? null : max(-10, min(30, (int) $acRaw));
|
||||
$values['attack_bonus'] = post_int('attack_bonus', (int) ($source['attack_bonus'] ?? 0));
|
||||
$values['gold_coins'] = post_int('gold_coins', (int) ($source['gold_coins'] ?? 0));
|
||||
$values['alignment'] = post_string('alignment', (string) ($source['alignment'] ?? ''));
|
||||
$values['deity'] = post_string('deity', (string) ($source['deity'] ?? ''));
|
||||
$values['age'] = post_string('age', (string) ($source['age'] ?? ''));
|
||||
$values['height'] = post_string('height', (string) ($source['height'] ?? ''));
|
||||
$values['weight'] = post_string('weight', (string) ($source['weight'] ?? ''));
|
||||
$values['appearance'] = post_string('appearance', (string) ($source['appearance'] ?? ''));
|
||||
$values['background'] = post_string('background', (string) ($source['background'] ?? ''));
|
||||
$values['notes'] = post_string('notes', (string) ($source['notes'] ?? ''));
|
||||
$values['status'] = post_string('status', (string) ($source['status'] ?? 'active'));
|
||||
if (!array_key_exists($values['status'], WS_CHARACTER_STATUS)) {
|
||||
$values['status'] = 'active';
|
||||
}
|
||||
if (!in_array($values['class_name'], WS_CLASSES, true)) {
|
||||
$values['class_name'] = 'Kämpfer';
|
||||
}
|
||||
foreach (WS_SAVES as $field => $label) {
|
||||
// Auf GET (Formular anzeigen) gilt der gespeicherte Wert; nur ein
|
||||
// tatsächlich abgeschicktes Feld überschreibt ihn.
|
||||
if (array_key_exists($field, $_POST) && is_string($_POST[$field])) {
|
||||
$raw = trim((string) $_POST[$field]);
|
||||
$values[$field] = $raw === '' ? null : max(-10, min(30, (int) $raw));
|
||||
} else {
|
||||
$stored = $source[$field] ?? null;
|
||||
$values[$field] = ($stored === null || $stored === '') ? null : (int) $stored;
|
||||
}
|
||||
}
|
||||
return $values;
|
||||
}
|
||||
|
||||
function page_character_new(string $method, array $user): void
|
||||
{
|
||||
$error = '';
|
||||
$values = character_form_values(['attr_str' => 14, 'attr_dex' => 12, 'attr_con' => 11, 'attr_int' => 10, 'attr_wis' => 9, 'attr_cha' => 7]);
|
||||
if ($method === 'POST') {
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} elseif ($values['name'] === '') {
|
||||
$error = 'Der Charakter braucht einen Namen.';
|
||||
} else {
|
||||
// Admin darf Charaktere für andere Konten anlegen.
|
||||
$ownerId = (int) $user['id'];
|
||||
if (auth_can_manage($user) && post_int('user_id', 0) > 0) {
|
||||
$ownerId = post_int('user_id');
|
||||
}
|
||||
$id = character_create($ownerId, $values);
|
||||
// Alles nachziehen, was das Anlegeformular schon kennt (Person,
|
||||
// Notizen). Die Rettungswürfe kommen aus der Klassentabelle und
|
||||
// dürfen nicht von leeren Formularfeldern überschrieben werden.
|
||||
character_update($id, array_merge($values, saving_throws_for($values['class_name'], (int) $values['level'])));
|
||||
flash('success', '„' . $values['name'] . '“ betritt die Westreiche.');
|
||||
redirect('/characters/' . $id . '/edit');
|
||||
}
|
||||
}
|
||||
render_page('character_form', [
|
||||
'character' => null,
|
||||
'values' => $values,
|
||||
'error' => $error,
|
||||
'owners' => auth_can_manage($user) ? db()->query('SELECT id, username FROM users ORDER BY username')->fetchAll() : [],
|
||||
], 'Neuer Charakter');
|
||||
}
|
||||
|
||||
function page_character_edit(string $method, int $id, array $user): void
|
||||
{
|
||||
$character = character_require($id, $user);
|
||||
$error = '';
|
||||
if ($method === 'POST') {
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} else {
|
||||
$values = character_form_values($character);
|
||||
if ($values['name'] === '') {
|
||||
$error = 'Der Charakter braucht einen Namen.';
|
||||
} else {
|
||||
character_update((int) $character['id'], $values);
|
||||
flash('success', 'Charakterbogen gespeichert.');
|
||||
redirect('/characters/' . $character['id'] . '/edit');
|
||||
}
|
||||
}
|
||||
}
|
||||
$character = character_require($id, $user);
|
||||
$armors = character_armors((int) $character['id']);
|
||||
render_page('character_edit', [
|
||||
'character' => $character,
|
||||
'weapons' => character_weapons((int) $character['id']),
|
||||
'armors' => $armors,
|
||||
'weaponCatalog' => weapons_catalog(),
|
||||
'armorCatalog' => armors_catalog(),
|
||||
'acInfo' => armor_class_total($character, $armors),
|
||||
'skills' => character_skills((int) $character['id']),
|
||||
'skillCatalog' => skills_catalog(),
|
||||
'spells' => character_spells((int) $character['id']),
|
||||
'spellCatalog' => db()->query('SELECT id, name, school, grade FROM spells ORDER BY school DESC, grade, name')->fetchAll(),
|
||||
'items' => character_items((int) $character['id']),
|
||||
], 'Bogen bearbeiten');
|
||||
}
|
||||
|
||||
function page_character_sheet(int $id, array $user): void
|
||||
{
|
||||
$character = character_require($id, $user);
|
||||
$armors = character_armors((int) $character['id']);
|
||||
render_page('character_sheet', [
|
||||
'character' => $character,
|
||||
'weapons' => character_weapons((int) $character['id']),
|
||||
'armors' => $armors,
|
||||
'acInfo' => armor_class_total($character, $armors),
|
||||
'derived' => character_derived($character),
|
||||
'skills' => character_skills((int) $character['id']),
|
||||
'spells' => character_spells((int) $character['id']),
|
||||
'items' => character_items((int) $character['id']),
|
||||
], (string) $character['name']);
|
||||
}
|
||||
|
||||
function page_character_pdf(int $id, array $user): void
|
||||
{
|
||||
$character = character_require($id, $user);
|
||||
$armors = character_armors((int) $character['id']);
|
||||
$pdf = character_pdf($character, [
|
||||
'weapons' => character_weapons((int) $character['id']),
|
||||
'armors' => $armors,
|
||||
'ac' => armor_class_total($character, $armors),
|
||||
'skills' => character_skills((int) $character['id']),
|
||||
'spells' => character_spells((int) $character['id']),
|
||||
'items' => character_items((int) $character['id']),
|
||||
]);
|
||||
$slug = preg_replace('/[^A-Za-z0-9]+/', '-', (string) $character['name']) ?: 'charakter';
|
||||
$slug = trim((string) $slug, '-');
|
||||
header('Content-Type: application/pdf');
|
||||
header('Content-Disposition: attachment; filename="Charakterbogen-' . $slug . '.pdf"');
|
||||
header('Content-Length: ' . strlen($pdf));
|
||||
echo $pdf;
|
||||
}
|
||||
|
||||
function page_spells_json(): void
|
||||
{
|
||||
auth_require_login();
|
||||
$school = query_string('school', 'arkan') === 'klerikal' ? 'klerikal' : 'arkan';
|
||||
$grade = query_int('grade', 0);
|
||||
$rows = spells_search($school, $grade, query_string('q'), 200);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode($rows, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- Admin */
|
||||
|
||||
function page_admin_users(array $user): void
|
||||
{
|
||||
auth_require_admin();
|
||||
render_page('admin_users', [
|
||||
'users' => db()->query(
|
||||
'SELECT u.*, (SELECT COUNT(*) FROM characters c WHERE c.user_id = u.id) AS character_count
|
||||
FROM users u ORDER BY u.role, u.username'
|
||||
)->fetchAll(),
|
||||
'lastInvite' => $_SESSION['last_invite'] ?? null,
|
||||
], 'Benutzer');
|
||||
}
|
||||
|
||||
function page_admin_user_new(string $method, array $user): void
|
||||
{
|
||||
$admin = auth_require_admin();
|
||||
$error = '';
|
||||
$values = [
|
||||
'username' => post_string('username'),
|
||||
'email' => post_string('email'),
|
||||
'display_name' => post_string('display_name'),
|
||||
'role' => post_string('role', 'user'),
|
||||
'password' => '',
|
||||
];
|
||||
$invite = null;
|
||||
if ($method === 'POST') {
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} else {
|
||||
$password = post_string('password');
|
||||
$sendInvite = post_string('send_invite') === '1';
|
||||
if ($values['username'] === '') {
|
||||
$error = 'Bitte einen Benutzernamen angeben.';
|
||||
} elseif (mb_strlen($values['username'], 'UTF-8') < 3) {
|
||||
$error = 'Der Benutzername braucht mindestens 3 Zeichen.';
|
||||
} elseif (auth_username_taken($values['username'])) {
|
||||
$error = 'Diesen Benutzernamen gibt es schon.';
|
||||
} elseif ($values['email'] !== '' && !filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$error = 'Diese E-Mail-Adresse sieht nicht gültig aus.';
|
||||
} elseif ($values['email'] !== '' && auth_email_taken($values['email'])) {
|
||||
$error = 'Diese E-Mail-Adresse wird bereits verwendet.';
|
||||
} elseif (!$sendInvite && ($problem = password_problem($password)) !== '') {
|
||||
$error = $problem;
|
||||
} else {
|
||||
if (!in_array($values['role'], ['admin', 'user'], true)) {
|
||||
$values['role'] = 'user';
|
||||
}
|
||||
$hash = hash_password($sendInvite ? bin2hex(random_bytes(24)) : $password);
|
||||
db()->prepare(
|
||||
'INSERT INTO users (username, email, display_name, password_hash, role, status,
|
||||
must_change_password, created_by, created_at, updated_at, password_changed_at)
|
||||
VALUES (?, ?, ?, ?, ?, \'active\', ?, ?, ?, ?, ?)'
|
||||
)->execute([
|
||||
$values['username'],
|
||||
$values['email'] === '' ? null : $values['email'],
|
||||
$values['display_name'],
|
||||
$hash,
|
||||
$values['role'],
|
||||
$sendInvite ? 1 : 0,
|
||||
(int) $admin['id'],
|
||||
utc_now(),
|
||||
utc_now(),
|
||||
utc_now(),
|
||||
]);
|
||||
$newId = (int) db()->lastInsertId();
|
||||
if ($sendInvite) {
|
||||
$created = invite_create($newId, (int) $admin['id']);
|
||||
$mail = mail_invite_result([
|
||||
'email' => $values['email'],
|
||||
'username' => $values['username'],
|
||||
'display_name' => $values['display_name'],
|
||||
], $created);
|
||||
$_SESSION['last_invite'] = [
|
||||
'user_id' => $newId,
|
||||
'url' => $created['url'],
|
||||
'expires_at' => $created['expires_at'],
|
||||
'sent' => (bool) $mail['sent'],
|
||||
'to' => $mail['to'],
|
||||
];
|
||||
flash('success', 'Konto angelegt – Einladungslink ist bereit.' . mail_invite_note($mail));
|
||||
} else {
|
||||
flash('success', 'Konto für ' . $values['username'] . ' angelegt.');
|
||||
}
|
||||
redirect('/admin/users/' . $newId);
|
||||
}
|
||||
}
|
||||
}
|
||||
render_page('admin_user_form', [
|
||||
'target' => null,
|
||||
'values' => $values,
|
||||
'error' => $error,
|
||||
'inviteUrl' => $invite,
|
||||
'lastInvite' => $_SESSION['last_invite'] ?? null,
|
||||
], 'Neues Konto');
|
||||
}
|
||||
|
||||
function page_admin_user_edit(string $method, int $id, array $user): void
|
||||
{
|
||||
$admin = auth_require_admin();
|
||||
$target = auth_user_by_id($id);
|
||||
if ($target === null) {
|
||||
abort_page(404, 'Dieses Konto gibt es nicht.');
|
||||
}
|
||||
$error = '';
|
||||
$values = [
|
||||
'username' => post_string('username', (string) $target['username']),
|
||||
'email' => post_string('email', (string) ($target['email'] ?? '')),
|
||||
'display_name' => post_string('display_name', (string) $target['display_name']),
|
||||
'role' => post_string('role', (string) $target['role']),
|
||||
'status' => post_string('status', (string) $target['status']),
|
||||
'password' => '',
|
||||
];
|
||||
if ($method === 'POST') {
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} else {
|
||||
$password = post_string('password');
|
||||
if ($values['username'] === '') {
|
||||
$error = 'Bitte einen Benutzernamen angeben.';
|
||||
} elseif (auth_username_taken($values['username'], $id)) {
|
||||
$error = 'Diesen Benutzernamen gibt es schon.';
|
||||
} elseif ($values['email'] !== '' && !filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
|
||||
$error = 'Diese E-Mail-Adresse sieht nicht gültig aus.';
|
||||
} elseif ($values['email'] !== '' && auth_email_taken($values['email'], $id)) {
|
||||
$error = 'Diese E-Mail-Adresse wird bereits verwendet.';
|
||||
} elseif ($password !== '' && ($problem = password_problem($password)) !== '') {
|
||||
$error = $problem;
|
||||
} elseif ((int) $admin['id'] === $id && ($values['role'] !== 'admin' || $values['status'] !== 'active')) {
|
||||
$error = 'Das eigene Konto darf nicht zum Benutzer oder deaktiviert werden.';
|
||||
} else {
|
||||
if (!in_array($values['role'], ['admin', 'user'], true)) {
|
||||
$values['role'] = 'user';
|
||||
}
|
||||
if (!in_array($values['status'], ['active', 'disabled'], true)) {
|
||||
$values['status'] = 'active';
|
||||
}
|
||||
db()->prepare(
|
||||
'UPDATE users SET username = ?, email = ?, display_name = ?, role = ?, status = ?, updated_at = ? WHERE id = ?'
|
||||
)->execute([
|
||||
$values['username'],
|
||||
$values['email'] === '' ? null : $values['email'],
|
||||
$values['display_name'],
|
||||
$values['role'],
|
||||
$values['status'],
|
||||
utc_now(),
|
||||
$id,
|
||||
]);
|
||||
if ($password !== '') {
|
||||
db()->prepare(
|
||||
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 0,
|
||||
auth_epoch = auth_epoch + 1 WHERE id = ?'
|
||||
)->execute([hash_password($password), utc_now(), $id]);
|
||||
}
|
||||
flash('success', 'Konto gespeichert.');
|
||||
redirect('/admin/users/' . $id);
|
||||
}
|
||||
}
|
||||
}
|
||||
$invite = invite_active_for_user($id);
|
||||
$last = $_SESSION['last_invite'] ?? null;
|
||||
render_page('admin_user_form', [
|
||||
'target' => $target,
|
||||
'values' => $values,
|
||||
'error' => $error,
|
||||
'activeInvite' => $invite,
|
||||
'lastInvite' => is_array($last) && (int) $last['user_id'] === $id ? $last : null,
|
||||
], 'Konto bearbeiten');
|
||||
}
|
||||
|
||||
function page_admin_skills(string $method, array $user): void
|
||||
{
|
||||
auth_require_admin();
|
||||
$error = '';
|
||||
if ($method === 'POST') {
|
||||
if (!csrf_valid()) {
|
||||
$error = 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.';
|
||||
} else {
|
||||
$name = shorten(post_string('name'), 80);
|
||||
$attribute = post_string('attribute');
|
||||
$category = post_string('category', 'Allgemein');
|
||||
if ($name === '') {
|
||||
$error = 'Bitte einen Namen angeben.';
|
||||
} elseif (!in_array($attribute, ['STR', 'DEX', 'CON', 'INT', 'WIS', 'CHA', ''], true)) {
|
||||
$attribute = '';
|
||||
} else {
|
||||
skills_catalog_add($name, $attribute, $category);
|
||||
flash('success', 'Fertigkeit „' . $name . '“ ergänzt.');
|
||||
redirect('/admin/skills');
|
||||
}
|
||||
}
|
||||
}
|
||||
render_page('admin_skills', [
|
||||
'skills' => skills_catalog(),
|
||||
'error' => $error,
|
||||
], 'Fertigkeiten-Katalog');
|
||||
}
|
||||
|
||||
function page_admin_spells(array $user): void
|
||||
{
|
||||
auth_require_admin();
|
||||
$school = query_string('school', 'arkan') === 'klerikal' ? 'klerikal' : 'arkan';
|
||||
render_page('admin_spells', [
|
||||
'school' => $school,
|
||||
'grade' => query_int('grade', 0),
|
||||
'needle' => query_string('q'),
|
||||
'spells' => spells_search($school, query_int('grade', 0), query_string('q'), 400),
|
||||
], 'Zauberkatalog');
|
||||
}
|
||||
303
westreiche_website/app/pdf.php
Normal file
303
westreiche_website/app/pdf.php
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Westreiche – PDF-Export des Charakterbogens.
|
||||
*
|
||||
* Bewusst ohne Fremdbibliothek: ein kleiner PDF-1.4-Writer mit den
|
||||
* Standard-Schriften (Helvetica/Times), Windows-1252-Kodierung und A4-Seiten.
|
||||
* Dadurch läuft der Export auf jedem Shared Hosting ohne Composer, GD oder
|
||||
* Python. Umlaute und ß sind in CP1252 enthalten; alles andere wird
|
||||
* transliteriert.
|
||||
*/
|
||||
final class WsPdf
|
||||
{
|
||||
private const PAGE_W = 595.28;
|
||||
private const PAGE_H = 841.89;
|
||||
|
||||
private const FONTS = [
|
||||
'F1' => 'Helvetica',
|
||||
'F2' => 'Helvetica-Bold',
|
||||
'F3' => 'Times-Roman',
|
||||
'F4' => 'Times-Bold',
|
||||
'F5' => 'Times-Italic',
|
||||
];
|
||||
|
||||
/** Grobe Zeichenbreite relativ zur Schriftgröße (reicht für Zeilenumbrüche). */
|
||||
private const WIDTH_FACTOR = ['F1' => 0.52, 'F2' => 0.57, 'F3' => 0.47, 'F4' => 0.52, 'F5' => 0.46];
|
||||
|
||||
/** @var list<array{bytes: string, w: int, h: int, name: string, object: int}> */
|
||||
private array $images = [];
|
||||
|
||||
/** @var list<string> */
|
||||
private array $pages = [];
|
||||
private string $buffer = '';
|
||||
private int $pageCount = 0;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->addPage();
|
||||
}
|
||||
|
||||
public static function width(): float
|
||||
{
|
||||
return self::PAGE_W;
|
||||
}
|
||||
|
||||
public static function height(): float
|
||||
{
|
||||
return self::PAGE_H;
|
||||
}
|
||||
|
||||
public function currentPage(): int
|
||||
{
|
||||
return $this->pageCount;
|
||||
}
|
||||
|
||||
public function addPage(): void
|
||||
{
|
||||
if ($this->buffer !== '') {
|
||||
$this->pages[] = $this->buffer;
|
||||
}
|
||||
$this->buffer = '';
|
||||
$this->pageCount++;
|
||||
}
|
||||
|
||||
private static function encode(string $text): string
|
||||
{
|
||||
$converted = @iconv('UTF-8', 'CP1252//TRANSLIT', $text);
|
||||
if ($converted === false) {
|
||||
$converted = preg_replace('/[^\x20-\x7e]/', '?', $text) ?? '';
|
||||
}
|
||||
return str_replace(['\\', '(', ')', "\r"], ['\\\\', '\\(', '\\)', ''], $converted);
|
||||
}
|
||||
|
||||
private static function color(array $rgb): string
|
||||
{
|
||||
return sprintf('%.3F %.3F %.3F', $rgb[0], $rgb[1], $rgb[2]);
|
||||
}
|
||||
|
||||
/** @param array{0:float,1:float,2:float} $rgb */
|
||||
public function text(float $x, float $yTop, float $size, string $font, array $rgb, string $text): void
|
||||
{
|
||||
if ($text === '') {
|
||||
return;
|
||||
}
|
||||
$this->buffer .= sprintf(
|
||||
"BT /%s %.2F Tf %s rg 1 0 0 1 %.2F %.2F Tm (%s) Tj ET\n",
|
||||
$font,
|
||||
$size,
|
||||
self::color($rgb),
|
||||
$x,
|
||||
self::PAGE_H - $yTop,
|
||||
self::encode($text)
|
||||
);
|
||||
}
|
||||
|
||||
public function textRight(float $xRight, float $yTop, float $size, string $font, array $rgb, string $text): void
|
||||
{
|
||||
$this->text($xRight - self::textWidth($text, $size, $font), $yTop, $size, $font, $rgb, $text);
|
||||
}
|
||||
|
||||
public function textCenter(float $centerX, float $yTop, float $size, string $font, array $rgb, string $text): void
|
||||
{
|
||||
$this->text($centerX - self::textWidth($text, $size, $font) / 2, $yTop, $size, $font, $rgb, $text);
|
||||
}
|
||||
|
||||
public static function textWidth(string $text, float $size, string $font = 'F3'): float
|
||||
{
|
||||
return mb_strlen($text, 'UTF-8') * $size * (self::WIDTH_FACTOR[$font] ?? 0.5);
|
||||
}
|
||||
|
||||
/** @param array{0:float,1:float,2:float} $rgb */
|
||||
public function line(float $x1, float $y1Top, float $x2, float $y2Top, array $rgb, float $lw = 0.6): void
|
||||
{
|
||||
$this->buffer .= sprintf(
|
||||
"q %s RG %.2F w %.2F %.2F m %.2F %.2F l S Q\n",
|
||||
self::color($rgb),
|
||||
$lw,
|
||||
$x1,
|
||||
self::PAGE_H - $y1Top,
|
||||
$x2,
|
||||
self::PAGE_H - $y2Top
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{0:float,1:float,2:float}|null $fill
|
||||
* @param array{0:float,1:float,2:float}|null $stroke
|
||||
*/
|
||||
public function rect(float $x, float $yTop, float $w, float $h, ?array $fill = null, ?array $stroke = null, float $lw = 0.6): void
|
||||
{
|
||||
$op = '';
|
||||
if ($fill !== null) {
|
||||
$op .= self::color($fill) . ' rg ';
|
||||
}
|
||||
if ($stroke !== null) {
|
||||
$op .= self::color($stroke) . ' RG ' . sprintf('%.2F w ', $lw);
|
||||
}
|
||||
$mode = ($fill !== null && $stroke !== null) ? 'B' : ($fill !== null ? 'f' : 'S');
|
||||
$this->buffer .= sprintf(
|
||||
"q %s%.2F %.2F %.2F %.2F re %s Q\n",
|
||||
$op,
|
||||
$x,
|
||||
self::PAGE_H - $yTop - $h,
|
||||
$w,
|
||||
$h,
|
||||
$mode
|
||||
);
|
||||
}
|
||||
|
||||
/** Zeilenumbruch nach geschätzter Breite. @return list<string> */
|
||||
public static function wrap(string $text, float $size, string $font, float $maxWidth): array
|
||||
{
|
||||
$text = trim(preg_replace('/\s+/u', ' ', $text) ?? '');
|
||||
if ($text === '') {
|
||||
return [];
|
||||
}
|
||||
$lines = [];
|
||||
$current = '';
|
||||
foreach (explode(' ', $text) as $word) {
|
||||
$candidate = $current === '' ? $word : $current . ' ' . $word;
|
||||
if (self::textWidth($candidate, $size, $font) <= $maxWidth || $current === '') {
|
||||
$current = $candidate;
|
||||
continue;
|
||||
}
|
||||
$lines[] = $current;
|
||||
$current = $word;
|
||||
}
|
||||
if ($current !== '') {
|
||||
$lines[] = $current;
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bettet ein JPEG ein (DCTDecode, keine Neukodierung nötig).
|
||||
*
|
||||
* @param string $source Dateipfad oder JPEG-Bytes
|
||||
*/
|
||||
public function imageJpeg(string $source, float $x, float $yTop, float $w, float $h, bool $isBytes = false): bool
|
||||
{
|
||||
$bytes = $isBytes ? $source : (is_file($source) ? (string) file_get_contents($source) : '');
|
||||
if ($bytes === '' || strncmp($bytes, "\xFF\xD8", 2) !== 0) {
|
||||
return false;
|
||||
}
|
||||
$size = getimagesizefromstring($bytes);
|
||||
if ($size === false) {
|
||||
return false;
|
||||
}
|
||||
$name = 'Im' . (count($this->images) + 1);
|
||||
$this->images[] = ['bytes' => $bytes, 'w' => (int) $size[0], 'h' => (int) $size[1], 'name' => $name, 'object' => 0];
|
||||
$this->buffer .= sprintf(
|
||||
"q %.2F 0 0 %.2F %.2F %.2F cm /%s Do Q\n",
|
||||
$w,
|
||||
$h,
|
||||
$x,
|
||||
self::PAGE_H - $yTop - $h,
|
||||
$name
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
public function output(): string
|
||||
{
|
||||
$pages = $this->pages;
|
||||
$pages[] = $this->buffer;
|
||||
|
||||
$objects = [];
|
||||
$fontIds = [];
|
||||
$nextFontObj = 3;
|
||||
foreach (self::FONTS as $key => $baseFont) {
|
||||
$fontIds[$key] = $nextFontObj++;
|
||||
$objects[$fontIds[$key]] = sprintf(
|
||||
'<< /Type /Font /Subtype /Type1 /BaseFont /%s /Encoding /WinAnsiEncoding >>',
|
||||
$baseFont
|
||||
);
|
||||
}
|
||||
|
||||
// Bilder als XObjects (JPEG, DCTDecode) – IDs nach den Schriften.
|
||||
$nextImageObj = $nextFontObj;
|
||||
foreach ($this->images as $index => $image) {
|
||||
$objectId = $nextImageObj + $index;
|
||||
$this->images[$index]['object'] = $objectId;
|
||||
$objects[$objectId] = sprintf(
|
||||
"<< /Type /XObject /Subtype /Image /Width %d /Height %d /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length %d >>\nstream\n%s\nendstream",
|
||||
$image['w'],
|
||||
$image['h'],
|
||||
strlen($image['bytes']),
|
||||
$image['bytes']
|
||||
);
|
||||
}
|
||||
$nextFontObj = $nextImageObj + count($this->images);
|
||||
|
||||
$imageRefs = '';
|
||||
foreach ($this->images as $image) {
|
||||
$imageRefs .= sprintf('/%s %d 0 R ', $image['name'], $image['object']);
|
||||
}
|
||||
|
||||
$pageObjStart = $nextFontObj;
|
||||
$pageIds = [];
|
||||
$pageCount = count($pages);
|
||||
for ($i = 0; $i < $pageCount; $i++) {
|
||||
$pageIds[] = $pageObjStart + $i * 2;
|
||||
}
|
||||
|
||||
$fontRefs = '';
|
||||
foreach ($fontIds as $key => $id) {
|
||||
$fontRefs .= sprintf('/%s %d 0 R ', $key, $id);
|
||||
}
|
||||
|
||||
foreach ($pages as $i => $content) {
|
||||
$pageId = $pageIds[$i];
|
||||
$contentId = $pageId + 1;
|
||||
$xObject = $imageRefs !== '' ? '/XObject << ' . $imageRefs . '>> ' : '';
|
||||
$objects[$pageId] = sprintf(
|
||||
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %.2F %.2F] /Resources << /Font << %s>> %s>> /Contents %d 0 R >>',
|
||||
self::PAGE_W,
|
||||
self::PAGE_H,
|
||||
$fontRefs,
|
||||
$xObject,
|
||||
$contentId
|
||||
);
|
||||
$objects[$contentId] = sprintf(
|
||||
"<< /Length %d >>\nstream\n%s\nendstream",
|
||||
strlen($content) + 1,
|
||||
$content
|
||||
);
|
||||
}
|
||||
|
||||
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
|
||||
$objects[2] = sprintf(
|
||||
'<< /Type /Pages /Count %d /Kids [%s] >>',
|
||||
$pageCount,
|
||||
implode(' ', array_map(static fn ($id) => $id . ' 0 R', $pageIds))
|
||||
);
|
||||
|
||||
ksort($objects);
|
||||
|
||||
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
|
||||
$offsets = [];
|
||||
foreach ($objects as $id => $body) {
|
||||
$offsets[$id] = strlen($pdf);
|
||||
$pdf .= sprintf("%d 0 obj\n%s\nendobj\n", $id, $body);
|
||||
}
|
||||
|
||||
$xrefPos = strlen($pdf);
|
||||
$maxObj = max(array_keys($objects));
|
||||
$pdf .= sprintf("xref\n0 %d\n", $maxObj + 1);
|
||||
$pdf .= "0000000000 65535 f \n";
|
||||
for ($id = 1; $id <= $maxObj; $id++) {
|
||||
$pdf .= isset($offsets[$id])
|
||||
? sprintf("%010d 00000 n \n", $offsets[$id])
|
||||
: "0000000000 65535 f \n";
|
||||
}
|
||||
$pdf .= sprintf(
|
||||
"trailer\n<< /Size %d /Root 1 0 R /Info << /Producer (Westreiche Charakterbogen) >> >>\nstartxref\n%d\n%%%%EOF\n",
|
||||
$maxObj + 1,
|
||||
$xrefPos
|
||||
);
|
||||
|
||||
return $pdf;
|
||||
}
|
||||
}
|
||||
177
westreiche_website/app/portrait.php
Normal file
177
westreiche_website/app/portrait.php
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Westreiche – Charakterporträts.
|
||||
*
|
||||
* Hochgeladene Bilder werden serverseitig über GD neu kodiert (JPEG, max.
|
||||
* 900 px Kantenlänge). Das entfernt Metadaten, verhindert eingeschleuste
|
||||
* Dateiinhalte und hält die Dateien klein. Ohne Upload greift ein gemaltes
|
||||
* Platzhalterporträt der jeweiligen Klasse aus assets/portraits/.
|
||||
*/
|
||||
|
||||
const WS_PORTRAIT_REL_DIR = 'uploads/portraits';
|
||||
const WS_PORTRAIT_MAX_BYTES = 5 * 1024 * 1024;
|
||||
const WS_PORTRAIT_MAX_EDGE = 900;
|
||||
|
||||
/** Dateiname-Stamm einer Klasse (Kämpfer → kaempfer). */
|
||||
function portrait_class_slug(string $className): string
|
||||
{
|
||||
$slug = mb_strtolower($className, 'UTF-8');
|
||||
$slug = str_replace(['ä', 'ö', 'ü', 'ß'], ['ae', 'oe', 'ue', 'ss'], $slug);
|
||||
$slug = preg_replace('/[^a-z0-9]+/', '-', $slug) ?? '';
|
||||
return trim($slug, '-');
|
||||
}
|
||||
|
||||
function portrait_dir(): string
|
||||
{
|
||||
return WS_ROOT . '/' . WS_PORTRAIT_REL_DIR;
|
||||
}
|
||||
|
||||
function portrait_placeholder_rel(string $className): string
|
||||
{
|
||||
$slug = portrait_class_slug($className);
|
||||
$rel = 'assets/portraits/' . $slug . '.webp';
|
||||
return is_file(WS_ROOT . '/' . $rel) ? $rel : '';
|
||||
}
|
||||
|
||||
/** Anzeige-URL: eigenes Bild, sonst Platzhalter der Klasse, sonst leer. */
|
||||
function portrait_url(array $character): string
|
||||
{
|
||||
$stored = (string) ($character['portrait'] ?? '');
|
||||
if ($stored !== '' && is_file(WS_ROOT . '/' . ltrim($stored, '/'))) {
|
||||
return url('/' . ltrim($stored, '/'));
|
||||
}
|
||||
$placeholder = portrait_placeholder_rel((string) ($character['class_name'] ?? ''));
|
||||
return $placeholder === '' ? '' : url('/' . $placeholder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nimmt ein hochgeladenes Bild an, kodiert es neu und speichert den Pfad.
|
||||
*
|
||||
* @param array{name?:string,type?:string,tmp_name?:string,error?:int,size?:int} $file
|
||||
* @return array{ok: bool, error: string}
|
||||
*/
|
||||
function portrait_upload(int $characterId, array $file): array
|
||||
{
|
||||
$error = (int) ($file['error'] ?? UPLOAD_ERR_NO_FILE);
|
||||
if ($error === UPLOAD_ERR_NO_FILE) {
|
||||
return ['ok' => false, 'error' => 'Bitte eine Bilddatei auswählen.'];
|
||||
}
|
||||
if ($error === UPLOAD_ERR_INI_SIZE || $error === UPLOAD_ERR_FORM_SIZE) {
|
||||
return ['ok' => false, 'error' => 'Das Bild ist zu groß (höchstens 5 MB).'];
|
||||
}
|
||||
if ($error !== UPLOAD_ERR_OK) {
|
||||
return ['ok' => false, 'error' => 'Der Upload ist fehlgeschlagen (Code ' . $error . ').'];
|
||||
}
|
||||
|
||||
$tmp = (string) ($file['tmp_name'] ?? '');
|
||||
if ($tmp === '' || !is_uploaded_file($tmp)) {
|
||||
return ['ok' => false, 'error' => 'Der Upload konnte nicht geprüft werden.'];
|
||||
}
|
||||
if ((int) ($file['size'] ?? 0) > WS_PORTRAIT_MAX_BYTES) {
|
||||
return ['ok' => false, 'error' => 'Das Bild ist zu groß (höchstens 5 MB).'];
|
||||
}
|
||||
if (!function_exists('imagecreatefromstring')) {
|
||||
return ['ok' => false, 'error' => 'Auf dem Server fehlt die GD-Erweiterung.'];
|
||||
}
|
||||
|
||||
$info = @getimagesize($tmp);
|
||||
if ($info === false || !in_array($info[2], [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP], true)) {
|
||||
return ['ok' => false, 'error' => 'Nur JPEG, PNG oder WebP werden angenommen.'];
|
||||
}
|
||||
|
||||
$image = @imagecreatefromstring((string) file_get_contents($tmp));
|
||||
if ($image === false) {
|
||||
return ['ok' => false, 'error' => 'Das Bild konnte nicht gelesen werden.'];
|
||||
}
|
||||
|
||||
$width = imagesx($image);
|
||||
$height = imagesy($image);
|
||||
$scale = min(1.0, WS_PORTRAIT_MAX_EDGE / max($width, $height));
|
||||
$newWidth = max(1, (int) round($width * $scale));
|
||||
$newHeight = max(1, (int) round($height * $scale));
|
||||
|
||||
$canvas = imagecreatetruecolor($newWidth, $newHeight);
|
||||
// JPEG kennt keine Transparenz – weißer Grund statt schwarzer Flächen.
|
||||
$white = imagecolorallocate($canvas, 250, 245, 230);
|
||||
imagefilledrectangle($canvas, 0, 0, $newWidth, $newHeight, $white);
|
||||
imagecopyresampled($canvas, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
|
||||
imagedestroy($image);
|
||||
|
||||
$dir = portrait_dir();
|
||||
if (!is_dir($dir) && !@mkdir($dir, 0755, true) && !is_dir($dir)) {
|
||||
imagedestroy($canvas);
|
||||
return ['ok' => false, 'error' => 'Der Bildordner konnte nicht angelegt werden.'];
|
||||
}
|
||||
|
||||
$fileName = sprintf('c%d-%s.jpg', $characterId, bin2hex(random_bytes(6)));
|
||||
$absolute = $dir . '/' . $fileName;
|
||||
$saved = imagejpeg($canvas, $absolute, 86);
|
||||
imagedestroy($canvas);
|
||||
|
||||
if (!$saved) {
|
||||
return ['ok' => false, 'error' => 'Das Bild konnte nicht gespeichert werden.'];
|
||||
}
|
||||
|
||||
portrait_delete_file((string) current_portrait((int) $characterId));
|
||||
db()->prepare('UPDATE characters SET portrait = ?, updated_at = ? WHERE id = ?')
|
||||
->execute([WS_PORTRAIT_REL_DIR . '/' . $fileName, utc_now(), $characterId]);
|
||||
|
||||
return ['ok' => true, 'error' => ''];
|
||||
}
|
||||
|
||||
function current_portrait(int $characterId): string
|
||||
{
|
||||
$stmt = db()->prepare('SELECT portrait FROM characters WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$characterId]);
|
||||
return (string) ($stmt->fetchColumn() ?: '');
|
||||
}
|
||||
|
||||
function portrait_remove(int $characterId): void
|
||||
{
|
||||
portrait_delete_file(current_portrait($characterId));
|
||||
db()->prepare('UPDATE characters SET portrait = \'\', updated_at = ? WHERE id = ?')
|
||||
->execute([utc_now(), $characterId]);
|
||||
}
|
||||
|
||||
function portrait_delete_file(string $relPath): void
|
||||
{
|
||||
$relPath = ltrim($relPath, '/');
|
||||
if ($relPath === '' || !str_starts_with($relPath, WS_PORTRAIT_REL_DIR . '/')) {
|
||||
return;
|
||||
}
|
||||
$absolute = WS_ROOT . '/' . $relPath;
|
||||
if (is_file($absolute)) {
|
||||
@unlink($absolute);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JPEG-Bytes für den PDF-Export: eigenes Bild direkt, Platzhalter (WebP)
|
||||
* wird über GD in JPEG umgewandelt.
|
||||
*/
|
||||
function portrait_jpeg_bytes(array $character): string
|
||||
{
|
||||
$stored = (string) ($character['portrait'] ?? '');
|
||||
if ($stored !== '' && is_file(WS_ROOT . '/' . ltrim($stored, '/'))) {
|
||||
$bytes = (string) file_get_contents(WS_ROOT . '/' . ltrim($stored, '/'));
|
||||
if (strncmp($bytes, "\xFF\xD8", 2) === 0) {
|
||||
return $bytes;
|
||||
}
|
||||
}
|
||||
|
||||
$placeholder = portrait_placeholder_rel((string) ($character['class_name'] ?? ''));
|
||||
if ($placeholder === '' || !function_exists('imagecreatefromwebp')) {
|
||||
return '';
|
||||
}
|
||||
$image = @imagecreatefromwebp(WS_ROOT . '/' . $placeholder);
|
||||
if ($image === false) {
|
||||
return '';
|
||||
}
|
||||
ob_start();
|
||||
imagejpeg($image, null, 88);
|
||||
$bytes = (string) ob_get_clean();
|
||||
imagedestroy($image);
|
||||
return $bytes;
|
||||
}
|
||||
249
westreiche_website/app/rules.php
Normal file
249
westreiche_website/app/rules.php
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Westreiche – Regelkonstanten (Hausregeln V1.1, OSE-alike). */
|
||||
|
||||
const WS_ATTRIBUTES = [
|
||||
'attr_str' => ['STR', 'Stärke'],
|
||||
'attr_dex' => ['DEX', 'Geschicklichkeit'],
|
||||
'attr_con' => ['CON', 'Konstitution'],
|
||||
'attr_int' => ['INT', 'Intelligenz'],
|
||||
'attr_wis' => ['WIS', 'Weisheit'],
|
||||
'attr_cha' => ['CHA', 'Charisma'],
|
||||
];
|
||||
|
||||
const WS_CLASSES = [
|
||||
'Kämpfer', 'Ritter', 'Paladin', 'Barbar', 'Waldläufer',
|
||||
'Dieb', 'Assassine', 'Barde',
|
||||
'Magier', 'Illusionist', 'Kleriker', 'Druide',
|
||||
];
|
||||
|
||||
const WS_SAVES = [
|
||||
'save_death' => 'Tod & Gift',
|
||||
'save_wand' => 'Zauberstäbe',
|
||||
'save_paralysis' => 'Lähmung',
|
||||
'save_breath' => 'Atemwaffen',
|
||||
'save_spell' => 'Zauber',
|
||||
];
|
||||
|
||||
const WS_ALIGNMENTS = ['Rechtschaffen', 'Neutral', 'Chaotisch', 'Gut', 'Böse', '–'];
|
||||
|
||||
const WS_ITEM_CATEGORIES = ['Waffe', 'Rüstung', 'Schild', 'Ausrüstung', 'Verbrauch', 'Schatz', 'Sonstiges'];
|
||||
|
||||
/**
|
||||
* Fertigkeitengruppen wie auf dem Westreiche-Charakterbogen
|
||||
* (RPG/6-Dokumente/Charakterbogen.pdf): KÖRPER, WILDNIS, SOZIAL, WISSEN.
|
||||
*/
|
||||
const WS_SKILL_GROUPS = ['Körper', 'Wildnis', 'Sozial', 'Wissen'];
|
||||
const WS_SKILL_CATEGORIES = WS_SKILL_GROUPS;
|
||||
|
||||
/**
|
||||
* Offizieller Fertigkeitenkatalog des Charakterbogens:
|
||||
* Name => [Attribut, Gruppe]. Startwert ist der Attributsbonus.
|
||||
*/
|
||||
const WS_SKILL_CATALOG = [
|
||||
'Ausdauer' => ['CON', 'Körper'],
|
||||
'Balancieren' => ['DEX', 'Körper'],
|
||||
'Fliegen' => ['DEX', 'Körper'],
|
||||
'Klettern' => ['STR', 'Körper'],
|
||||
'Reiten & Wagenführung' => ['DEX', 'Körper'],
|
||||
'Schleichen' => ['DEX', 'Körper'],
|
||||
'Schwimmen' => ['CON', 'Körper'],
|
||||
'Wahrnehmung' => ['WIS', 'Körper'],
|
||||
|
||||
'Wildniskunde' => ['WIS', 'Wildnis'],
|
||||
'Nahrung finden' => ['WIS', 'Wildnis'],
|
||||
'Navigation' => ['WIS', 'Wildnis'],
|
||||
'Orientierung' => ['INT', 'Wildnis'],
|
||||
'Pflanzenkunde' => ['INT', 'Wildnis'],
|
||||
'Segeln + Schiffahrt' => ['INT', 'Wildnis'],
|
||||
'Seilkunde' => ['DEX', 'Wildnis'],
|
||||
'Spurenlesen' => ['WIS', 'Wildnis'],
|
||||
|
||||
'Anführen' => ['CHA', 'Sozial'],
|
||||
'Aufführung' => ['CHA', 'Sozial'],
|
||||
'Einschüchtern' => ['STR', 'Sozial'],
|
||||
'Etikette' => ['CHA', 'Sozial'],
|
||||
'Handeln & Schätzen' => ['WIS', 'Sozial'],
|
||||
'Überzeugen' => ['CHA', 'Sozial'],
|
||||
'Verstellen' => ['INT', 'Sozial'],
|
||||
|
||||
'Alchimie' => ['INT', 'Wissen'],
|
||||
'Geschichts + Sagenkunde' => ['INT', 'Wissen'],
|
||||
'Handwerk' => ['DEX', 'Wissen'],
|
||||
'Heilkunde: Geist' => ['WIS', 'Wissen'],
|
||||
'Heilkunde: Gift' => ['INT', 'Wissen'],
|
||||
'Heilkunde: Krankheiten' => ['INT', 'Wissen'],
|
||||
'Heilkunde: Wunden' => ['WIS', 'Wissen'],
|
||||
'Religionskunde' => ['INT', 'Wissen'],
|
||||
'Verwaltung' => ['INT', 'Wissen'],
|
||||
'Zauberkunde' => ['INT', 'Wissen'],
|
||||
];
|
||||
|
||||
const WS_CHARACTER_STATUS = [
|
||||
'active' => 'im Spiel',
|
||||
'dead' => 'gefallen',
|
||||
'retired' => 'im Ruhestand',
|
||||
];
|
||||
|
||||
/**
|
||||
* Attributsbonus nach Hausregel V1.1:
|
||||
* 3 → −3, 4–5 → −2, 6–8 → −1, 9–12 → 0, 13–15 → +1, 16–17 → +2, 18 → +3.
|
||||
* Werte über 18 werden wie 18 behandelt.
|
||||
*/
|
||||
function attribute_bonus(int $value): int
|
||||
{
|
||||
return match (true) {
|
||||
$value <= 3 => -3,
|
||||
$value <= 5 => -2,
|
||||
$value <= 8 => -1,
|
||||
$value <= 12 => 0,
|
||||
$value <= 15 => 1,
|
||||
$value <= 17 => 2,
|
||||
default => 3,
|
||||
};
|
||||
}
|
||||
|
||||
function signed(int $value): string
|
||||
{
|
||||
return $value > 0 ? '+' . $value : (string) $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* CSS-Klasse für einen Bonus: positive Werte grün, Null grau, negative rot.
|
||||
*/
|
||||
function bonus_class(int $value): string
|
||||
{
|
||||
return $value > 0 ? 'bonus-pos' : ($value < 0 ? 'bonus-neg' : 'bonus-zero');
|
||||
}
|
||||
|
||||
/** Rettungswurf-Feld formatieren; leere Werte bleiben ein Gedankenstrich. */
|
||||
function save_display(mixed $value): string
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return '–';
|
||||
}
|
||||
return (string) (int) $value;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- Rettungswürfe */
|
||||
|
||||
/**
|
||||
* Rettungswurf-Grundwerte je Klasse und Stufe (Würfelwurf ≥ Wert, OSE-SRD).
|
||||
*
|
||||
* Aufbau: Klassenname → Liste aus [bis Stufe, [Tod & Gift, Zauberstäbe,
|
||||
* Lähmung, Atemwaffen, Zauber]]. Der erste Eintrag, dessen Stufengrenze
|
||||
* erreicht ist, gilt. Die Westreiche-Klassen ohne eigene Tabelle laufen auf
|
||||
* der passenden Grundklasse: Kämpfer, Ritter, Paladin, Barbar und Waldläufer
|
||||
* auf der Kämpfer-Tabelle, Druide auf der Kleriker-, Assassine und Barde auf
|
||||
* der Diebes-Tabelle.
|
||||
*/
|
||||
const WS_SAVE_TABLES = [
|
||||
'Kämpfer' => [
|
||||
[3, [12, 13, 14, 15, 16]],
|
||||
[6, [10, 11, 12, 13, 14]],
|
||||
[9, [8, 9, 10, 11, 12]],
|
||||
[12, [6, 7, 8, 9, 10]],
|
||||
[99, [4, 5, 6, 7, 8]],
|
||||
],
|
||||
'Kleriker' => [
|
||||
[3, [11, 12, 14, 16, 15]],
|
||||
[6, [9, 10, 12, 14, 13]],
|
||||
[9, [6, 7, 9, 11, 10]],
|
||||
[12, [3, 5, 7, 8, 8]],
|
||||
[99, [2, 3, 5, 6, 6]],
|
||||
],
|
||||
'Magier' => [
|
||||
[5, [13, 14, 13, 16, 15]],
|
||||
[10, [11, 12, 11, 14, 12]],
|
||||
[99, [8, 9, 8, 11, 8]],
|
||||
],
|
||||
'Dieb' => [
|
||||
[4, [13, 14, 13, 16, 15]],
|
||||
[8, [12, 13, 11, 14, 13]],
|
||||
[12, [11, 10, 9, 12, 10]],
|
||||
[99, [9, 8, 7, 10, 8]],
|
||||
],
|
||||
];
|
||||
|
||||
/** Klasse → Grundklasse für Rettungswürfe. */
|
||||
const WS_SAVE_BASE_CLASS = [
|
||||
'Ritter' => 'Kämpfer',
|
||||
'Paladin' => 'Kämpfer',
|
||||
'Barbar' => 'Kämpfer',
|
||||
'Waldläufer' => 'Kämpfer',
|
||||
'Druide' => 'Kleriker',
|
||||
'Illusionist' => 'Magier',
|
||||
'Assassine' => 'Dieb',
|
||||
'Barde' => 'Dieb',
|
||||
];
|
||||
|
||||
/** Rettungswürfe für Klasse + Stufe als Feld → Wert. */
|
||||
function saving_throws_for(string $className, int $level): array
|
||||
{
|
||||
$base = WS_SAVE_BASE_CLASS[$className] ?? $className;
|
||||
$table = WS_SAVE_TABLES[$base] ?? WS_SAVE_TABLES['Kämpfer'];
|
||||
$level = max(1, $level);
|
||||
$values = $table[count($table) - 1][1];
|
||||
foreach ($table as [$maxLevel, $row]) {
|
||||
if ($level <= $maxLevel) {
|
||||
$values = $row;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$fields = array_keys(WS_SAVES);
|
||||
$result = [];
|
||||
foreach ($fields as $index => $field) {
|
||||
$result[$field] = $values[$index];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/* ----------------------------------------- Waffen und Rüstungen (Ableitung) */
|
||||
|
||||
/** Trefferwurf mit einer Waffe: Grundangriff + Attributsbonus + Waffenbonus. */
|
||||
function weapon_attack_total(array $character, array $weapon): int
|
||||
{
|
||||
$attribute = ($weapon['category'] ?? 'Nahkampf') === 'Fernkampf' ? 'attr_dex' : 'attr_str';
|
||||
return (int) ($character['attack_bonus'] ?? 0)
|
||||
+ attribute_bonus((int) ($character[$attribute] ?? 10))
|
||||
+ (int) ($weapon['attack_bonus'] ?? 0);
|
||||
}
|
||||
|
||||
/** Schaden mit Waffe: Würfelausdruck + Attributsbonus (bei Fernkampf Geschick). */
|
||||
function weapon_damage_total(array $character, array $weapon): string
|
||||
{
|
||||
$damage = trim((string) ($weapon['damage'] ?? ''));
|
||||
if ($damage === '') {
|
||||
return '–';
|
||||
}
|
||||
$attribute = ($weapon['category'] ?? 'Nahkampf') === 'Fernkampf' ? 'attr_dex' : 'attr_str';
|
||||
$bonus = attribute_bonus((int) ($character[$attribute] ?? 10));
|
||||
return $bonus === 0 ? $damage : $damage . signed($bonus);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rüstungsklasse: 10 + Geschicklichkeitsbonus + alle angelegten Rüstungsteile.
|
||||
* Ein manueller Wert in characters.ac (nicht NULL) überschreibt das.
|
||||
*/
|
||||
function armor_class_total(array $character, array $armors): array
|
||||
{
|
||||
$dexterity = attribute_bonus((int) ($character['attr_dex'] ?? 10));
|
||||
$armorBonus = 0;
|
||||
foreach ($armors as $armor) {
|
||||
if ((int) ($armor['equipped'] ?? 0) === 1) {
|
||||
$armorBonus += (int) ($armor['ac_bonus'] ?? 0);
|
||||
}
|
||||
}
|
||||
$derived = 10 + $dexterity + $armorBonus;
|
||||
$manual = $character['ac'] ?? null;
|
||||
$isManual = $manual !== null && $manual !== '' && (int) $manual > 0;
|
||||
return [
|
||||
'derived' => $derived,
|
||||
'manual' => $isManual ? (int) $manual : null,
|
||||
'total' => $isManual ? (int) $manual : $derived,
|
||||
'dexterity' => $dexterity,
|
||||
'armor' => $armorBonus,
|
||||
'manual_active' => $isManual,
|
||||
];
|
||||
}
|
||||
373
westreiche_website/app/sheet.php
Normal file
373
westreiche_website/app/sheet.php
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Westreiche – Zeichnet den Charakterbogen als PDF (A4, Pergament-Optik mit
|
||||
* Gold-Rahmen). Quelle sind die Datensätze aus characters/character_*.
|
||||
*/
|
||||
|
||||
/** @return array{0:float,1:float,2:float} */
|
||||
function pdf_color(string $hex): array
|
||||
{
|
||||
$hex = ltrim($hex, '#');
|
||||
return [
|
||||
hexdec(substr($hex, 0, 2)) / 255,
|
||||
hexdec(substr($hex, 2, 2)) / 255,
|
||||
hexdec(substr($hex, 4, 2)) / 255,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut den kompletten Charakterbogen.
|
||||
*
|
||||
* @param array $c Charakterdatensatz
|
||||
* @param array $extra ['skills' => [...], 'spells' => ['arkan'=>[], 'klerikal'=>[]], 'items' => [...]]
|
||||
*/
|
||||
function character_pdf(array $c, array $extra): string
|
||||
{
|
||||
$ink = pdf_color('#1a1712');
|
||||
$soft = pdf_color('#4a4336');
|
||||
$gold = pdf_color('#a8862a');
|
||||
$goldLight = pdf_color('#d9be6a');
|
||||
$parchment = pdf_color('#faf5e6');
|
||||
$parchment2 = pdf_color('#f2e9d2');
|
||||
|
||||
$pdf = new WsPdf();
|
||||
$W = WsPdf::width();
|
||||
$H = WsPdf::height();
|
||||
$M = 34.0;
|
||||
$inner = $W - 2 * $M;
|
||||
|
||||
$pageNo = 0;
|
||||
$y = 0.0;
|
||||
|
||||
$frame = static function (WsPdf $pdf, int $pageNo) use ($W, $H, $M, $gold, $goldLight, $parchment, $parchment2, $ink, $soft): void {
|
||||
$pdf->rect(0, 0, $W, $H, $parchment);
|
||||
$pdf->rect(0, 0, $W, 16, $parchment2);
|
||||
$pdf->rect(0, $H - 16, $W, 16, $parchment2);
|
||||
$pdf->rect($M - 12, 18, $W - 2 * ($M - 12), $H - 36, null, $gold, 1.2);
|
||||
$pdf->rect($M - 8, 22, $W - 2 * ($M - 8), $H - 44, null, $goldLight, 0.4);
|
||||
|
||||
// Ecken-Ornamente
|
||||
foreach ([[$M - 12, 18], [$W - $M + 12 - 14, 18], [$M - 12, $H - 32], [$W - $M + 12 - 14, $H - 32]] as [$cx, $cy]) {
|
||||
$pdf->rect($cx, $cy, 14, 14, $gold);
|
||||
}
|
||||
|
||||
$pdf->textCenter($W / 2, $H - 22, 7.5, 'F1', $soft, 'Westreiche · Chronik der Zauberturm-Runde · zauberturm.de');
|
||||
$pdf->textRight($W - $M, $H - 40, 7.5, 'F1', $soft, 'Seite ' . $pageNo);
|
||||
};
|
||||
|
||||
$newPage = static function () use (&$pageNo, &$y, $pdf, $frame): void {
|
||||
if ($pageNo > 0) {
|
||||
$pdf->addPage();
|
||||
}
|
||||
$pageNo++;
|
||||
$frame($pdf, $pageNo);
|
||||
$y = 52.0;
|
||||
};
|
||||
|
||||
$newPage();
|
||||
|
||||
$ensure = static function (float $needed) use (&$y, $newPage, $H): void {
|
||||
if ($y + $needed > $H - 70) {
|
||||
$newPage();
|
||||
}
|
||||
};
|
||||
|
||||
$sectionTitle = static function (string $label) use (&$y, $pdf, $gold, $ink, $ensure, $M, $inner): void {
|
||||
$ensure(34);
|
||||
$y += 12;
|
||||
$pdf->rect($M, $y, 3.2, 10, $gold);
|
||||
$pdf->text($M + 8, $y + 9, 11.5, 'F4', $ink, mb_strtoupper($label, 'UTF-8'));
|
||||
$pdf->line($M, $y + 14, $M + $inner, $y + 14, $gold, 0.4);
|
||||
$y += 22;
|
||||
};
|
||||
|
||||
$paragraph = static function (string $text, float $size = 8.6) use (&$y, $pdf, $ink, $ensure, $M, $inner): void {
|
||||
if (trim($text) === '') {
|
||||
return;
|
||||
}
|
||||
foreach (preg_split('/\R{2,}/', trim($text)) ?: [] as $block) {
|
||||
foreach (WsPdf::wrap(str_replace("\n", ' ', $block), $size, 'F3', $inner) as $line) {
|
||||
$ensure(12);
|
||||
$pdf->text($M, $y + 9, $size, 'F3', $ink, $line);
|
||||
$y += 11.4;
|
||||
}
|
||||
$y += 3;
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------- Kopf */
|
||||
$portraitW = 74.0;
|
||||
$portraitH = 94.0;
|
||||
$pX = $W - $M - $portraitW;
|
||||
$textRight = $pX - 12;
|
||||
|
||||
$pdf->text($M, $y, 7.5, 'F2', $gold, 'CHARAKTERBOGEN');
|
||||
$nameSize = 24.0;
|
||||
$nameText = (string) $c['name'];
|
||||
while ($nameText !== '' && WsPdf::textWidth($nameText, $nameSize, 'F4') > $textRight - $M) {
|
||||
$nameText = mb_substr($nameText, 0, -1, 'UTF-8');
|
||||
}
|
||||
if ($nameText !== (string) $c['name']) {
|
||||
$nameText = rtrim($nameText) . '…';
|
||||
}
|
||||
$pdf->text($M, $y + 30, $nameSize, 'F4', $ink, $nameText);
|
||||
$titleLine = [];
|
||||
if ((string) $c['title'] !== '') {
|
||||
$titleLine[] = (string) $c['title'];
|
||||
}
|
||||
$titleLine[] = (string) $c['class_name'];
|
||||
$titleLine[] = 'Stufe ' . (int) $c['level'];
|
||||
if ((string) $c['alignment'] !== '' && (string) $c['alignment'] !== '–') {
|
||||
$titleLine[] = 'Gesinnung: ' . (string) $c['alignment'];
|
||||
}
|
||||
$titleLine[] = character_status_label((string) $c['status']);
|
||||
$titleText = implode(' · ', $titleLine);
|
||||
while ($titleText !== '' && WsPdf::textWidth($titleText, 9.6, 'F5') > $textRight - $M) {
|
||||
$titleText = mb_substr($titleText, 0, -1, 'UTF-8');
|
||||
}
|
||||
$pdf->text($M, $y + 46, 9.6, 'F5', $soft, $titleText);
|
||||
|
||||
// Porträt rechts (sonst Monogramm)
|
||||
$pH = $y + 2;
|
||||
$portraitBytes = portrait_jpeg_bytes($c);
|
||||
if ($portraitBytes === '' || !$pdf->imageJpeg($portraitBytes, $pX, $pH, $portraitW, $portraitH, true)) {
|
||||
$cgX = $W - $M - 26;
|
||||
$cgY = $y + 26;
|
||||
$pdf->rect($cgX - 26, $cgY - 26, 52, 52, null, $gold, 1.0);
|
||||
$pdf->rect($cgX - 22, $cgY - 22, 44, 44, null, $goldLight, 0.4);
|
||||
$pdf->textCenter($cgX, $cgY + 8, 20, 'F4', $gold, mb_strtoupper(mb_substr((string) $c['name'], 0, 1), 'UTF-8'));
|
||||
}
|
||||
$pdf->rect($pX - 2.5, $pH - 2.5, $portraitW + 5, $portraitH + 5, null, $gold, 1.0);
|
||||
|
||||
$y += 78;
|
||||
|
||||
/* ---------------------------------------------------------- Attribute */
|
||||
$sectionTitle('Attribute');
|
||||
$boxW = 60.0;
|
||||
$boxH = 54.0;
|
||||
$gap = 6.0;
|
||||
$x = $M;
|
||||
foreach (WS_ATTRIBUTES as $field => [$short, $label]) {
|
||||
$value = (int) ($c[$field] ?? 10);
|
||||
$pdf->rect($x, $y, $boxW, $boxH, $parchment2, $gold, 0.5);
|
||||
$pdf->textCenter($x + $boxW / 2, $y + 13, 7.2, 'F2', $soft, $short);
|
||||
$pdf->textCenter($x + $boxW / 2, $y + 34, 17, 'F4', $ink, (string) $value);
|
||||
$pdf->textCenter($x + $boxW / 2, $y + 46, 8, 'F2', $gold, signed(attribute_bonus($value)));
|
||||
$x += $boxW + $gap;
|
||||
}
|
||||
|
||||
// Kampfblock rechts
|
||||
$combatX = $x + 4;
|
||||
$combatW = $W - $M - $combatX;
|
||||
$pdf->rect($combatX, $y, $combatW, $boxH, null, $gold, 0.6);
|
||||
$combatRows = [
|
||||
['Trefferpunkte', (int) $c['hp_current'] . ' / ' . (int) $c['hp_max']],
|
||||
['Rüstungsklasse', (string) (int) ($extra['ac']['total'] ?? 10)],
|
||||
['Angriff', signed((int) $c['attack_bonus'])],
|
||||
['Gold', (int) $c['gold_coins'] . ' GM'],
|
||||
];
|
||||
$ry = $y + 12;
|
||||
$rowStep = 12.0;
|
||||
foreach ($combatRows as $i => [$label, $value]) {
|
||||
$pdf->text($combatX + 7, $ry, 7.0, 'F1', $soft, $label);
|
||||
$pdf->textRight($combatX + $combatW - 7, $ry, 9, 'F2', $ink, $value);
|
||||
$ry += $rowStep;
|
||||
}
|
||||
$y += $boxH + 6;
|
||||
|
||||
/* ----------------------------------------------------- Rettungswürfe */
|
||||
$saves = [];
|
||||
foreach (WS_SAVES as $field => $label) {
|
||||
$saves[$label] = save_display($c[$field] ?? null);
|
||||
}
|
||||
$sectionTitle('Rettungswürfe');
|
||||
$sw = ($inner - 4 * 5) / 5;
|
||||
$sx = $M;
|
||||
foreach ($saves as $label => $value) {
|
||||
$pdf->rect($sx, $y, $sw, 32, $parchment2, $gold, 0.4);
|
||||
$pdf->textCenter($sx + $sw / 2, $y + 12, 6.8, 'F1', $soft, $label);
|
||||
$pdf->textCenter($sx + $sw / 2, $y + 27, 13, 'F4', $ink, $value);
|
||||
$sx += $sw + 5;
|
||||
}
|
||||
$y += 38;
|
||||
|
||||
/* ------------------------------------------------- Bewaffnung / Rüstung */
|
||||
$weapons = $extra['weapons'] ?? [];
|
||||
if ($weapons !== []) {
|
||||
$sectionTitle('Bewaffnung');
|
||||
$ensure(14);
|
||||
$pdf->text($M, $y + 8, 6.8, 'F2', $soft, 'WAFFE');
|
||||
$pdf->text($M + 200, $y + 8, 6.8, 'F2', $soft, 'ART');
|
||||
$pdf->textRight($M + $inner - 74, $y + 8, 6.8, 'F2', $soft, 'TREFFER');
|
||||
$pdf->textRight($M + $inner, $y + 8, 6.8, 'F2', $soft, 'SCHADEN');
|
||||
$y += 12;
|
||||
$pdf->line($M, $y, $M + $inner, $y, $gold, 0.4);
|
||||
$y += 4;
|
||||
foreach ($weapons as $weapon) {
|
||||
$ensure(13);
|
||||
$pdf->text($M, $y + 8.5, 8.6, 'F3', $ink, shorten((string) $weapon['name'], 40));
|
||||
$pdf->text($M + 200, $y + 8.5, 7.6, 'F1', $soft, (string) $weapon['category']);
|
||||
$pdf->textRight($M + $inner - 74, $y + 8.5, 8.6, 'F2', $ink, signed(weapon_attack_total($c, $weapon)));
|
||||
$pdf->textRight($M + $inner, $y + 8.5, 8.6, 'F3', $ink, weapon_damage_total($c, $weapon));
|
||||
$pdf->line($M, $y + 10.8, $M + $inner, $y + 10.8, $goldLight, 0.22);
|
||||
$y += 13;
|
||||
}
|
||||
$y += 4;
|
||||
}
|
||||
|
||||
$armors = $extra['armors'] ?? [];
|
||||
if ($armors !== []) {
|
||||
$sectionTitle('Rüstung');
|
||||
$ensure(14);
|
||||
$pdf->text($M, $y + 8, 6.8, 'F2', $soft, 'TEIL');
|
||||
$pdf->text($M + 200, $y + 8, 6.8, 'F2', $soft, 'ART');
|
||||
$pdf->textRight($M + $inner - 60, $y + 8, 6.8, 'F2', $soft, 'RK-BONUS');
|
||||
$pdf->textRight($M + $inner, $y + 8, 6.8, 'F2', $soft, 'STATUS');
|
||||
$y += 12;
|
||||
$pdf->line($M, $y, $M + $inner, $y, $gold, 0.4);
|
||||
$y += 4;
|
||||
foreach ($armors as $armor) {
|
||||
$ensure(13);
|
||||
$pdf->text($M, $y + 8.5, 8.6, 'F3', $ink, shorten((string) $armor['name'], 40));
|
||||
$pdf->text($M + 200, $y + 8.5, 7.6, 'F1', $soft, (string) $armor['kind']);
|
||||
$pdf->textRight($M + $inner - 60, $y + 8.5, 8.6, 'F2', $ink, signed((int) $armor['ac_bonus']));
|
||||
$pdf->textRight($M + $inner, $y + 8.5, 7.6, 'F1', $soft, (int) $armor['equipped'] === 1 ? 'angelegt' : 'abgelegt');
|
||||
$pdf->line($M, $y + 10.8, $M + $inner, $y + 10.8, $goldLight, 0.22);
|
||||
$y += 13;
|
||||
}
|
||||
$acInfo = $extra['ac'] ?? null;
|
||||
if (is_array($acInfo)) {
|
||||
$ensure(14);
|
||||
$pdf->text($M, $y + 9, 8.2, 'F5', $soft, sprintf(
|
||||
'Rüstungsklasse gesamt: 10 %s Geschick %s Rüstung = %d%s',
|
||||
signed((int) $acInfo['dexterity']),
|
||||
signed((int) $acInfo['armor']),
|
||||
(int) $acInfo['total'],
|
||||
$acInfo['manual_active'] ? ' (manuell überschrieben)' : ''
|
||||
));
|
||||
$y += 14;
|
||||
}
|
||||
$y += 2;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- Fertigkeiten */
|
||||
$skills = $extra['skills'] ?? [];
|
||||
if ($skills !== []) {
|
||||
$sectionTitle('Fertigkeiten');
|
||||
foreach (skills_grouped($skills) as $group => $rows) {
|
||||
$ensure(26);
|
||||
$pdf->text($M, $y + 9, 7.0, 'F2', $gold, mb_strtoupper($group, 'UTF-8'));
|
||||
$pdf->line($M, $y + 12.5, $M + $inner, $y + 12.5, $goldLight, 0.3);
|
||||
$y += 15;
|
||||
$colW = ($inner - 16) / 2;
|
||||
$perColumn = (int) ceil(count($rows) / 2);
|
||||
for ($i = 0; $i < $perColumn; $i++) {
|
||||
$ensure(13);
|
||||
foreach ([0, 1] as $col) {
|
||||
$index = $i + $col * $perColumn;
|
||||
if (!isset($rows[$index])) {
|
||||
continue;
|
||||
}
|
||||
$skill = $rows[$index];
|
||||
$cx = $M + $col * ($colW + 16);
|
||||
$mod = skill_attribute_modifier($c, $skill);
|
||||
$pdf->text($cx, $y + 8.5, 8.4, 'F3', $ink, shorten((string) $skill['name'], 34));
|
||||
$pdf->text($cx + $colW - 64, $y + 8.2, 6.6, 'F1', $soft, trim((string) ($skill['attribute'] ?? '')));
|
||||
$pdf->textRight($cx + $colW - 28, $y + 8.2, 6.8, 'F1', $soft, $mod === null ? '–' : signed($mod));
|
||||
$pdf->textRight($cx + $colW, $y + 8.5, 8.4, 'F2', $gold, signed((int) $skill['bonus']));
|
||||
$pdf->line($cx, $y + 10.4, $cx + $colW, $y + 10.4, $goldLight, 0.22);
|
||||
}
|
||||
$y += 12.6;
|
||||
}
|
||||
$y += 4;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- Zauber & Liturgien */
|
||||
$spells = $extra['spells'] ?? ['arkan' => [], 'klerikal' => []];
|
||||
$spellBlocks = [
|
||||
'arkan' => ['Arkane Zauber', $spells['arkan'] ?? []],
|
||||
'klerikal' => ['Göttliche Liturgien', $spells['klerikal'] ?? []],
|
||||
];
|
||||
foreach ($spellBlocks as $key => [$label, $list]) {
|
||||
if ($list === []) {
|
||||
continue;
|
||||
}
|
||||
$sectionTitle($label);
|
||||
$byGrade = [];
|
||||
foreach ($list as $spell) {
|
||||
$byGrade[(int) $spell['grade']][] = $spell;
|
||||
}
|
||||
ksort($byGrade);
|
||||
foreach ($byGrade as $grade => $entries) {
|
||||
$names = [];
|
||||
foreach ($entries as $entry) {
|
||||
$names[] = (string) $entry['name'];
|
||||
}
|
||||
foreach (WsPdf::wrap('Grad ' . $grade . ': ' . implode(', ', $names), 8.6, 'F3', $inner - 6) as $i => $line) {
|
||||
$ensure(12);
|
||||
if ($i === 0) {
|
||||
$pdf->text($M, $y + 8.5, 8.6, 'F2', $gold, '');
|
||||
}
|
||||
$pdf->text($M + 2, $y + 8.5, 8.6, 'F3', $ink, $line);
|
||||
$y += 11.6;
|
||||
}
|
||||
$y += 2;
|
||||
}
|
||||
$y += 2;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- Inventar */
|
||||
$items = $extra['items'] ?? [];
|
||||
if ($items !== []) {
|
||||
$sectionTitle('Inventar');
|
||||
$pdf->text($M, $y + 8, 6.8, 'F2', $soft, 'ANZAHL');
|
||||
$pdf->text($M + 52, $y + 8, 6.8, 'F2', $soft, 'GEGENSTAND');
|
||||
$pdf->text($M + $inner - 78, $y + 8, 6.8, 'F2', $soft, 'ART');
|
||||
$pdf->textRight($M + $inner, $y + 8, 6.8, 'F2', $soft, 'WERT');
|
||||
$y += 12;
|
||||
$pdf->line($M, $y, $M + $inner, $y, $gold, 0.4);
|
||||
$y += 4;
|
||||
foreach ($items as $item) {
|
||||
$ensure(12);
|
||||
$pdf->text($M, $y + 8, 8.4, 'F1', $ink, ((int) $item['qty']) . '×');
|
||||
$pdf->text($M + 52, $y + 8, 8.6, 'F3', $ink, shorten((string) $item['name'], 56));
|
||||
$pdf->text($M + $inner - 78, $y + 8, 7.4, 'F1', $soft, (string) $item['category']);
|
||||
$pdf->textRight($M + $inner, $y + 8, 8.2, 'F3', $ink, (string) ($item['value'] !== '' ? $item['value'] : '–'));
|
||||
$pdf->line($M, $y + 10.4, $M + $inner, $y + 10.4, $goldLight, 0.22);
|
||||
$y += 12.6;
|
||||
}
|
||||
$y += 4;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ Person & Notizen */
|
||||
$facts = [];
|
||||
if ((string) $c['deity'] !== '') {
|
||||
$facts[] = 'Gottheit: ' . $c['deity'];
|
||||
}
|
||||
if ((string) $c['age'] !== '') {
|
||||
$facts[] = 'Alter: ' . $c['age'];
|
||||
}
|
||||
if ((string) $c['height'] !== '') {
|
||||
$facts[] = 'Größe: ' . $c['height'];
|
||||
}
|
||||
if ((string) $c['weight'] !== '') {
|
||||
$facts[] = 'Gewicht: ' . $c['weight'];
|
||||
}
|
||||
if ($facts !== []) {
|
||||
$sectionTitle('Person');
|
||||
$paragraph(implode(' · ', $facts), 9);
|
||||
}
|
||||
|
||||
foreach (['appearance' => 'Erscheinung', 'background' => 'Hintergrund', 'notes' => 'Notizen'] as $field => $label) {
|
||||
if (trim((string) $c[$field]) === '') {
|
||||
continue;
|
||||
}
|
||||
$sectionTitle($label);
|
||||
$paragraph((string) $c[$field]);
|
||||
}
|
||||
|
||||
return $pdf->output();
|
||||
}
|
||||
217
westreiche_website/app/util.php
Normal file
217
westreiche_website/app/util.php
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Westreiche – Basis: Konfiguration, Session, CSRF, Ausgabe, Zeit. */
|
||||
|
||||
function config(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$value = $GLOBALS['ws_config'] ?? [];
|
||||
foreach (explode('.', $key) as $part) {
|
||||
if (!is_array($value) || !array_key_exists($part, $value)) {
|
||||
return $default;
|
||||
}
|
||||
$value = $value[$part];
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function is_https(): bool
|
||||
{
|
||||
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
|
||||
return true;
|
||||
}
|
||||
return strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
|
||||
}
|
||||
|
||||
function security_headers(): void
|
||||
{
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('X-Frame-Options: DENY');
|
||||
header('X-Robots-Tag: noindex, nofollow, noarchive');
|
||||
header('Referrer-Policy: same-origin');
|
||||
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
|
||||
header(
|
||||
"Content-Security-Policy: default-src 'self'; img-src 'self' data:; "
|
||||
. "font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; "
|
||||
. "connect-src 'self'; media-src 'self'; form-action 'self'; "
|
||||
. "frame-ancestors 'none'; base-uri 'none'"
|
||||
);
|
||||
header('Cache-Control: no-store');
|
||||
if (is_https()) {
|
||||
header('Strict-Transport-Security: max-age=15552000');
|
||||
}
|
||||
}
|
||||
|
||||
function start_session(): void
|
||||
{
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
return;
|
||||
}
|
||||
$absolute = (int) config('app.session_absolute_seconds', 7776000);
|
||||
ini_set('session.use_strict_mode', '1');
|
||||
ini_set('session.use_only_cookies', '1');
|
||||
ini_set('session.cookie_httponly', '1');
|
||||
ini_set('session.cookie_samesite', 'Lax');
|
||||
ini_set('session.cookie_secure', is_https() ? '1' : '0');
|
||||
ini_set('session.cookie_path', '/');
|
||||
ini_set('session.gc_maxlifetime', (string) $absolute);
|
||||
session_name('WESTREICHE_SESSION');
|
||||
session_start();
|
||||
}
|
||||
|
||||
function utc_now(): string
|
||||
{
|
||||
return gmdate('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
function utc_after(int $seconds): string
|
||||
{
|
||||
return gmdate('Y-m-d H:i:s', time() + $seconds);
|
||||
}
|
||||
|
||||
function now_local(): string
|
||||
{
|
||||
return (new DateTimeImmutable('now', new DateTimeZone('Europe/Berlin')))->format('d.m.Y H:i');
|
||||
}
|
||||
|
||||
function e(mixed $value): string
|
||||
{
|
||||
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
|
||||
function url(string $path = '/'): string
|
||||
{
|
||||
$base = rtrim((string) config('app.base_path', ''), '/');
|
||||
if ($path === '' || $path[0] !== '/') {
|
||||
$path = '/' . $path;
|
||||
}
|
||||
return $base . $path;
|
||||
}
|
||||
|
||||
/** Cache-Buster: bei Änderungen an app.css/app.js erhöhen. */
|
||||
const WS_ASSET_VERSION = '5';
|
||||
|
||||
function asset(string $path): string
|
||||
{
|
||||
return url('/assets/' . ltrim($path, '/')) . '?v=' . WS_ASSET_VERSION;
|
||||
}
|
||||
|
||||
function redirect(string $path, int $status = 303): never
|
||||
{
|
||||
header('Location: ' . url($path), true, $status);
|
||||
exit;
|
||||
}
|
||||
|
||||
function current_path(): string
|
||||
{
|
||||
$path = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
|
||||
$base = rtrim((string) config('app.base_path', ''), '/');
|
||||
if ($base !== '' && str_starts_with($path, $base)) {
|
||||
$path = substr($path, strlen($base));
|
||||
}
|
||||
return '/' . trim($path, '/');
|
||||
}
|
||||
|
||||
function client_ip(): string
|
||||
{
|
||||
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
|
||||
return $ip !== '' ? substr($ip, 0, 45) : '0.0.0.0';
|
||||
}
|
||||
|
||||
function request_method(): string
|
||||
{
|
||||
return strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
|
||||
}
|
||||
|
||||
function is_post(): bool
|
||||
{
|
||||
return request_method() === 'POST';
|
||||
}
|
||||
|
||||
function post_string(string $key, string $default = ''): string
|
||||
{
|
||||
$value = $_POST[$key] ?? $default;
|
||||
return is_string($value) ? trim($value) : $default;
|
||||
}
|
||||
|
||||
function post_int(string $key, int $default = 0): int
|
||||
{
|
||||
$value = $_POST[$key] ?? null;
|
||||
if (is_int($value)) {
|
||||
return $value;
|
||||
}
|
||||
return is_string($value) && preg_match('/^-?\d+$/', trim($value)) === 1 ? (int) $value : $default;
|
||||
}
|
||||
|
||||
function query_string(string $key, string $default = ''): string
|
||||
{
|
||||
$value = $_GET[$key] ?? $default;
|
||||
return is_string($value) ? trim($value) : $default;
|
||||
}
|
||||
|
||||
function query_int(string $key, int $default = 0): int
|
||||
{
|
||||
$value = $_GET[$key] ?? null;
|
||||
return is_numeric($value) ? (int) $value : $default;
|
||||
}
|
||||
|
||||
function flash(string $type, string $message): void
|
||||
{
|
||||
$_SESSION['flash'][] = ['type' => $type, 'message' => $message];
|
||||
}
|
||||
|
||||
function flash_pull(): array
|
||||
{
|
||||
$items = $_SESSION['flash'] ?? [];
|
||||
unset($_SESSION['flash']);
|
||||
return is_array($items) ? $items : [];
|
||||
}
|
||||
|
||||
function csrf_token(): string
|
||||
{
|
||||
if (empty($_SESSION['csrf'])) {
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
return (string) $_SESSION['csrf'];
|
||||
}
|
||||
|
||||
function csrf_field(): string
|
||||
{
|
||||
return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
|
||||
}
|
||||
|
||||
function csrf_valid(): bool
|
||||
{
|
||||
$sent = $_POST['_csrf'] ?? '';
|
||||
return is_string($sent) && $sent !== '' && hash_equals(csrf_token(), $sent);
|
||||
}
|
||||
|
||||
function require_post(): void
|
||||
{
|
||||
if (!is_post()) {
|
||||
abort_page(405, 'Diese Aktion erfordert ein Formular.');
|
||||
}
|
||||
if (!csrf_valid()) {
|
||||
abort_page(419, 'Die Sitzung ist abgelaufen. Bitte erneut versuchen.');
|
||||
}
|
||||
}
|
||||
|
||||
function abort_page(int $status, string $message): never
|
||||
{
|
||||
http_response_code($status);
|
||||
$user = auth_user();
|
||||
$title = 'Fehler ' . $status;
|
||||
$content = '<section class="panel"><h1>' . e($title) . '</h1><p>' . e($message) . '</p>'
|
||||
. '<p><a class="btn" href="' . e(url('/')) . '">Zurück zur Übersicht</a></p></section>';
|
||||
require WS_ROOT . '/views/layout.php';
|
||||
exit;
|
||||
}
|
||||
|
||||
/** Kürzt Text auf eine Zeichenzahl (mb-safe) und ergänzt eine Ellipse. */
|
||||
function shorten(string $text, int $max): string
|
||||
{
|
||||
if (mb_strlen($text, 'UTF-8') <= $max) {
|
||||
return $text;
|
||||
}
|
||||
return rtrim(mb_substr($text, 0, $max - 1, 'UTF-8')) . '…';
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue