version 0.8.0

This commit is contained in:
danny 2026-09-18 06:46:56 +02:00
parent f22007003a
commit e5ca9ef194
95 changed files with 5601 additions and 4042 deletions

View file

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
/** API-Controller (Ad) - 1:1 aus api.php. */
final class AdController
{
public function fake_ads(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
// Öffentlich: aktive Fake-Ads fürs Polling im Frontend
$rows = $pdo->query('SELECT id, image_url, target_url FROM gtl_fake_ads WHERE is_active=1 ORDER BY id DESC')->fetchAll();
respond(['ok' => true, 'ads' => $rows]);
}
public function fake_ads_all(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
RoomService::requireAdminApi($pdo, $authUserId);
$rows = $pdo->query('SELECT id, image_url, target_url, is_active, created_at FROM gtl_fake_ads ORDER BY id DESC')->fetchAll();
respond(['ok' => true, 'ads' => $rows]);
}
public function fake_ad_create(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
RoomService::requireAdminApi($pdo, $authUserId);
$body = input();
$img = substr(trim((string) ($body['image_url'] ?? '')), 0, 500);
$target= substr(trim((string) ($body['target_url'] ?? '')), 0, 500);
if ($img === '') respond(['error' => 'Bild-URL erforderlich.'], 400);
$pdo->prepare('INSERT INTO gtl_fake_ads (image_url, target_url, is_active, created_at) VALUES (?,?,1,?)')
->execute([$img, $target !== '' ? $target : null, $now]);
respond(['ok' => true, 'id' => (int) $pdo->lastInsertId()]);
}
public function fake_ad_toggle(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
RoomService::requireAdminApi($pdo, $authUserId);
$body = input();
$id = (int) ($body['id'] ?? 0);
$pdo->prepare('UPDATE gtl_fake_ads SET is_active = 1 - is_active WHERE id = ?')->execute([$id]);
respond(['ok' => true]);
}
public function fake_ad_delete(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
RoomService::requireAdminApi($pdo, $authUserId);
$body = input();
$id = (int) ($body['id'] ?? 0);
$pdo->prepare('DELETE FROM gtl_fake_ads WHERE id = ?')->execute([$id]);
respond(['ok' => true]);
}
}

View file

@ -0,0 +1,159 @@
<?php
declare(strict_types=1);
/**
* Globale, admin-verwaltete Spiel-Assets: Sounds (Audio), Reaktionen
* (Emoji ODER Bild) und Sticker (Bild). Lesen = eingeloggt; Anlegen/Löschen = Admin.
*/
final class AssetController
{
/** Alle Assets fürs Spiel + die Admin-Verwaltung. */
public function assets(): void
{
$pdo = Database::pdo();
if (empty($_SESSION['user_id'])) {
respond(['error' => 'Bitte erst einloggen.'], 401);
}
respond([
'ok' => true,
'sounds' => $pdo->query('SELECT id, label, file FROM gtl_sounds ORDER BY id ASC')->fetchAll(),
'reactions' => $pdo->query('SELECT id, emoji, image FROM gtl_reactions ORDER BY id ASC')->fetchAll(),
'stickers' => $pdo->query('SELECT id, label, file FROM gtl_stickers ORDER BY id ASC')->fetchAll(),
]);
}
// ── Sounds ────────────────────────────────────────────────
public function sound_create(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$b = input();
$label = trim((string) ($b['label'] ?? ''));
if ($label === '') respond(['error' => 'Label erforderlich.'], 400);
$fn = $this->saveAudio((string) ($b['fileBase64'] ?? ''));
$pdo->prepare('INSERT INTO gtl_sounds (label, file, created_at) VALUES (?,?,?)')
->execute([mb_substr($label, 0, 60), '/uploads/sounds/' . $fn, time()]);
respond(['ok' => true]);
}
public function sound_delete(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$id = (int) (input()['id'] ?? 0);
$st = $pdo->prepare('SELECT file FROM gtl_sounds WHERE id=?');
$st->execute([$id]);
$this->unlinkUpload((string) ($st->fetchColumn() ?: ''));
$pdo->prepare('DELETE FROM gtl_sounds WHERE id=?')->execute([$id]);
respond(['ok' => true]);
}
// ── Reaktionen (Emoji ODER Bild) ──────────────────────────
public function reaction_create(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$b = input();
$emoji = trim((string) ($b['emoji'] ?? ''));
$b64 = (string) ($b['imageBase64'] ?? '');
if ($emoji !== '') {
$pdo->prepare('INSERT INTO gtl_reactions (emoji, created_at) VALUES (?,?)')
->execute([mb_substr($emoji, 0, 8), time()]);
} elseif ($b64 !== '') {
$fn = $this->saveImage($b64, 'reactions');
$pdo->prepare('INSERT INTO gtl_reactions (image, created_at) VALUES (?,?)')
->execute(['/uploads/reactions/' . $fn, time()]);
} else {
respond(['error' => 'Emoji oder Bild angeben.'], 400);
}
respond(['ok' => true]);
}
public function reaction_delete(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$id = (int) (input()['id'] ?? 0);
$st = $pdo->prepare('SELECT image FROM gtl_reactions WHERE id=?');
$st->execute([$id]);
$this->unlinkUpload((string) ($st->fetchColumn() ?: ''));
$pdo->prepare('DELETE FROM gtl_reactions WHERE id=?')->execute([$id]);
respond(['ok' => true]);
}
// ── Sticker (Bild) ────────────────────────────────────────
public function sticker_create(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$b = input();
$label = trim((string) ($b['label'] ?? ''));
if ($label === '') respond(['error' => 'Label erforderlich.'], 400);
$fn = $this->saveImage((string) ($b['imageBase64'] ?? ''), 'stickers');
$pdo->prepare('INSERT INTO gtl_stickers (label, file, created_at) VALUES (?,?,?)')
->execute([mb_substr($label, 0, 60), '/uploads/stickers/' . $fn, time()]);
respond(['ok' => true]);
}
public function sticker_delete(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$id = (int) (input()['id'] ?? 0);
$st = $pdo->prepare('SELECT file FROM gtl_stickers WHERE id=?');
$st->execute([$id]);
$this->unlinkUpload((string) ($st->fetchColumn() ?: ''));
$pdo->prepare('DELETE FROM gtl_stickers WHERE id=?')->execute([$id]);
respond(['ok' => true]);
}
// ── Helfer ────────────────────────────────────────────────
private function saveImage(string $b64, string $subdir): string
{
if (!preg_match('#^data:image/(png|gif|jpeg|webp);base64,#', $b64, $m)) {
respond(['error' => 'Nur PNG, GIF, JPEG oder WebP erlaubt.'], 400);
}
$ext = $m[1] === 'jpeg' ? 'jpg' : $m[1];
$raw = base64_decode(preg_replace('#^data:image/[^;]+;base64,#', '', $b64) ?? '');
if ($raw === false || strlen($raw) > 800 * 1024) {
respond(['error' => 'Bild zu groß (max 800 KB).'], 400);
}
$tmp = tempnam(sys_get_temp_dir(), 'gtl_');
file_put_contents($tmp, $raw);
$info = @getimagesize($tmp);
unlink($tmp);
if (!$info) respond(['error' => 'Ungültige Bilddatei.'], 400);
$dir = BSB_UPLOADS . '/' . $subdir;
if (!is_dir($dir)) @mkdir($dir, 0755, true);
$fn = bin2hex(random_bytes(6)) . '.' . $ext;
file_put_contents($dir . '/' . $fn, $raw);
return $fn;
}
private function saveAudio(string $b64): string
{
if (!preg_match('#^data:audio/(mpeg|mp3|ogg|wav|x-wav);base64,#', $b64, $m)) {
respond(['error' => 'Nur MP3, OGG oder WAV erlaubt.'], 400);
}
$ext = ($m[1] === 'mpeg') ? 'mp3' : (($m[1] === 'x-wav') ? 'wav' : $m[1]);
$raw = base64_decode(preg_replace('#^data:audio/[^;]+;base64,#', '', $b64) ?? '');
if ($raw === false || strlen($raw) > 1500 * 1024) {
respond(['error' => 'Audio zu groß (max 1,5 MB).'], 400);
}
$dir = BSB_UPLOADS . '/sounds';
if (!is_dir($dir)) @mkdir($dir, 0755, true);
$fn = bin2hex(random_bytes(6)) . '.' . $ext;
file_put_contents($dir . '/' . $fn, $raw);
return $fn;
}
/** Löscht eine hochgeladene Datei (nur innerhalb /uploads/, nie die Seed-Statics). */
private function unlinkUpload(string $path): void
{
if ($path !== '' && str_starts_with($path, '/uploads/')) {
$abs = BSB_BASE . '/public' . $path;
if (is_file($abs)) @unlink($abs);
}
}
}

