commit 44e5b48c3c10ae25aa5ad1fdc16de5f16a6ef408 Author: danny Date: Sun Jun 14 12:25:44 2026 +0200 chore: snapshot before branding & feature pass diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..9b2bf47 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,11 @@ +{ + "permissions": { + "allow": [ + "mcp__visualize__read_me", + "mcp__visualize__show_widget", + "Bash(git init *)", + "Bash(git add *)", + "Bash(git commit *)" + ] + } +} diff --git a/admin.php b/admin.php new file mode 100644 index 0000000..bbaf67a --- /dev/null +++ b/admin.php @@ -0,0 +1,305 @@ + + + + + + +Admin – Black Sheep Bluff + + + + + + + +
+ + + + + + +
+

Übersicht

+
+
–
User
+
–
Runden gespielt
+
–
PIN fehlt noch
+
+
+ + +
+

Neuen User anlegen

+
+
+ + +
+ +
+

+ Der User legt beim ersten Login selbst einen PIN fest. Kein Passwort nötig. +

+
+ + +
+
+

Alle User

+ +
+
+

Lade…

+
+
+
+ + + + diff --git a/api.php b/api.php new file mode 100644 index 0000000..3e44e7f --- /dev/null +++ b/api.php @@ -0,0 +1,619 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, + ]); +} + +function respond(array $data, int $status = 200): never +{ + http_response_code($status); + echo json_encode($data, JSON_UNESCAPED_UNICODE); + exit; +} + +function input(): array +{ + $raw = file_get_contents('php://input') ?: ''; + $data = json_decode($raw, true); + return is_array($data) ? $data : []; +} + +function slugCode(string $value): string +{ + return substr(preg_replace('/[^A-Z0-9]/', '', strtoupper($value)) ?? '', 0, 12); +} + +function playerKey(string $name): string +{ + return substr(preg_replace('/[^a-z0-9]/', '_', strtolower($name)) ?? '', 0, 40); +} + +function loadRoom(PDO $pdo, string $code): ?array +{ + $stmt = $pdo->prepare( + 'SELECT code, revealed, liar_keys, normal_question, imposter_question, + round_num, voted_out_keys, round_outcome, voting_open + FROM gtl_rooms WHERE code = ?' + ); + $stmt->execute([$code]); + $room = $stmt->fetch(); + if ($room === false) return null; + + $j = fn($v) => (!empty($v) && is_string($v)) ? (json_decode($v, true) ?: []) : []; + + + $ps = $pdo->prepare( + 'SELECT p.pkey, p.name, p.user_id, p.question, p.answer, p.answered, p.score, p.vote_for, + u.avatar + FROM gtl_players p + LEFT JOIN gtl_users u ON u.id = p.user_id + WHERE p.room_code = ? ORDER BY p.id ASC' + ); + $ps->execute([$code]); + + $players = []; + foreach ($ps->fetchAll() as $row) { + $players[$row['pkey']] = [ + 'pkey' => $row['pkey'], + 'name' => $row['name'], + 'userId' => $row['user_id'] ? (int) $row['user_id'] : null, + 'avatar' => $row['avatar'] ?? null, + 'question' => $row['question'] ?? '', + 'answer' => $row['answer'] ?? '', + 'answered' => (bool) $row['answered'], + 'score' => (int) $row['score'], + 'voteFor' => $row['vote_for'] ?? '', + ]; + } + + $outcome = $room['round_outcome'] ?? null; + + return [ + 'code' => $room['code'], + 'revealed' => (bool) $room['revealed'], + // liarKeys only sent after resolution — prevents clients from seeing imposters early + 'liarKeys' => $outcome ? $j($room['liar_keys']) : [], + 'normalQuestion' => $room['normal_question'] ?? '', + 'imposterQuestion' => $room['imposter_question'] ?? '', + 'roundNum' => (int) $room['round_num'], + 'votedOutKeys' => $j($room['voted_out_keys']), + 'roundOutcome' => $outcome, + 'votingOpen' => (bool) ($room['voting_open'] ?? false), + 'players' => $players, + ]; +} + +/** + * Bestimmt, wer herausgewählt wurde. + * + * Regeln: + * - Nur Niemand hat Max-Stimmen → niemand raus + * - Tie Niemand + User, User ist Imposter → Imposter raus + * - Tie Niemand + User, User ist kein Imposter → niemand raus (Tie geht an Niemand) + * - Tie zwischen echten Spielern (ohne Niemand) → alle raus + * + * @param array> $players + * @param array $liarKeys + * @return array pkeys der herausgewählten Spieler + */ +function resolveVotes(array $players, array $liarKeys): array +{ + $tally = ['__nobody__' => 0]; + foreach ($players as $p) { + $tally[$p['pkey']] = 0; + } + foreach ($players as $p) { + $vf = $p['voteFor'] ?? ''; + if ($vf === '' || $vf === '__nobody__') { + $tally['__nobody__']++; + } elseif (array_key_exists($vf, $tally)) { + $tally[$vf]++; + } + } + + $max = max($tally); + if ($max === 0) return []; + + $top = array_keys(array_filter($tally, fn($v) => $v === $max)); + + // Nur Niemand → niemand raus + if ($top === ['__nobody__']) { + return []; + } + + $hasNobody = in_array('__nobody__', $top, true); + $realCandidates = array_values(array_filter($top, fn($k) => $k !== '__nobody__')); + + if (!$hasNobody) { + // Reiner Tie zwischen echten Spielern → alle raus + return $realCandidates; + } + + // Tie Niemand + Spieler: nur Imposters unter den Tied fliegen raus + // (Innocent überlebt den Tie mit Niemand) + return array_values(array_filter($realCandidates, fn($pk) => in_array($pk, $liarKeys, true))); +} + +/** + * Archiviert die aktuelle Runde in gtl_game_rounds + gtl_round_players. + * Idempotent: läuft resolve_round vorher, wird nur outcome aktualisiert. + * Stats werden NICHT hier aktualisiert (nur in resolve_round). + */ +function archiveRound(PDO $pdo, array $state, int $now): void +{ + $code = $state['code']; + $roundNum = $state['roundNum']; + $outcome = $state['roundOutcome'] ?: null; + $liarKeys = $state['liarKeys']; + $votedOut = $state['votedOutKeys']; + + $existing = $pdo->prepare('SELECT id FROM gtl_game_rounds WHERE room_code=? AND round_num=?'); + $existing->execute([$code, $roundNum]); + $row = $existing->fetch(); + + if ($row) { + // Nur Outcome aktualisieren falls noch nicht gesetzt + if ($outcome && !$pdo->query("SELECT outcome FROM gtl_game_rounds WHERE id={$row['id']}")->fetchColumn()) { + $pdo->prepare('UPDATE gtl_game_rounds SET outcome=? WHERE id=?') + ->execute([$outcome, $row['id']]); + } + return; // Spieler bereits archiviert + } + + $pdo->prepare('INSERT INTO gtl_game_rounds (room_code, round_num, played_at, outcome) VALUES (?,?,?,?)') + ->execute([$code, $roundNum, $now, $outcome]); + $roundId = (int) $pdo->lastInsertId(); + + $ins = $pdo->prepare( + 'INSERT IGNORE INTO gtl_round_players + (round_id, user_id, player_name, pkey, was_imposter, voted_out, question, answer) + VALUES (?,?,?,?,?,?,?,?)' + ); + foreach ($state['players'] as $p) { + $ins->execute([ + $roundId, + $p['userId'], + $p['name'], + $p['pkey'], + in_array($p['pkey'], $liarKeys, true) ? 1 : 0, + in_array($p['pkey'], $votedOut, true) ? 1 : 0, + $p['question'], + $p['answer'], + ]); + } +} + +$cfg = require __DIR__ . '/config.php'; + +try { + $pdo = db($cfg); + runMigrations($pdo, $cfg['dbname']); +} catch (Throwable $e) { + respond(['error' => 'DB-Verbindung fehlgeschlagen: ' . $e->getMessage()], 500); +} + +$action = $_GET['action'] ?? ''; +$now = time(); +$authUserId = $_SESSION['user_id'] ?? null; + +try { + switch ($action) { + + case 'host_open': + $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' => loadRoom($pdo, $code)]); + break; + + case 'player_join': + 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]); + + respond(['ok' => true, 'pkey' => $pkey, 'state' => loadRoom($pdo, $code)]); + break; + + case 'state': + $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]); + // Lazy cleanup: delete rooms inactive for 12+ hours + $pdo->exec('DELETE FROM gtl_rooms WHERE updated_at < ' . ($now - 43200)); + $state = loadRoom($pdo, $code); + if ($state === null) respond(['error' => 'Raum nicht gefunden.'], 404); + respond(['ok' => true, 'state' => $state]); + break; + + case 'delete_room': + $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]); + break; + + case 'assign_questions': + $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, 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=?, 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' => loadRoom($pdo, $code)]); + break; + + case 'submit_answer': + $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]); + respond(['ok' => true]); + break; + + case 'delete_answer': + $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' => loadRoom($pdo, $code)]); + break; + + case 'reveal': + $body = input(); + $code = slugCode((string) ($body['code'] ?? '')); + $pdo->prepare('UPDATE gtl_rooms SET revealed=1, updated_at=? WHERE code=?') + ->execute([$now, $code]); + respond(['ok' => true]); + break; + + case 'open_voting': + $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' => loadRoom($pdo, $code)]); + break; + + case 'vote': + $body = input(); + $code = slugCode((string) ($body['code'] ?? '')); + $pkey = (string) ($body['pkey'] ?? ''); + $voteFor = (string) ($body['voteFor'] ?? ''); + + // Voting gesperrt prüfen + $vCheck = $pdo->prepare('SELECT voting_open FROM gtl_rooms WHERE code=?'); + $vCheck->execute([$code]); + $vRow = $vCheck->fetch(); + if (!$vRow || !$vRow['voting_open']) { + respond(['error' => 'Das Voting ist noch nicht geöffnet.'], 403); + } + + if ($voteFor !== '__nobody__' && $voteFor === $pkey) respond(['error' => 'Du kannst nicht für dich selbst stimmen.'], 400); + + $pdo->prepare( + 'UPDATE gtl_players SET vote_for=?, updated_at=? WHERE room_code=? AND pkey=?' + )->execute([$voteFor !== '' ? $voteFor : null, $now, $code, $pkey]); + respond(['ok' => true]); + break; + + case 'resolve_round': + $body = input(); + $code = slugCode((string) ($body['code'] ?? '')); + $state = loadRoom($pdo, $code); + if ($state === null) respond(['error' => 'Raum nicht gefunden.'], 404); + if (!$state['revealed']) respond(['error' => 'Runde noch nicht aufgedeckt.'], 400); + + $players = $state['players']; + $liarKeys = $state['liarKeys']; + $votedOut = resolveVotes(array_values($players), $liarKeys); + + // Outcome-Logik: + // - Niemand hatte Max + kein Imposter gesetzt → innocents_win + // - Niemand hatte Max + Imposter exist. → imposters_win + // - Alle Imposters rausgewählt → innocents_win + // - Mind. 1 Imposter überlebt → imposters_win + if (empty($liarKeys)) { + // Kein Imposter gesetzt: bei voting war niemand der Böse + // Niemand gewinnt = Spiel war "clean" + $outcome = 'no_liar'; + } elseif (empty($votedOut)) { + // Niemand rausgewählt UND es gibt Imposters → Imposters gewinnen + $outcome = 'imposters_win'; + } elseif (empty(array_diff($liarKeys, $votedOut))) { + // Alle Imposters raus → Innocents gewinnen + $outcome = 'innocents_win'; + } else { + // Mind. 1 Imposter überlebt + $outcome = 'imposters_win'; + } + + $pdo->prepare( + 'UPDATE gtl_rooms SET voted_out_keys=?, round_outcome=?, updated_at=? WHERE code=?' + )->execute([json_encode($votedOut), $outcome, $now, $code]); + + // Verlauf speichern + $existing = $pdo->prepare('SELECT id FROM gtl_game_rounds WHERE room_code=? AND round_num=?'); + $existing->execute([$code, $state['roundNum']]); + $existingRow = $existing->fetch(); + + if ($existingRow) { + $roundId = (int) $existingRow['id']; + $pdo->prepare('UPDATE gtl_game_rounds SET outcome=? WHERE id=?') + ->execute([$outcome, $roundId]); + $pdo->prepare('UPDATE gtl_round_players SET voted_out=? WHERE round_id=? AND pkey=?'); + // Update voted_out for each player + $updVo = $pdo->prepare('UPDATE gtl_round_players SET voted_out=? WHERE round_id=? AND pkey=?'); + foreach ($players as $p) { + $updVo->execute([in_array($p['pkey'], $votedOut, true) ? 1 : 0, $roundId, $p['pkey']]); + } + } else { + $pdo->prepare('INSERT INTO gtl_game_rounds (room_code, round_num, played_at, outcome) VALUES (?,?,?,?)') + ->execute([$code, $state['roundNum'], $now, $outcome]); + $roundId = (int) $pdo->lastInsertId(); + + $ins = $pdo->prepare( + 'INSERT IGNORE INTO gtl_round_players + (round_id, user_id, player_name, pkey, was_imposter, voted_out, question, answer) + VALUES (?,?,?,?,?,?,?,?)' + ); + foreach ($players as $p) { + $ins->execute([ + $roundId, $p['userId'], $p['name'], $p['pkey'], + in_array($p['pkey'], $liarKeys, true) ? 1 : 0, + in_array($p['pkey'], $votedOut, true) ? 1 : 0, + $p['question'], $p['answer'], + ]); + } + } + + // Statistiken aktualisieren + $updStats = $pdo->prepare( + 'UPDATE gtl_user_stats SET + games_played = games_played + 1, + games_won = games_won + ?, + games_lost = games_lost + ?, + times_imposter = times_imposter + ?, + imposter_wins = imposter_wins + ?, + imposter_losses = imposter_losses + ?, + innocent_wins = innocent_wins + ?, + innocent_losses = innocent_losses + ? + WHERE user_id = ?' + ); + + $updScore = $pdo->prepare( + 'UPDATE gtl_players SET score=score+1, updated_at=? WHERE room_code=? AND pkey=?' + ); + + foreach ($players as $p) { + $wasImposter = in_array($p['pkey'], $liarKeys, true); + $wasVotedOut = in_array($p['pkey'], $votedOut, true); + + if ($wasImposter) { + $playerWon = !$wasVotedOut; + } else { + $playerWon = ($outcome === 'innocents_win'); + } + + // Automatische Punktevergabe + if ($playerWon) { + $updScore->execute([$now, $code, $p['pkey']]); + } + + // Profil-Statistiken (nur für eingeloggte User) + if (!$p['userId']) continue; + + $updStats->execute([ + $playerWon ? 1 : 0, + $playerWon ? 0 : 1, + $wasImposter ? 1 : 0, + $wasImposter && $playerWon ? 1 : 0, + $wasImposter && !$playerWon ? 1 : 0, + !$wasImposter && $playerWon ? 1 : 0, + !$wasImposter && !$playerWon ? 1 : 0, + $p['userId'], + ]); + } + + respond(['ok' => true, 'state' => loadRoom($pdo, $code)]); + break; + + case 'get_host_history': + $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)]); + break; + + case 'score': + $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]); + break; + + case 'new_round': + $body = input(); + $code = slugCode((string) ($body['code'] ?? '')); + $state = loadRoom($pdo, $code); + + // Aktuelle Runde zuerst archivieren (falls noch nicht geschehen) + if ($state && !empty($state['players'])) { + 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, + 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, updated_at=? + WHERE room_code=?' + )->execute([$now, $code]); + + respond(['ok' => true, 'state' => loadRoom($pdo, $code)]); + break; + + case 'remove_player': + $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]); + break; + + case 'reset_scores': + $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]); + break; + + default: + respond(['error' => 'Unbekannte Aktion.'], 400); + } +} catch (Throwable $e) { + respond(['error' => 'Serverfehler: ' . $e->getMessage()], 500); +} diff --git a/auth.php b/auth.php new file mode 100644 index 0000000..31fa4b6 --- /dev/null +++ b/auth.php @@ -0,0 +1,388 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, + ]); +} + +/** @param array $data */ +function respond(array $data, int $status = 200): never +{ + http_response_code($status); + echo json_encode($data, JSON_UNESCAPED_UNICODE); + exit; +} + +/** @return array */ +function input(): array +{ + $raw = file_get_contents('php://input') ?: ''; + $data = json_decode($raw, true); + return is_array($data) ? $data : []; +} + +function requireAuth(PDO $pdo): array +{ + if (empty($_SESSION['user_id'])) { + respond(['error' => 'Nicht eingeloggt.'], 401); + } + $stmt = $pdo->prepare('SELECT id, username, avatar, role FROM gtl_users WHERE id = ?'); + $stmt->execute([$_SESSION['user_id']]); + $user = $stmt->fetch(); + if (!$user) { + session_destroy(); + respond(['error' => 'Session ungültig.'], 401); + } + return $user; +} + +function requireAdmin(PDO $pdo): void +{ + $user = requireAuth($pdo); + if ($user['role'] !== 'admin') { + respond(['error' => 'Keine Berechtigung.'], 403); + } +} + +function publicUser(array $row): array +{ + return [ + 'id' => (int) $row['id'], + 'username' => $row['username'], + 'avatar' => $row['avatar'] ?? null, + 'role' => $row['role'], + ]; +} + +$cfg = require __DIR__ . '/config.php'; + +try { + $pdo = db($cfg); + runMigrations($pdo, $cfg['dbname']); +} catch (Throwable $e) { + respond(['error' => 'DB-Verbindung fehlgeschlagen.'], 500); +} + +$action = $_GET['action'] ?? ''; + +try { + switch ($action) { + + // ── Wer bin ich? ───────────────────────────────────────────── + case 'me': + 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 ? publicUser($user) : null]); + break; + + // ── Username prüfen (Step 1 des Logins) ────────────────────── + case 'check_username': + $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'), + ]); + break; + + // ── Login ───────────────────────────────────────────────────── + case 'login': + $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' => publicUser($user)]); + break; + + // ── PIN erstmalig setzen (First-Login) ──────────────────────── + case 'set_pin': + $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' => publicUser($user)]); + break; + + // ── PIN / Passwort ändern ───────────────────────────────────── + case 'change_credential': + $me = 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]); + break; + + // ── Logout ──────────────────────────────────────────────────── + case 'logout': + session_destroy(); + respond(['ok' => true]); + break; + + // ── User anlegen (Admin) ────────────────────────────────────── + case 'create_user': + 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; + } + break; + + // ── PIN zurücksetzen (Admin) ─────────────────────────────────── + case 'reset_pin': + 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]); + break; + + // ── User löschen (Admin) ────────────────────────────────────── + case 'delete_user': + 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]); + break; + + // ── Alle User abrufen (Admin) ───────────────────────────────── + case 'get_users': + 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()]); + break; + + // ── Profil abrufen ──────────────────────────────────────────── + case 'get_profile': + $me = requireAuth($pdo); + + $stmt = $pdo->prepare( + 'SELECT u.id, u.username, u.avatar, u.role, u.created_at, u.last_login, + 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]); + break; + + // ── Spielhistorie ───────────────────────────────────────────── + case 'get_history': + $me = 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]); + break; + + // ── Avatar hochladen ────────────────────────────────────────── + case 'upload_avatar': + $me = 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 = __DIR__ . '/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]); + break; + + default: + respond(['error' => 'Unbekannte Aktion.'], 400); + } +} catch (Throwable $e) { + respond(['error' => 'Serverfehler: ' . $e->getMessage()], 500); +} diff --git a/config.php b/config.php new file mode 100644 index 0000000..91f2895 --- /dev/null +++ b/config.php @@ -0,0 +1,15 @@ + deine DB -> Benutzer. + */ +return [ + 'host' => 'localhost', + 'dbname' => 'DEINE_DATENBANK', + 'user' => 'DEIN_DB_USER', + 'pass' => 'DEIN_DB_PASSWORT', + 'charset' => 'utf8mb4', +]; diff --git a/idetity/Gemini_Generated_Image_jhrp20jhrp20jhrp.png b/idetity/Gemini_Generated_Image_jhrp20jhrp20jhrp.png new file mode 100644 index 0000000..4e87490 Binary files /dev/null and b/idetity/Gemini_Generated_Image_jhrp20jhrp20jhrp.png differ diff --git a/idetity/favicon.png b/idetity/favicon.png new file mode 100644 index 0000000..c3371f2 Binary files /dev/null and b/idetity/favicon.png differ diff --git a/idetity/favicon.psd b/idetity/favicon.psd new file mode 100644 index 0000000..536470a Binary files /dev/null and b/idetity/favicon.psd differ diff --git a/idetity/logo.png b/idetity/logo.png new file mode 100644 index 0000000..9d8651d Binary files /dev/null and b/idetity/logo.png differ diff --git a/idetity/logo.psd b/idetity/logo.psd new file mode 100644 index 0000000..569e94f Binary files /dev/null and b/idetity/logo.psd differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..7e3d715 --- /dev/null +++ b/index.html @@ -0,0 +1,914 @@ + + + + + + +Black Sheep Bluff – Guess the Imposter + + + + + + + +
+ + +
+ +

Imposters bekommen eine andere Frage. Findet sie!

+
+ + + + +
+
+

Mitspielen

+ + + + + +
+
+

Spielleiter

+ + + + + +

Beim ersten Mal legt das Passwort den Raum an. Danach brauchst du es zum Wiederbetreten.

+
+
+ + + + + + +
+ + + + diff --git a/login.php b/login.php new file mode 100644 index 0000000..8d72df1 --- /dev/null +++ b/login.php @@ -0,0 +1,238 @@ + + + + + + +Login – Black Sheep Bluff + + + + + + + +
+
+ +

Melde dich an

+
+ +
+ + + +
+

Schritt 1 — Username eingeben

+ + + +
+ + + + + + + + + +
+
+ + + + diff --git a/migrate.php b/migrate.php new file mode 100644 index 0000000..83673de --- /dev/null +++ b/migrate.php @@ -0,0 +1,178 @@ +exec("CREATE TABLE IF NOT EXISTS `gtl_migrations` ( + `version` INT UNSIGNED NOT NULL, + `applied_at` INT UNSIGNED NOT NULL, + PRIMARY KEY (`version`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + + $current = (int) $pdo->query("SELECT COALESCE(MAX(version),0) FROM gtl_migrations")->fetchColumn(); + if ($current >= LATEST_MIGRATION) return; + + // ── V1: Basis-Tabellen ──────────────────────────────────── + if ($current < 1) { + $pdo->exec("CREATE TABLE IF NOT EXISTS `gtl_rooms` ( + `code` VARCHAR(12) NOT NULL, + `pass_hash` VARCHAR(255) NOT NULL, + `revealed` TINYINT(1) NOT NULL DEFAULT 0, + `created_at` INT UNSIGNED NOT NULL, + `updated_at` INT UNSIGNED NOT NULL, + PRIMARY KEY (`code`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + + $pdo->exec("CREATE TABLE IF NOT EXISTS `gtl_players` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `room_code` VARCHAR(12) NOT NULL, + `pkey` VARCHAR(40) NOT NULL, + `name` VARCHAR(40) NOT NULL, + `question` TEXT NULL, + `answer` TEXT NULL, + `answered` TINYINT(1) NOT NULL DEFAULT 0, + `score` INT NOT NULL DEFAULT 0, + `updated_at`INT UNSIGNED NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_room_player` (`room_code`,`pkey`), + CONSTRAINT `fk_player_room` FOREIGN KEY (`room_code`) + REFERENCES `gtl_rooms`(`code`) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + + markMigration($pdo, 1); + } + + // ── V2: Neue Spalten + User/Statistik/Verlauf-Tabellen ─── + if ($current < 2) { + // gtl_rooms + addColumnIfMissing($pdo, $dbname, 'gtl_rooms', 'liar_keys', 'TEXT NULL AFTER revealed'); + addColumnIfMissing($pdo, $dbname, 'gtl_rooms', 'normal_question', 'TEXT NULL AFTER liar_keys'); + addColumnIfMissing($pdo, $dbname, 'gtl_rooms', 'imposter_question', 'TEXT NULL AFTER normal_question'); + addColumnIfMissing($pdo, $dbname, 'gtl_rooms', 'round_num', 'INT UNSIGNED NOT NULL DEFAULT 1 AFTER imposter_question'); + addColumnIfMissing($pdo, $dbname, 'gtl_rooms', 'voted_out_keys', 'TEXT NULL AFTER round_num'); + addColumnIfMissing($pdo, $dbname, 'gtl_rooms', 'round_outcome', 'VARCHAR(20) NULL AFTER voted_out_keys'); + dropColumnIfExists($pdo, $dbname, 'gtl_rooms', 'liar_key'); // legacy + + // gtl_players + addColumnIfMissing($pdo, $dbname, 'gtl_players', 'user_id', 'INT UNSIGNED NULL AFTER name'); + addColumnIfMissing($pdo, $dbname, 'gtl_players', 'vote_for', 'VARCHAR(40) NULL AFTER score'); + + // gtl_users + $pdo->exec("CREATE TABLE IF NOT EXISTS `gtl_users` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `username` VARCHAR(40) NOT NULL, + `credential_hash` VARCHAR(255) NULL, + `avatar` VARCHAR(255) NULL, + `role` ENUM('admin','user') NOT NULL DEFAULT 'user', + `created_at` INT UNSIGNED NOT NULL, + `last_login` INT UNSIGNED NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_username` (`username`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + + // gtl_user_stats + $pdo->exec("CREATE TABLE IF NOT EXISTS `gtl_user_stats` ( + `user_id` INT UNSIGNED NOT NULL, + `games_played` INT UNSIGNED NOT NULL DEFAULT 0, + `games_won` INT UNSIGNED NOT NULL DEFAULT 0, + `games_lost` INT UNSIGNED NOT NULL DEFAULT 0, + `times_imposter` INT UNSIGNED NOT NULL DEFAULT 0, + `imposter_wins` INT UNSIGNED NOT NULL DEFAULT 0, + `imposter_losses` INT UNSIGNED NOT NULL DEFAULT 0, + `innocent_wins` INT UNSIGNED NOT NULL DEFAULT 0, + `innocent_losses` INT UNSIGNED NOT NULL DEFAULT 0, + PRIMARY KEY (`user_id`), + CONSTRAINT `fk_stats_user` FOREIGN KEY (`user_id`) REFERENCES `gtl_users`(`id`) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + + // gtl_game_rounds + $pdo->exec("CREATE TABLE IF NOT EXISTS `gtl_game_rounds` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `room_code` VARCHAR(12) NOT NULL, + `round_num` INT UNSIGNED NOT NULL DEFAULT 1, + `played_at` INT UNSIGNED NOT NULL, + `outcome` VARCHAR(20) NULL, + PRIMARY KEY (`id`), + KEY `idx_room` (`room_code`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + + // gtl_round_players + $pdo->exec("CREATE TABLE IF NOT EXISTS `gtl_round_players` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `round_id` INT UNSIGNED NOT NULL, + `user_id` INT UNSIGNED NULL, + `player_name` VARCHAR(40) NOT NULL, + `pkey` VARCHAR(40) NOT NULL, + `was_imposter`TINYINT(1) NOT NULL DEFAULT 0, + `voted_out` TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_round_player` (`round_id`,`pkey`), + CONSTRAINT `fk_rp_round` FOREIGN KEY (`round_id`) REFERENCES `gtl_game_rounds`(`id`) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + + markMigration($pdo, 2); + } + + // ── V3: Antworten + Fragen im Verlauf speichern ────────── + if ($current < 3) { + addColumnIfMissing($pdo, $dbname, 'gtl_round_players', 'question', 'TEXT NULL AFTER voted_out'); + addColumnIfMissing($pdo, $dbname, 'gtl_round_players', 'answer', 'TEXT NULL AFTER question'); + markMigration($pdo, 3); + } + + // ── V4: uploads-Verzeichnis anlegen ────────────────────── + if ($current < 4) { + $dir = __DIR__ . '/uploads/avatars'; + if (!is_dir($dir)) { + mkdir($dir, 0755, true); + } + markMigration($pdo, 4); + } + + // ── V5: Voting-Steuerung ────────────────────────────────── + if ($current < 5) { + addColumnIfMissing($pdo, $dbname, 'gtl_rooms', 'voting_open', + 'TINYINT(1) NOT NULL DEFAULT 0 AFTER round_outcome'); + markMigration($pdo, 5); + } +} + +// ── Hilfsfunktionen ────────────────────────────────────────── + +function columnExists(PDO $pdo, string $db, string $table, string $col): bool +{ + $stmt = $pdo->prepare( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME=?" + ); + $stmt->execute([$db, $table, $col]); + return (int) $stmt->fetchColumn() > 0; +} + +function addColumnIfMissing(PDO $pdo, string $db, string $table, string $col, string $def): void +{ + if (!columnExists($pdo, $db, $table, $col)) { + $pdo->exec("ALTER TABLE `$table` ADD COLUMN `$col` $def"); + } +} + +function dropColumnIfExists(PDO $pdo, string $db, string $table, string $col): void +{ + if (columnExists($pdo, $db, $table, $col)) { + $pdo->exec("ALTER TABLE `$table` DROP COLUMN `$col`"); + } +} + +function markMigration(PDO $pdo, int $version): void +{ + $pdo->prepare("INSERT IGNORE INTO gtl_migrations (version, applied_at) VALUES (?,?)") + ->execute([$version, time()]); +} diff --git a/profile.php b/profile.php new file mode 100644 index 0000000..3f7552c --- /dev/null +++ b/profile.php @@ -0,0 +1,467 @@ + + + + + + +Profil – Black Sheep Bluff + + + + + + + + + + + +
+
+
+
✏️
+
+
…
+
+ user + +
+ +
+ +
+ + + + +
+

Statistiken

+
+
🎮
–
Gespielt
+
🏆
–
Gewonnen
+
💀
–
Verloren
+
🐑
–
Mal Imposter
+
🗡️
–
Imposter Wins
+
🛡️
–
Innocent Wins
+
+ +
+ +
+
+
Gesamt0%
+
+
+
+
Als Imposter0%
+
+
+
+
Als Innocent0%
+
+
+
+
+ + +
+

Profilbild ändern

+
+ 🖼️ + Bild hierher ziehen oder klicken zum Auswählen
+ JPEG · PNG · WebP · max 2 MB +
+
+ + +
+

PIN ändern

+ + + + + + +
+ + +
+

Spielhistorie

+

Lade…

+ +
+ + +
+ + + + diff --git a/schema.sql b/schema.sql new file mode 100644 index 0000000..e63b7ad --- /dev/null +++ b/schema.sql @@ -0,0 +1,124 @@ +-- ============================================================ +-- Guess the Liar – vollständiges Datenbankschema v2 +-- Import: mysql -u USER -p DBNAME < schema.sql +-- ============================================================ +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ── Benutzer ───────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS `gtl_users` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `username` VARCHAR(40) NOT NULL, + `credential_hash` VARCHAR(255) NULL COMMENT 'NULL bis PIN erstmals gesetzt; Admin nutzt Passwort-Hash', + `avatar` VARCHAR(255) NULL COMMENT 'Dateiname in uploads/avatars/', + `role` ENUM('admin','user') NOT NULL DEFAULT 'user', + `created_at` INT UNSIGNED NOT NULL, + `last_login` INT UNSIGNED NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_username` (`username`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- ── Statistiken ─────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS `gtl_user_stats` ( + `user_id` INT UNSIGNED NOT NULL, + `games_played` INT UNSIGNED NOT NULL DEFAULT 0, + `games_won` INT UNSIGNED NOT NULL DEFAULT 0, + `games_lost` INT UNSIGNED NOT NULL DEFAULT 0, + `times_imposter` INT UNSIGNED NOT NULL DEFAULT 0, + `imposter_wins` INT UNSIGNED NOT NULL DEFAULT 0, + `imposter_losses` INT UNSIGNED NOT NULL DEFAULT 0, + `innocent_wins` INT UNSIGNED NOT NULL DEFAULT 0, + `innocent_losses` INT UNSIGNED NOT NULL DEFAULT 0, + PRIMARY KEY (`user_id`), + CONSTRAINT `fk_stats_user` + FOREIGN KEY (`user_id`) REFERENCES `gtl_users` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- ── Spielrunden-Historie ────────────────────────────────────── +CREATE TABLE IF NOT EXISTS `gtl_game_rounds` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `room_code` VARCHAR(12) NOT NULL, + `round_num` INT UNSIGNED NOT NULL DEFAULT 1, + `played_at` INT UNSIGNED NOT NULL, + `outcome` VARCHAR(20) NULL COMMENT 'innocents_win | imposters_win | no_liar', + PRIMARY KEY (`id`), + KEY `idx_room` (`room_code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- ── Spieler einer Runde ─────────────────────────────────────── +CREATE TABLE IF NOT EXISTS `gtl_round_players` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `round_id` INT UNSIGNED NOT NULL, + `user_id` INT UNSIGNED NULL, + `player_name` VARCHAR(40) NOT NULL, + `pkey` VARCHAR(40) NOT NULL, + `was_imposter`TINYINT(1) NOT NULL DEFAULT 0, + `voted_out` TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + CONSTRAINT `fk_rp_round` + FOREIGN KEY (`round_id`) REFERENCES `gtl_game_rounds` (`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- ── Räume ───────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS `gtl_rooms` ( + `code` VARCHAR(12) NOT NULL, + `pass_hash` VARCHAR(255) NOT NULL, + `revealed` TINYINT(1) NOT NULL DEFAULT 0, + `liar_keys` TEXT NULL COMMENT 'JSON-Array der Imposter-pkeys', + `normal_question` TEXT NULL, + `imposter_question` TEXT NULL, + `round_num` INT UNSIGNED NOT NULL DEFAULT 1, + `voted_out_keys` TEXT NULL COMMENT 'JSON-Array: wer herausgewählt wurde', + `round_outcome` VARCHAR(20) NULL COMMENT 'innocents_win | imposters_win | no_liar', + `created_at` INT UNSIGNED NOT NULL, + `updated_at` INT UNSIGNED NOT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- ── Spieler ─────────────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS `gtl_players` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `room_code` VARCHAR(12) NOT NULL, + `pkey` VARCHAR(40) NOT NULL, + `name` VARCHAR(40) NOT NULL, + `user_id` INT UNSIGNED NULL, + `question` TEXT NULL, + `answer` TEXT NULL, + `answered` TINYINT(1) NOT NULL DEFAULT 0, + `score` INT NOT NULL DEFAULT 0, + `vote_for` VARCHAR(40) NULL, + `updated_at`INT UNSIGNED NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uniq_room_player` (`room_code`, `pkey`), + CONSTRAINT `fk_player_room` + FOREIGN KEY (`room_code`) REFERENCES `gtl_rooms` (`code`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +SET FOREIGN_KEY_CHECKS = 1; + + +-- ============================================================ +-- MIGRATION (wenn du v1-Schema bereits importiert hattest) +-- ============================================================ +-- Neue User-Tabellen: +-- (s. o. – einfach dieses Schema frisch importieren, wenn +-- keine Daten verloren gehen sollen) +-- +-- Neue Spalten in bestehenden Tabellen (einzeln ausführen): +-- +-- ALTER TABLE gtl_rooms +-- ADD COLUMN liar_keys TEXT NULL AFTER revealed, +-- ADD COLUMN normal_question TEXT NULL AFTER liar_keys, +-- ADD COLUMN imposter_question TEXT NULL AFTER normal_question, +-- ADD COLUMN round_num INT UNSIGNED NOT NULL DEFAULT 1 AFTER imposter_question, +-- ADD COLUMN voted_out_keys TEXT NULL AFTER round_num, +-- ADD COLUMN round_outcome VARCHAR(20) NULL AFTER voted_out_keys; +-- +-- -- Falls liar_key (VARCHAR) noch vorhanden: +-- UPDATE gtl_rooms SET liar_keys = JSON_ARRAY(liar_key) +-- WHERE liar_key IS NOT NULL AND liar_key != ''; +-- ALTER TABLE gtl_rooms DROP COLUMN liar_key; +-- +-- ALTER TABLE gtl_players +-- ADD COLUMN user_id INT UNSIGNED NULL AFTER name, +-- ADD COLUMN vote_for VARCHAR(40) NULL AFTER score; diff --git a/setup.php b/setup.php new file mode 100644 index 0000000..ba4e6ba --- /dev/null +++ b/setup.php @@ -0,0 +1,113 @@ + PDO::ERRMODE_EXCEPTION, + PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, + PDO::ATTR_EMULATE_PREPARES => false, + ]); +} + +$error = $success = ''; + +if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $adminUser = trim($_POST['username'] ?? ''); + $adminPass = $_POST['password'] ?? ''; + $adminPass2 = $_POST['password2'] ?? ''; + + if (!preg_match('/^[a-zA-Z0-9_\-]{2,40}$/', $adminUser)) { + $error = 'Username: 2–40 Zeichen, nur Buchstaben/Zahlen/_/-'; + } elseif (strlen($adminPass) < 8) { + $error = 'Passwort muss mindestens 8 Zeichen haben.'; + } elseif ($adminPass !== $adminPass2) { + $error = 'Passwörter stimmen nicht überein.'; + } else { + try { + $pdo = db($cfg); + $check = $pdo->prepare("SELECT id FROM gtl_users WHERE role = 'admin' LIMIT 1"); + $check->execute(); + if ($check->fetch()) { + $error = 'Admin-Konto existiert bereits. Setup-Datei löschen!'; + } else { + $hash = password_hash($adminPass, PASSWORD_DEFAULT); + $now = time(); + $ins = $pdo->prepare( + "INSERT INTO gtl_users (username, credential_hash, role, created_at) + VALUES (?, ?, 'admin', ?)" + ); + $ins->execute([$adminUser, $hash, $now]); + $uid = $pdo->lastInsertId(); + $pdo->prepare("INSERT INTO gtl_user_stats (user_id) VALUES (?)")->execute([$uid]); + + // Create uploads directory + $dir = __DIR__ . '/uploads/avatars'; + if (!is_dir($dir)) { + mkdir($dir, 0755, true); + } + + $success = 'Admin-Konto „' . htmlspecialchars($adminUser) . '" erfolgreich angelegt! Lösche diese Datei jetzt.'; + } + } catch (Throwable $e) { + $error = 'DB-Fehler: ' . $e->getMessage(); + } + } +} +?> + + + + + +Setup – Guess the Liar + + + +
+

🎭 Admin-Setup

+

Legt das erste Admin-Konto an. Danach diese Datei löschen!

+
+
+ +
+ + + + + + + +
+ +
⚠️ Diese Datei nach dem Setup löschen oder per .htaccess sperren!
+
+ +