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, active_emojis 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), 'activeEmojis' => array_values(array_filter( $j($room['active_emojis'] ?? '[]'), fn($e) => ($e['ts'] ?? 0) >= (time() - 4) )), '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]); $pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]); 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 'send_emoji': $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]); 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]); $pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]); 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); }