View file

@ -0,0 +1,450 @@
<?php
declare(strict_types=1);
/** Auth-API-Controller - 1:1 aus auth.php. */
final class AuthController
{
/** Admin: sich als anderer User anmelden (Impersonation). */
public function impersonate(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$uid = (int) (input()['user_id'] ?? 0);
$st = $pdo->prepare('SELECT id, role FROM gtl_users WHERE id=?');
$st->execute([$uid]);
$u = $st->fetch();
if (!$u) respond(['error' => 'User nicht gefunden.'], 404);
// ursprünglichen Admin merken (für „Zurück zum Admin")
if (empty($_SESSION['impersonator_id'])) {
$_SESSION['impersonator_id'] = (int) $_SESSION['user_id'];
}
session_regenerate_id(true);
$_SESSION['user_id'] = (int) $u['id'];
$_SESSION['role'] = $u['role'];
respond(['ok' => true]);
}
/** Impersonation beenden: zurück zur ursprünglichen Admin-Sitzung. */
public function stop_impersonating(): void
{
$pdo = Database::pdo();
$adminId = (int) ($_SESSION['impersonator_id'] ?? 0);
if (!$adminId) respond(['error' => 'Keine Admin-Sitzung aktiv.'], 400);
$st = $pdo->prepare('SELECT id, role FROM gtl_users WHERE id=?');
$st->execute([$adminId]);
$u = $st->fetch();
unset($_SESSION['impersonator_id']);
if (!$u || $u['role'] !== 'admin') respond(['error' => 'Admin-Konto nicht mehr gültig.'], 400);
session_regenerate_id(true);
$_SESSION['user_id'] = (int) $u['id'];
$_SESSION['role'] = $u['role'];
respond(['ok' => true]);
}
public function me(): void
{
$pdo = Database::pdo();
if (empty($_SESSION['user_id'])) {
respond(['ok' => true, 'user' => null]);
}
$stmt = $pdo->prepare('SELECT id, username, avatar, role FROM gtl_users WHERE id = ?');
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();
respond(['ok' => true, 'user' => $user ? AuthService::publicUser($user) : null,
'impersonating' => !empty($_SESSION['impersonator_id'])]);
}
/** Eigenen Anzeige-/Login-Namen frei ändern (eindeutig, 2–40 Zeichen). */
public function change_username(): void
{
$pdo = Database::pdo();
$me = AuthService::requireAuth($pdo);
$new = trim((string) (input()['username'] ?? ''));
$len = mb_strlen($new);
if ($len < 2 || $len > 40) respond(['error' => 'Name muss 2–40 Zeichen lang sein.'], 400);
if (preg_match('/[\x00-\x1F\x7F]/u', $new)) respond(['error' => 'Ungültige Zeichen im Namen.'], 400);
try {
$pdo->prepare('UPDATE gtl_users SET username=? WHERE id=?')->execute([$new, $me['id']]);
} catch (PDOException $e) {
if ($e->getCode() === '23000') respond(['error' => 'Dieser Name ist bereits vergeben.'], 409);
throw $e;
}
respond(['ok' => true, 'username' => $new]);
}
public function check_username(): void
{
$pdo = Database::pdo();
$username = trim($_GET['username'] ?? '');
$stmt = $pdo->prepare('SELECT id, credential_hash, role FROM gtl_users WHERE username = ?');
$stmt->execute([$username]);
$user = $stmt->fetch();
if (!$user) {
respond(['error' => 'Benutzer nicht gefunden.'], 404);
}
respond([
'ok' => true,
'needs_pin_setup' => ($user['credential_hash'] === null && $user['role'] !== 'admin'),
'is_admin' => ($user['role'] === 'admin'),
]);
}
public function login(): void
{
$pdo = Database::pdo();
$body = input();
$username = trim((string) ($body['username'] ?? ''));
$credential = (string) ($body['credential'] ?? '');
if ($username === '' || $credential === '') {
respond(['error' => 'Username und Credential erforderlich.'], 400);
}
$stmt = $pdo->prepare(
'SELECT id, username, credential_hash, avatar, role FROM gtl_users WHERE username = ?'
);
$stmt->execute([$username]);
$user = $stmt->fetch();
// Generic error to prevent username enumeration
if (!$user || $user['credential_hash'] === null) {
respond(['error' => 'Benutzername oder PIN/Passwort falsch.'], 401);
}
if (!password_verify($credential, $user['credential_hash'])) {
respond(['error' => 'Benutzername oder PIN/Passwort falsch.'], 401);
}
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['role'] = $user['role'];
$pdo->prepare('UPDATE gtl_users SET last_login = ? WHERE id = ?')
->execute([time(), $user['id']]);
respond(['ok' => true, 'user' => AuthService::publicUser($user)]);
}
public function set_pin(): void
{
$pdo = Database::pdo();
$body = input();
$username = trim((string) ($body['username'] ?? ''));
$pin = (string) ($body['pin'] ?? '');
$confirmPin = (string) ($body['confirmPin'] ?? '');
if (!preg_match('/^\d{4,8}$/', $pin)) {
respond(['error' => 'PIN muss 4–8 Ziffern sein.'], 400);
}
if ($pin !== $confirmPin) {
respond(['error' => 'PINs stimmen nicht überein.'], 400);
}
$stmt = $pdo->prepare(
'SELECT id, credential_hash, role, avatar FROM gtl_users WHERE username = ?'
);
$stmt->execute([$username]);
$user = $stmt->fetch();
if (!$user) {
respond(['error' => 'Benutzer nicht gefunden.'], 404);
}
if ($user['credential_hash'] !== null) {
respond(['error' => 'PIN wurde bereits festgelegt.'], 409);
}
if ($user['role'] === 'admin') {
respond(['error' => 'Admin-Konto nutzt ein Passwort.'], 400);
}
$hash = password_hash($pin, PASSWORD_DEFAULT);
$pdo->prepare('UPDATE gtl_users SET credential_hash = ? WHERE id = ?')
->execute([$hash, $user['id']]);
session_regenerate_id(true);
$_SESSION['user_id'] = $user['id'];
$_SESSION['role'] = $user['role'];
$pdo->prepare('UPDATE gtl_users SET last_login = ? WHERE id = ?')
->execute([time(), $user['id']]);
respond(['ok' => true, 'user' => AuthService::publicUser($user)]);
}
public function change_credential(): void
{
$pdo = Database::pdo();
$me = AuthService::requireAuth($pdo);
$body = input();
$old = (string) ($body['old'] ?? '');
$new = (string) ($body['new'] ?? '');
if ($me['role'] !== 'admin' && !preg_match('/^\d{4,8}$/', $new)) {
respond(['error' => 'Neuer PIN muss 4–8 Ziffern sein.'], 400);
}
if ($me['role'] === 'admin' && strlen($new) < 8) {
respond(['error' => 'Passwort muss mindestens 8 Zeichen haben.'], 400);
}
$stmt = $pdo->prepare('SELECT credential_hash FROM gtl_users WHERE id = ?');
$stmt->execute([$me['id']]);
$row = $stmt->fetch();
if (!$row || !password_verify($old, $row['credential_hash'] ?? '')) {
respond(['error' => 'Aktueller PIN/Passwort falsch.'], 401);
}
$pdo->prepare('UPDATE gtl_users SET credential_hash = ? WHERE id = ?')
->execute([password_hash($new, PASSWORD_DEFAULT), $me['id']]);
respond(['ok' => true]);
}
public function logout(): void
{
$pdo = Database::pdo();
session_destroy();
respond(['ok' => true]);
}
public function create_user(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$body = input();
$username = trim((string) ($body['username'] ?? ''));
if (!preg_match('/^[a-zA-Z0-9_\-]{2,40}$/', $username)) {
respond(['error' => 'Username: 2–40 Zeichen, nur Buchstaben, Zahlen, _ und -.'], 400);
}
try {
$pdo->prepare(
"INSERT INTO gtl_users (username, role, created_at) VALUES (?, 'user', ?)"
)->execute([$username, time()]);
$uid = (int) $pdo->lastInsertId();
$pdo->prepare('INSERT INTO gtl_user_stats (user_id) VALUES (?)')->execute([$uid]);
respond(['ok' => true, 'user_id' => $uid, 'username' => $username]);
} catch (PDOException $e) {
if ($e->getCode() === '23000') {
respond(['error' => 'Username bereits vergeben.'], 409);
}
throw $e;
}
}
public function reset_pin(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$body = input();
$uid = (int) ($body['user_id'] ?? 0);
$stmt = $pdo->prepare("SELECT role FROM gtl_users WHERE id = ?");
$stmt->execute([$uid]);
$target = $stmt->fetch();
if (!$target) respond(['error' => 'User nicht gefunden.'], 404);
if ($target['role'] === 'admin') respond(['error' => 'Admin-PIN kann hier nicht zurückgesetzt werden.'], 400);
$pdo->prepare('UPDATE gtl_users SET credential_hash = NULL WHERE id = ?')
->execute([$uid]);
respond(['ok' => true]);
}
public function delete_user(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$body = input();
$uid = (int) ($body['user_id'] ?? 0);
if ($uid === (int) ($_SESSION['user_id'] ?? 0)) {
respond(['error' => 'Du kannst dich nicht selbst löschen.'], 400);
}
$pdo->prepare('DELETE FROM gtl_users WHERE id = ? AND role != "admin"')
->execute([$uid]);
respond(['ok' => true]);
}
public function get_users(): void
{
$pdo = Database::pdo();
AuthService::requireAdmin($pdo);
$stmt = $pdo->query(
'SELECT u.id, u.username, u.avatar, u.role, u.created_at, u.last_login,
(u.credential_hash IS NULL AND u.role != "admin") AS needs_pin_setup,
s.games_played, s.games_won
FROM gtl_users u
LEFT JOIN gtl_user_stats s ON s.user_id = u.id
ORDER BY u.created_at ASC'
);
respond(['ok' => true, 'users' => $stmt->fetchAll()]);
}
public function save_color(): void
{
$pdo = Database::pdo();
$me = AuthService::requireAuth($pdo);
$body = input();
$color = trim($body['color'] ?? '');
if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
respond(['error' => 'Ungültige Farbe.'], 400);
}
$pdo->prepare('UPDATE gtl_users SET color=? WHERE id=?')
->execute([$color, $me['id']]);
respond(['ok' => true]);
}
/** Vollständiger Name-Stil: Farbe(n), Stil (solid/gradient/rainbow), Font. */
public function save_name_style(): void
{
$pdo = Database::pdo();
$me = AuthService::requireAuth($pdo);
$b = input();
$color = trim((string) ($b['color'] ?? ''));
if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) respond(['error' => 'Ungültige Farbe.'], 400);
$style = (string) ($b['name_style'] ?? 'solid');
if (!in_array($style, ['solid', 'gradient', 'rainbow'], true)) $style = 'solid';
$color2 = trim((string) ($b['color2'] ?? ''));
$color2v = preg_match('/^#[0-9a-fA-F]{6}$/', $color2) ? $color2 : null;
$font = (string) ($b['name_font'] ?? '');
$fonts = ['inter', 'sora', 'pacifico', 'lobster', 'bungee', 'bangers', 'orbitron', 'pressstart'];
$fontv = in_array($font, $fonts, true) ? $font : null;
$pdo->prepare('UPDATE gtl_users SET color=?, color2=?, name_style=?, name_font=? WHERE id=?')
->execute([$color, $color2v, $style, $fontv, $me['id']]);
respond(['ok' => true]);
}
public function get_profile(): void
{
$pdo = Database::pdo();
$me = AuthService::requireAuth($pdo);
$stmt = $pdo->prepare(
'SELECT u.id, u.username, u.avatar, u.role, u.created_at, u.last_login, u.color, u.sticker,
u.color2, u.name_style, u.name_font, u.theme,
s.*
FROM gtl_users u
LEFT JOIN gtl_user_stats s ON s.user_id = u.id
WHERE u.id = ?'
);
$stmt->execute([$me['id']]);
$profile = $stmt->fetch();
respond(['ok' => true, 'profile' => $profile]);
}
public function get_history(): void
{
$pdo = Database::pdo();
$me = AuthService::requireAuth($pdo);
$page = max(1, (int) ($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;
$stmt = $pdo->prepare(
'SELECT r.id AS round_id, r.room_code, r.round_num, r.played_at, r.outcome,
rp.was_imposter, rp.voted_out
FROM gtl_round_players rp
JOIN gtl_game_rounds r ON r.id = rp.round_id
WHERE rp.user_id = ?
ORDER BY r.played_at DESC
LIMIT ? OFFSET ?'
);
$stmt->execute([$me['id'], $limit, $offset]);
$rounds = $stmt->fetchAll();
$countStmt = $pdo->prepare(
'SELECT COUNT(*) FROM gtl_round_players WHERE user_id = ?'
);
$countStmt->execute([$me['id']]);
$total = (int) $countStmt->fetchColumn();
respond(['ok' => true, 'rounds' => $rounds, 'total' => $total, 'page' => $page]);
}
public function upload_avatar(): void
{
$pdo = Database::pdo();
$me = AuthService::requireAuth($pdo);
$body = input();
$b64 = (string) ($body['imageBase64'] ?? '');
if (!preg_match('#^data:image/(jpeg|png|webp);base64,#', $b64, $m)) {
respond(['error' => 'Nur JPEG, PNG oder WebP erlaubt.'], 400);
}
$ext = $m[1] === 'jpeg' ? 'jpg' : $m[1];
$raw = base64_decode(preg_replace('#^data:image/[^;]+;base64,#', '', $b64) ?? '');
if ($raw === false || strlen($raw) > 2 * 1024 * 1024) {
respond(['error' => 'Bild zu groß (max 2 MB).'], 400);
}
// Validate actual image
$tmpFile = tempnam(sys_get_temp_dir(), 'gtl_');
file_put_contents($tmpFile, $raw);
$info = @getimagesize($tmpFile);
unlink($tmpFile);
if (!$info) {
respond(['error' => 'Ungültige Bilddatei.'], 400);
}
$dir = BSB_UPLOADS . '/avatars';
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
// Remove old avatar
$stmt = $pdo->prepare('SELECT avatar FROM gtl_users WHERE id = ?');
$stmt->execute([$me['id']]);
$old = $stmt->fetchColumn();
if ($old && file_exists($dir . '/' . $old)) {
unlink($dir . '/' . $old);
}
$filename = $me['id'] . '_' . time() . '.' . $ext;
file_put_contents($dir . '/' . $filename, $raw);
$pdo->prepare('UPDATE gtl_users SET avatar = ? WHERE id = ?')
->execute([$filename, $me['id']]);
respond(['ok' => true, 'avatar' => $filename]);
}
public function upload_sticker(): void
{
$pdo = Database::pdo();
$me = AuthService::requireAuth($pdo);
$body = input();
$b64 = (string) ($body['imageBase64'] ?? '');
if (!preg_match('#^data:image/(png|gif);base64,#', $b64, $m)) {
respond(['error' => 'Nur PNG oder GIF erlaubt.'], 400);
}
$ext = $m[1];
$raw = base64_decode(preg_replace('#^data:image/[^;]+;base64,#', '', $b64) ?? '');
if ($raw === false || strlen($raw) > 500 * 1024) {
respond(['error' => 'Sticker zu groß (max 500 KB).'], 400);
}
$tmpFile = tempnam(sys_get_temp_dir(), 'gtl_');
file_put_contents($tmpFile, $raw);
$info = @getimagesize($tmpFile);
unlink($tmpFile);
if (!$info || !in_array($info[2], [IMAGETYPE_PNG, IMAGETYPE_GIF], true)) {
respond(['error' => 'Ungültige Sticker-Datei.'], 400);
}
$dir = BSB_UPLOADS . '/sticker';
if (!is_dir($dir)) { mkdir($dir, 0755, true); }
// alten Sticker entfernen
$stmt = $pdo->prepare('SELECT sticker FROM gtl_users WHERE id = ?');
$stmt->execute([$me['id']]);
$old = $stmt->fetchColumn();
if ($old && file_exists($dir . '/' . $old)) { unlink($dir . '/' . $old); }
$filename = $me['id'] . '_' . time() . '.' . $ext;
file_put_contents($dir . '/' . $filename, $raw);
$pdo->prepare('UPDATE gtl_users SET sticker = ? WHERE id = ?')
->execute([$filename, $me['id']]);
respond(['ok' => true, 'sticker' => $filename]);
}
}

View file

@ -0,0 +1,131 @@
<?php
declare(strict_types=1);
/** API-Controller (Chat) - 1:1 aus api.php. */
final class ChatController
{
public function send_emoji(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$emoji = (string) ($body['emoji'] ?? '');
$allowed = ['🐑','🔥','😂','👍','🐱'];
if (!in_array($emoji, $allowed, true)) respond(['error' => 'Ungültiges Emoji.'], 400);
// Load existing, prune stale (>4s), append new, keep max 20
$emojiStmt = $pdo->prepare('SELECT active_emojis FROM gtl_rooms WHERE code=?');
$emojiStmt->execute([$code]);
$emojiRow = $emojiStmt->fetch();
if (!$emojiRow) respond(['error' => 'Raum nicht gefunden.'], 404);
$list = (!empty($emojiRow['active_emojis'])) ? (json_decode($emojiRow['active_emojis'], true) ?: []) : [];
$list = array_filter($list, fn($e) => ($e['ts'] ?? 0) >= ($now - 4));
$list[] = ['emoji' => $emoji, 'ts' => $now, 'id' => uniqid()];
$list = array_values(array_slice($list, -20));
$pdo->prepare('UPDATE gtl_rooms SET active_emojis=?, updated_at=? WHERE code=?')
->execute([json_encode($list), $now, $code]);
respond(['ok' => true]);
}
/** Globale Reaktion (Emoji ODER Bild) per id senden. */
public function send_reaction(): void
{
$pdo = Database::pdo();
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$id = (int) ($body['id'] ?? 0);
$st = $pdo->prepare('SELECT emoji, image FROM gtl_reactions WHERE id=?');
$st->execute([$id]);
$r = $st->fetch();
if (!$r) respond(['error' => 'Unbekannte Reaktion.'], 400);
$item = !empty($r['emoji']) ? ['emoji' => $r['emoji']] : ['sticker' => $r['image']];
$this->broadcast($pdo, $code, $item);
respond(['ok' => true]);
}
/** Sticker fliegen lassen: globaler Sticker per id, sonst der eigene Profil-Sticker. */
public function send_sticker(): void
{
$pdo = Database::pdo();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$id = (int) ($body['id'] ?? 0);
if ($id > 0) {
$st = $pdo->prepare('SELECT file FROM gtl_stickers WHERE id=?');
$st->execute([$id]);
$file = (string) ($st->fetchColumn() ?: '');
if ($file === '') respond(['error' => 'Unbekannter Sticker.'], 400);
$this->broadcast($pdo, $code, ['sticker' => $file]);
respond(['ok' => true]);
}
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$st = $pdo->prepare('SELECT sticker FROM gtl_users WHERE id=?');
$st->execute([$authUserId]);
$stickerFile = (string) ($st->fetchColumn() ?: '');
if ($stickerFile === '' || !preg_match('/^[A-Za-z0-9_.\-]+$/', $stickerFile)) {
respond(['error' => 'Kein gültiger Sticker vorhanden.'], 400);
}
$this->broadcast($pdo, $code, ['sticker' => '/uploads/sticker/' . $stickerFile]);
respond(['ok' => true]);
}
/** Soundboard: globalen Sound per id bei allen abspielen. */
public function send_sound(): void
{
$pdo = Database::pdo();
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$id = (int) ($body['id'] ?? 0);
$st = $pdo->prepare('SELECT file FROM gtl_sounds WHERE id=?');
$st->execute([$id]);
$file = (string) ($st->fetchColumn() ?: '');
if ($file === '') respond(['error' => 'Unbekannter Sound.'], 400);
$this->broadcast($pdo, $code, ['sound' => $file]);
respond(['ok' => true]);
}
/** Hängt eine Reaktion/Sound/Sticker an die Live-Broadcast-Liste des Raums an. */
private function broadcast(PDO $pdo, string $code, array $item): void
{
$now = time();
$st = $pdo->prepare('SELECT active_emojis FROM gtl_rooms WHERE code=?');
$st->execute([$code]);
$row = $st->fetch();
if (!$row) respond(['error' => 'Raum nicht gefunden.'], 404);
$list = (!empty($row['active_emojis'])) ? (json_decode($row['active_emojis'], true) ?: []) : [];
$list = array_filter($list, fn($e) => ($e['ts'] ?? 0) >= ($now - 4));
$item['ts'] = $now;
$item['id'] = uniqid();
$list[] = $item;
$list = array_values(array_slice($list, -20));
$pdo->prepare('UPDATE gtl_rooms SET active_emojis=?, updated_at=? WHERE code=?')
->execute([json_encode($list), $now, $code]);
}
public function send_chat(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$sender = substr(trim((string) ($body['name'] ?? '')), 0, 40);
$message = substr(trim((string) ($body['message'] ?? '')), 0, 500);
if ($code === '' || $sender === '' || $message === '') {
respond(['error' => 'Fehlende Parameter.'], 400);
}
$pdo->prepare(
'INSERT INTO gtl_chat_messages (room_code, player_name, message, created_at) VALUES (?,?,?,?)'
)->execute([$code, $sender, $message, $now]);
// Keep only last 200 messages per room
$pdo->prepare(
'DELETE FROM gtl_chat_messages WHERE room_code=? AND id NOT IN
(SELECT id FROM (SELECT id FROM gtl_chat_messages WHERE room_code=? ORDER BY id DESC LIMIT 200) t)'
)->execute([$code, $code]);
respond(['ok' => true]);
}
}

View file

@ -0,0 +1,268 @@
<?php
declare(strict_types=1);
/** API-Controller (Game) - 1:1 aus api.php. */
final class GameController
{
public function assign_questions(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$normalQ = substr(trim((string) ($body['normalQuestion'] ?? '')), 0, 2000);
$imposterQ = substr(trim((string) ($body['imposterQuestion'] ?? '')), 0, 2000);
$imposterKeys = array_values(array_filter(
(array) ($body['imposterKeys'] ?? []),
fn($k) => is_string($k) && $k !== ''
));
if ($normalQ === '') respond(['error' => 'Normale Frage darf nicht leer sein.'], 400);
if ($imposterQ === '') respond(['error' => 'Imposter-Frage darf nicht leer sein.'], 400);
if (!empty($imposterKeys)) {
$in = implode(',', array_fill(0, count($imposterKeys), '?'));
$chk = $pdo->prepare("SELECT pkey FROM gtl_players WHERE room_code=? AND pkey IN ($in)");
$chk->execute(array_merge([$code], $imposterKeys));
$valid = array_column($chk->fetchAll(), 'pkey');
$imposterKeys = array_values(array_intersect($imposterKeys, $valid));
}
$pdo->prepare(
'UPDATE gtl_rooms
SET normal_question=?, imposter_question=?, liar_keys=?,
voted_out_keys=NULL, round_outcome=NULL, voting_open=0,
reveal_index=-1, revealed_keys=NULL, questions_revealed=0, updated_at=?
WHERE code=?'
)->execute([$normalQ, $imposterQ, json_encode($imposterKeys), $now, $code]);
$ps = $pdo->prepare('SELECT pkey FROM gtl_players WHERE room_code=?');
$ps->execute([$code]);
$upd = $pdo->prepare(
'UPDATE gtl_players SET question=?, vote_for=NULL, vote_locked=0, vote_request=0, late_join=0, updated_at=?
WHERE room_code=? AND pkey=?'
);
foreach (array_column($ps->fetchAll(), 'pkey') as $pk) {
$q = in_array($pk, $imposterKeys, true) ? $imposterQ : $normalQ;
$upd->execute([$q, $now, $code, $pk]);
}
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function submit_answer(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
$answer = substr(trim((string) ($body['answer'] ?? '')), 0, 2000);
if ($answer === '') respond(['error' => 'Antwort darf nicht leer sein.'], 400);
$pdo->prepare(
'UPDATE gtl_players SET answer=?, answered=1, updated_at=? WHERE room_code=? AND pkey=?'
)->execute([$answer, $now, $code, $pkey]);
$pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]);
respond(['ok' => true]);
}
public function delete_answer(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
if ($code === '' || $pkey === '') respond(['error' => 'Fehlende Parameter.'], 400);
$pdo->prepare(
'UPDATE gtl_players SET answer=NULL, answered=0, vote_for=NULL, updated_at=?
WHERE room_code=? AND pkey=?'
)->execute([$now, $code, $pkey]);
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function reveal(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
// Alle gleichzeitig aufdecken
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
// Collect all player pkeys for this room
$pkStmt = $pdo->prepare('SELECT pkey FROM gtl_players WHERE room_code=?');
$pkStmt->execute([$code]);
$allKeys = array_column($pkStmt->fetchAll(), 'pkey');
$pdo->prepare('UPDATE gtl_rooms SET revealed=1, reveal_index=9999, revealed_keys=?, updated_at=? WHERE code=?')
->execute([json_encode($allKeys), $now, $code]);
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function reveal_answer(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
// Gezielt eine Antwort aufdecken (Host klickt Spielerkarte)
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$rpkey = (string) ($body['pkey'] ?? '');
if ($rpkey === '') respond(['error' => 'pkey fehlt.'], 400);
$rkStmt = $pdo->prepare('SELECT revealed_keys FROM gtl_rooms WHERE code=?');
$rkStmt->execute([$code]);
$rkRow = $rkStmt->fetch();
if (!$rkRow) respond(['error' => 'Raum nicht gefunden.'], 404);
$j2 = fn($v) => (!empty($v) && is_string($v)) ? (json_decode($v, true) ?: []) : [];
$rkeys = $j2($rkRow['revealed_keys'] ?? '');
if (!in_array($rpkey, $rkeys, true)) {
$rkeys[] = $rpkey;
}
$pdo->prepare('UPDATE gtl_rooms SET revealed=1, reveal_index=?, revealed_keys=?, updated_at=? WHERE code=?')
->execute([count($rkeys), json_encode($rkeys), $now, $code]);
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function reveal_questions(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
// Leiter deckt die echte Frage für die Imposter auf (Knopfdruck)
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pdo->prepare('UPDATE gtl_rooms SET questions_revealed=1, updated_at=? WHERE code=?')
->execute([$now, $code]);
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function reveal_next(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
// Legacy: Nächste Antwort sequenziell aufdecken (fallback)
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$riRow = $pdo->prepare('SELECT reveal_index FROM gtl_rooms WHERE code=?');
$riRow->execute([$code]);
$riData = $riRow->fetch();
if (!$riData) respond(['error' => 'Raum nicht gefunden.'], 404);
$newIdx = (int) $riData['reveal_index'] + 1;
$pdo->prepare('UPDATE gtl_rooms SET revealed=1, reveal_index=?, updated_at=? WHERE code=?')
->execute([$newIdx, $now, $code]);
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function update_weights(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$weights = (string) ($body['weights'] ?? '');
$decoded = json_decode($weights, true);
if (!is_array($decoded)) respond(['error' => 'Ungültiges JSON für Imposter-Gewichte.'], 400);
$pdo->prepare('UPDATE gtl_rooms SET imposter_weights=?, updated_at=? WHERE code=?')
->execute([$weights, $now, $code]);
respond(['ok' => true]);
}
public function get_host_history(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$code = slugCode((string) ($_GET['code'] ?? ''));
if ($code === '') respond(['error' => 'Code fehlt.'], 400);
$stmt = $pdo->prepare(
'SELECT r.id AS round_id, r.round_num, r.played_at, r.outcome,
rp.player_name, rp.pkey, rp.was_imposter, rp.voted_out,
rp.question, rp.answer, u.avatar
FROM gtl_game_rounds r
JOIN gtl_round_players rp ON rp.round_id = r.id
LEFT JOIN gtl_users u ON u.id = rp.user_id
WHERE r.room_code = ?
ORDER BY r.round_num DESC, rp.id ASC'
);
$stmt->execute([$code]);
$rows = $stmt->fetchAll();
$grouped = [];
foreach ($rows as $row) {
$rn = (int) $row['round_num'];
if (!isset($grouped[$rn])) {
$grouped[$rn] = [
'round_num' => $rn,
'played_at' => (int) $row['played_at'],
'outcome' => $row['outcome'],
'players' => [],
];
}
$grouped[$rn]['players'][] = [
'name' => $row['player_name'],
'pkey' => $row['pkey'],
'avatar' => $row['avatar'] ?? null,
'was_imposter'=> (bool) $row['was_imposter'],
'voted_out' => (bool) $row['voted_out'],
'question' => $row['question'] ?? '',
'answer' => $row['answer'] ?? '',
];
}
respond(['ok' => true, 'history' => array_values($grouped)]);
}
public function score(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
$delta = (int) ($body['delta'] ?? 0);
$pdo->prepare('UPDATE gtl_players SET score=score+?, updated_at=? WHERE room_code=? AND pkey=?')
->execute([$delta, $now, $code, $pkey]);
respond(['ok' => true]);
}
public function new_round(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$state = RoomService::loadRoom($pdo, $code);
// Aktuelle Runde zuerst archivieren (falls noch nicht geschehen)
if ($state && !empty($state['players'])) {
RoomService::archiveRound($pdo, $state, $now);
}
$pdo->prepare(
'UPDATE gtl_rooms
SET revealed=0, liar_keys=NULL, voted_out_keys=NULL, round_outcome=NULL,
normal_question=NULL, imposter_question=NULL, voting_open=0,
reveal_index=-1, revealed_keys=NULL, questions_revealed=0, active_emojis=NULL,
round_num=round_num+1, updated_at=?
WHERE code=?'
)->execute([$now, $code]);
$pdo->prepare(
'UPDATE gtl_players
SET question=NULL, answer=NULL, answered=0, vote_for=NULL,
vote_locked=0, vote_request=0, late_join=0, updated_at=?
WHERE room_code=?'
)->execute([$now, $code]);
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
}

View file

@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
/** API-Controller (Group) - 1:1 aus api.php. */
final class GroupController
{
public function group_create(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$body = input();
$gname = substr(trim((string) ($body['name'] ?? '')), 0, 60);
if ($gname === '') respond(['error' => 'Gruppenname erforderlich.'], 400);
$pdo->prepare('INSERT INTO gtl_groups (group_name, created_by, created_at) VALUES (?,?,?)')
->execute([$gname, $authUserId, $now]);
$gid = (int) $pdo->lastInsertId();
$pdo->prepare('INSERT IGNORE INTO gtl_group_members (group_id, user_id, joined_at) VALUES (?,?,?)')
->execute([$gid, $authUserId, $now]);
respond(['ok' => true, 'id' => $gid]);
}
public function group_join(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$body = input();
$gname = substr(trim((string) ($body['name'] ?? '')), 0, 60);
$gs = $pdo->prepare('SELECT id FROM gtl_groups WHERE group_name = ? ORDER BY id ASC LIMIT 1');
$gs->execute([$gname]);
$gid = (int) ($gs->fetchColumn() ?: 0);
if (!$gid) respond(['error' => 'Herde nicht gefunden.'], 404);
$pdo->prepare('INSERT IGNORE INTO gtl_group_members (group_id, user_id, joined_at) VALUES (?,?,?)')
->execute([$gid, $authUserId, $now]);
respond(['ok' => true, 'id' => $gid]);
}
public function group_leave(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$body = input();
$gid = (int) ($body['id'] ?? 0);
$pdo->prepare('DELETE FROM gtl_group_members WHERE group_id=? AND user_id=?')
->execute([$gid, $authUserId]);
respond(['ok' => true]);
}
public function groups_my(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
if (!$authUserId) respond(['ok' => true, 'groups' => []]);
$gq = $pdo->prepare(
'SELECT g.id, g.group_name FROM gtl_groups g
JOIN gtl_group_members m ON m.group_id = g.id
WHERE m.user_id = ? ORDER BY g.group_name ASC'
);
$gq->execute([$authUserId]);
$groups = $gq->fetchAll();
$mq = $pdo->prepare(
'SELECT u.username, u.last_seen, u.current_room, u.color, u.color2, u.name_style, u.name_font
FROM gtl_group_members gm JOIN gtl_users u ON u.id = gm.user_id
WHERE gm.group_id = ? ORDER BY u.username ASC'
);
$online = $now - 40;
foreach ($groups as &$g) {
$mq->execute([(int) $g['id']]);
$g['members'] = array_map(function ($m) use ($online) {
return [
'username' => $m['username'],
'color' => $m['color'],
'color2' => $m['color2'],
'nameStyle' => $m['name_style'] ?? 'solid',
'nameFont' => $m['name_font'],
'online' => ((int) ($m['last_seen'] ?? 0)) >= $online,
'room' => $m['current_room'],
];
}, $mq->fetchAll());
}
unset($g);
respond(['ok' => true, 'groups' => $groups]);
}
}

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
/** API-Controller (Presence) - 1:1 aus api.php. */
final class PresenceController
{
public function heartbeat(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
if ($authUserId) {
$pdo->prepare('UPDATE gtl_users SET last_seen=?, current_room=NULL WHERE id=?')
->execute([$now, $authUserId]);
}
respond(['ok' => true]);
}
}

View file

@ -0,0 +1,187 @@
<?php
declare(strict_types=1);
/** API-Controller (Room) - 1:1 aus api.php. */
final class RoomController
{
public function host_open(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pass = (string) ($body['pass'] ?? '');
if ($code === '' || $pass === '') respond(['error' => 'Code und Passwort erforderlich.'], 400);
$stmt = $pdo->prepare('SELECT pass_hash FROM gtl_rooms WHERE code = ?');
$stmt->execute([$code]);
$existing = $stmt->fetch();
if ($existing === false) {
$pdo->prepare(
'INSERT INTO gtl_rooms (code, pass_hash, revealed, round_num, created_at, updated_at)
VALUES (?, ?, 0, 1, ?, ?)'
)->execute([$code, password_hash($pass, PASSWORD_DEFAULT), $now, $now]);
} elseif (!password_verify($pass, $existing['pass_hash'])) {
respond(['error' => 'Falsches Passwort.'], 403);
}
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function player_join(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$name = substr(trim((string) ($body['name'] ?? '')), 0, 40);
if ($code === '' || $name === '') respond(['error' => 'Code und Name erforderlich.'], 400);
$chk = $pdo->prepare('SELECT 1 FROM gtl_rooms WHERE code = ?');
$chk->execute([$code]);
if ($chk->fetch() === false) respond(['error' => 'Raum existiert nicht. Spielleiter muss ihn zuerst eröffnen.'], 404);
$pkey = playerKey($name);
$pdo->prepare(
'INSERT INTO gtl_players (room_code, pkey, name, user_id, answered, score, updated_at)
VALUES (?, ?, ?, ?, 0, 0, ?)
ON DUPLICATE KEY UPDATE name=VALUES(name), user_id=VALUES(user_id), updated_at=VALUES(updated_at)'
)->execute([$code, $pkey, $name, $authUserId, $now]);
// Nachzügler-Logik: Läuft bereits eine Runde (Frage gesetzt, nicht aufgelöst),
// wird ein NEU beitretender Spieler für diese Runde zum Zuschauer. Er blockiert
// weder Reveal noch Auto-Voting und wird bei new_round wieder voll aktiv.
$rstmt = $pdo->prepare('SELECT normal_question, round_outcome FROM gtl_rooms WHERE code=?');
$rstmt->execute([$code]);
$rrow = $rstmt->fetch();
$roundActive = $rrow && !empty($rrow['normal_question']) && empty($rrow['round_outcome']);
if ($roundActive) {
$pdo->prepare(
"UPDATE gtl_players
SET answer='Zuschauer / Später beigetreten', answered=1,
vote_locked=1, late_join=1, updated_at=?
WHERE room_code=? AND pkey=? AND (question IS NULL OR question='')"
)->execute([$now, $code, $pkey]);
}
respond(['ok' => true, 'pkey' => $pkey, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function admin_spectate(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401);
$roleStmt = $pdo->prepare('SELECT role FROM gtl_users WHERE id = ?');
$roleStmt->execute([$authUserId]);
if ($roleStmt->fetchColumn() !== 'admin') respond(['error' => 'Keine Berechtigung.'], 403);
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
if ($code === '') respond(['error' => 'Raum-Code erforderlich.'], 400);
$state = RoomService::loadRoom($pdo, $code, true);
if ($state === null) respond(['error' => 'Raum nicht gefunden.'], 404);
// Remember this admin is spectating this room → state polls keep revealing imposters
$_SESSION['spectate'][$code] = true;
respond(['ok' => true, 'state' => $state]);
}
public function state(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$code = slugCode((string) ($_GET['code'] ?? ''));
// Update activity timestamp so room stays alive while anyone polls
$pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]);
// Präsenz für die Herden-Übersicht: dieser User ist gerade in diesem Raum
if ($authUserId) {
$pdo->prepare('UPDATE gtl_users SET last_seen=?, current_room=? WHERE id=?')
->execute([$now, $code, $authUserId]);
}
// Lazy cleanup: delete rooms inactive for 12+ hours
$pdo->exec('DELETE FROM gtl_rooms WHERE updated_at < ' . ($now - 43200));
// Admin spectators keep seeing imposters while polling (flag set via admin_spectate)
$spectating = !empty($_SESSION['spectate'][$code]);
$state = RoomService::loadRoom($pdo, $code, $spectating);
if ($state === null) respond(['error' => 'Raum nicht gefunden.'], 404);
respond(['ok' => true, 'state' => $state]);
}
public function delete_room(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pass = (string) ($body['pass'] ?? '');
$stmt = $pdo->prepare('SELECT pass_hash FROM gtl_rooms WHERE code=?');
$stmt->execute([$code]);
$row = $stmt->fetch();
if (!$row || !password_verify($pass, $row['pass_hash'])) {
respond(['error' => 'Falsches Passwort.'], 403);
}
$pdo->prepare('DELETE FROM gtl_rooms WHERE code=?')->execute([$code]);
respond(['ok' => true]);
}
public function remove_player(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
$pdo->prepare('DELETE FROM gtl_players WHERE room_code=? AND pkey=?')
->execute([$code, $pkey]);
$stmt = $pdo->prepare('SELECT liar_keys FROM gtl_rooms WHERE code=?');
$stmt->execute([$code]);
$row = $stmt->fetch();
if ($row && !empty($row['liar_keys'])) {
$keys = json_decode($row['liar_keys'], true) ?: [];
$keys = array_values(array_filter($keys, fn($k) => $k !== $pkey));
$pdo->prepare('UPDATE gtl_rooms SET liar_keys=?, updated_at=? WHERE code=?')
->execute([json_encode($keys), $now, $code]);
}
respond(['ok' => true]);
}
public function reset_scores(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pdo->prepare('UPDATE gtl_players SET score=0, updated_at=? WHERE room_code=?')
->execute([$now, $code]);
respond(['ok' => true]);
}
/** Liste aktiver Lobbys (für die Lobby-Übersicht im Join-Screen). */
public function active_rooms(): void
{
$pdo = Database::pdo();
$cutoff = time() - 150; // ~2,5 Min ohne Aktivität => nicht mehr gelistet
$stmt = $pdo->prepare(
'SELECT r.code, r.round_num, r.voting_open, r.updated_at, COUNT(p.id) AS players
FROM gtl_rooms r
JOIN gtl_players p ON p.room_code = r.code
WHERE r.updated_at >= ?
GROUP BY r.code, r.round_num, r.voting_open, r.updated_at
ORDER BY r.updated_at DESC
LIMIT 30'
);
$stmt->execute([$cutoff]);
respond(['ok' => true, 'rooms' => $stmt->fetchAll()]);
}
}

View file

@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
/** API-Controller (Voting) - 1:1 aus api.php. */
final class VotingController
{
public function open_voting(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pdo->prepare('UPDATE gtl_rooms SET voting_open=1, updated_at=? WHERE code=?')
->execute([$now, $code]);
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function request_voting(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
// Demokratischer Voting-Antrag: sobald ALLE Spieler angefragt haben → auto-open
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
// Antrag nur erlauben, wenn alle Antworten aufgedeckt sind
$rvStmt = $pdo->prepare('SELECT reveal_index, revealed_keys FROM gtl_rooms WHERE code=?');
$rvStmt->execute([$code]);
$rvRoom = $rvStmt->fetch();
if (!$rvRoom) respond(['error' => 'Raum nicht gefunden.'], 404);
$playerCount = (int) $pdo->query('SELECT COUNT(*) FROM gtl_players WHERE late_join=0 AND room_code=' . $pdo->quote($code))->fetchColumn();
$revealedKeys = (!empty($rvRoom['revealed_keys'])) ? (json_decode($rvRoom['revealed_keys'], true) ?: []) : [];
$allRevealed = $playerCount > 0
&& ((int) ($rvRoom['reveal_index'] ?? -1) >= 9999 || count($revealedKeys) >= $playerCount);
if (!$allRevealed) {
respond(['error' => 'Erst müssen alle Antworten aufgedeckt werden.'], 409);
}
$pdo->prepare('UPDATE gtl_players SET vote_request=1, updated_at=? WHERE room_code=? AND pkey=?')
->execute([$now, $code, $pkey]);
$pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]);
// Wenn alle Spieler request gesetzt haben → Voting öffnen
$pending = $pdo->prepare('SELECT COUNT(*) FROM gtl_players WHERE room_code=? AND vote_request=0 AND late_join=0');
$pending->execute([$code]);
if ((int) $pending->fetchColumn() === 0) {
$pdo->prepare('UPDATE gtl_rooms SET voting_open=1, updated_at=? WHERE code=?')
->execute([$now, $code]);
}
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function lock_vote(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
// Stimme final abschicken. Sperrt die Auswahl; wenn alle gesperrt → Auto-Auswertung.
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
$votes = array_values(array_filter((array) ($body['votes'] ?? []), 'is_string'));
$vLock = $pdo->prepare('SELECT voting_open FROM gtl_rooms WHERE code=?');
$vLock->execute([$code]);
$vLockRow = $vLock->fetch();
if (!$vLockRow || !$vLockRow['voting_open']) {
respond(['error' => 'Das Voting ist noch nicht geöffnet.'], 403);
}
// Niemand ist exklusiv; eigene pkey nicht erlaubt
if (in_array('__nobody__', $votes, true)) {
$votes = ['__nobody__'];
} else {
$votes = array_values(array_filter($votes, fn($v) => $v !== $pkey));
}
$pdo->prepare(
'UPDATE gtl_players SET vote_for=?, vote_locked=1, updated_at=? WHERE room_code=? AND pkey=?'
)->execute([json_encode($votes), $now, $code, $pkey]);
$pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]);
// Auto-Auswertung wenn alle Spieler abgestimmt haben
$unlocked = $pdo->prepare('SELECT COUNT(*) FROM gtl_players WHERE room_code=? AND vote_locked=0 AND late_join=0');
$unlocked->execute([$code]);
if ((int) $unlocked->fetchColumn() === 0) {
$newState = RoomService::performResolveRound($pdo, $code, $now);
respond(['ok' => true, 'autoResolved' => true, 'state' => $newState]);
}
respond(['ok' => true, 'state' => RoomService::loadRoom($pdo, $code)]);
}
public function resolve_round(): void
{
$pdo = Database::pdo();
$now = time();
$authUserId = $_SESSION['user_id'] ?? null;
// Manueller Trigger durch Host — nutzt den gemeinsamen Helper
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$check = RoomService::loadRoom($pdo, $code);
if ($check === null) respond(['error' => 'Raum nicht gefunden.'], 404);
if (!$check['revealed'] && $check['revealIndex'] < 0) {
respond(['error' => 'Runde noch nicht aufgedeckt.'], 400);
}
$newState = RoomService::performResolveRound($pdo, $code, $now);
respond(['ok' => true, 'state' => $newState]);
}
}

View file

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
/** Admin-Seite: eigenständiges Dokument (noindex) -> ohne Layout. */
final class AdminController extends Controller
{
public function index(): void
{
$this->view('admin', [], false);
}
}

View file

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* SEO-/Content-Seiten. Jede Methode rendert eine Artikel-View im gemeinsamen
* Layout. Neue Seite = View unter app/Views/pages/seo/ + Methode + Route.
*/
final class ContentController extends Controller
{
public function spielanleitung(): void
{
$this->view('seo/spielanleitung', [
'title' => 'Spielanleitung: Black Sheep Bluff einfach erklärt',
'description' => 'Die komplette Spielanleitung für Black Sheep Bluff – Lobby starten, Fragen verteilen, aufdecken, abstimmen. In 5 Minuten startklar.',
'css' => ['content'],
]);
}
public function strategie(): void
{
$this->view('seo/strategie', [
'title' => 'Bluff-Strategie: So entlarvst du das schwarze Schaf',
'description' => 'Taktiken für Innocents und Imposter in Black Sheep Bluff – Fragen stellen, Antworten lesen, clever abstimmen und unauffällig bluffen.',
'css' => ['content'],
]);
}
public function spielvarianten(): void
{
$this->view('seo/spielvarianten', [
'title' => 'Spielvarianten & Hausregeln für Black Sheep Bluff',
'description' => 'Mehr Abwechslung: Team-Modus, mehrere schwarze Schafe, Schnellrunden, Themen-Abende und weitere Hausregeln für Black Sheep Bluff.',
'css' => ['content'],
]);
}
public function faq(): void
{
$this->view('seo/faq', [
'title' => 'FAQ – Häufige Fragen zu Black Sheep Bluff',
'description' => 'Antworten auf die häufigsten Fragen zu Black Sheep Bluff: Spieleranzahl, Kosten, Geräte, Account, Datenschutz und mehr.',
'css' => ['content'],
]);
}
public function partyspiele(): void
{
$this->view('seo/partyspiele', [
'title' => 'Die besten Bluff-Partyspiele für jede Gruppe',
'description' => 'Bluff-Partyspiele im Überblick: Wann sie sich lohnen, worauf es ankommt und warum Black Sheep Bluff für 3–15+ Spieler perfekt ist.',
'css' => ['content'],
]);
}
}

View file

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
final class HomeController extends Controller
{
public function index(): void
{
$this->view('home', [
'title' => 'Black Sheep Bluff – Wer ist das schwarze Schaf?',
'description' => 'Black Sheep Bluff – das Bluff-Partyspiel. Imposters bekommen eine andere Frage. Findet das schwarze Schaf!',
'css' => ['home'],
'js' => ['home'],
]);
}
}

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
final class LegalController extends Controller
{
public function datenschutz(): void
{
$this->view('datenschutz', [
'title' => 'Datenschutz – Black Sheep Bluff',
'description' => 'Datenschutzerklärung von Black Sheep Bluff.',
'css' => ['legal'],
]);
}
public function impressum(): void
{
$this->view('impressum', [
'title' => 'Impressum – Black Sheep Bluff',
'description' => 'Impressum von Black Sheep Bluff.',
'css' => ['legal'],
]);
}
public function notFound(): void
{
$this->view('404', [
'title' => 'Seite nicht gefunden – Black Sheep Bluff',
'description' => '',
'css' => ['legal'],
]);
}
}

View file

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
/** Login-Seite: eigenständiges Dokument (noindex) -> ohne Layout. */
final class LoginController extends Controller
{
public function index(): void
{
$this->view('login', [], false);
}
}

View file

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
/** Spiel-Seite: eigenständiges Dokument (eigene Nav, noindex) -> ohne Layout. */
final class PlayController extends Controller
{
public function index(): void
{
$this->view('play', [], false);
}
}

View file

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
/** Profil-Seite: eigenständiges Dokument (noindex) -> ohne Layout. */
final class ProfileController extends Controller
{
public function index(): void
{
$this->view('profile', [], false);
}
}

View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
final class RegelnController extends Controller
{
public function index(): void
{
$this->view('regeln', [
'title' => 'Spielregeln – Black Sheep Bluff',
'description' => 'Spielregeln von Black Sheep Bluff – so findet ihr das schwarze Schaf.',
'css' => ['regeln'],
]);
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
/** Dynamische sitemap.xml (Domain wird automatisch erkannt). */
final class SitemapController extends Controller
{
public function xml(): void
{
header('Content-Type: application/xml; charset=utf-8');
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$base = $scheme . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
// Nur indexierbare Inhaltsseiten (App-Seiten sind noindex)
$paths = [
'/', '/regeln', '/spielanleitung', '/strategie', '/spielvarianten',
'/faq', '/partyspiele', '/datenschutz', '/impressum',
];
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($paths as $p) {
echo ' <url><loc>' . htmlspecialchars($base . $p, ENT_QUOTES) . '</loc></url>' . "\n";
}
echo '</urlset>' . "\n";
}
}