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, bool $revealLiars = false): ?array { $stmt = $pdo->prepare( 'SELECT code, revealed, liar_keys, normal_question, imposter_question, round_num, voted_out_keys, round_outcome, voting_open, active_emojis, reveal_index, revealed_keys, imposter_weights, questions_revealed 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, p.vote_locked, p.vote_request, p.late_join, u.avatar, u.color, u.sticker 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) { // Parse vote_for: JSON array (new) or legacy single pkey string $voteRaw = $row['vote_for'] ?? null; if ($voteRaw !== null && str_starts_with(ltrim((string) $voteRaw), '[')) { $parsedVotes = json_decode($voteRaw, true) ?: []; } elseif ($voteRaw !== null && $voteRaw !== '') { $parsedVotes = [$voteRaw]; } else { $parsedVotes = []; } $players[$row['pkey']] = [ 'pkey' => $row['pkey'], 'name' => $row['name'], 'userId' => $row['user_id'] ? (int) $row['user_id'] : null, 'avatar' => $row['avatar'] ?? null, 'color' => $row['color'] ?? null, 'question' => $row['question'] ?? '', 'answer' => $row['answer'] ?? '', 'answered' => (bool) $row['answered'], 'score' => (int) $row['score'], 'votes' => $parsedVotes, 'voteLocked' => (bool) ($row['vote_locked'] ?? false), 'voteRequest' => (bool) ($row['vote_request'] ?? false), 'lateJoin' => (bool) ($row['late_join'] ?? false), 'sticker' => $row['sticker'] ?? null, ]; } $outcome = $room['round_outcome'] ?? null; return [ 'code' => $room['code'], 'revealed' => (bool) $room['revealed'], // liarKeys only sent after resolution — prevents clients from seeing imposters early. // Admin spectators ($revealLiars) get them immediately to mirror the host view. 'liarKeys' => ($outcome || $revealLiars) ? $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), 'revealIndex' => (int) ($room['reveal_index'] ?? -1), 'revealedKeys' => $j($room['revealed_keys'] ?? ''), 'questionsRevealed'=> (bool) ($room['questions_revealed'] ?? false), 'imposterWeights' => $room['imposter_weights'] ?? null, 'activeEmojis' => array_values(array_filter( $j($room['active_emojis'] ?? '[]'), fn($e) => ($e['ts'] ?? 0) >= (time() - 4) )), 'players' => $players, 'chat' => (function() use ($pdo, $code) { try { $cs = $pdo->prepare( 'SELECT player_name, message, created_at FROM gtl_chat_messages WHERE room_code=? ORDER BY created_at DESC, id DESC LIMIT 30' ); $cs->execute([$code]); return array_reverse($cs->fetchAll()); } catch (Throwable) { return []; } })(), ]; } /** * 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) { $votes = $p['votes'] ?? []; if (!is_array($votes)) $votes = []; if (empty($votes)) { $tally['__nobody__']++; } else { // __nobody__ is exclusive: if present, count only as nobody if (in_array('__nobody__', $votes, true)) { $tally['__nobody__']++; } else { foreach ($votes as $vf) { if (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'], ]); } } /** * Führt die Rundenauswertung durch. Liest liar_keys direkt aus der DB, * damit die Redaktion in loadRoom() (liarKeys=[] solange roundOutcome=null) umgangen wird. * Schreibt Ergebnis, Archiv, Punkte und Profil-Stats. * * @return array Neuer state nach Auswertung (loadRoom-Ergebnis). */ function performResolveRound(PDO $pdo, string $code, int $now): array { $j = fn($v) => (!empty($v) && is_string($v)) ? (json_decode($v, true) ?: []) : []; // Liar-Keys direkt lesen — loadRoom() würde sie ohne roundOutcome verstecken $lkStmt = $pdo->prepare('SELECT liar_keys FROM gtl_rooms WHERE code=?'); $lkStmt->execute([$code]); $lkRow = $lkStmt->fetch(); $liarKeys = $j($lkRow['liar_keys'] ?? ''); $state = loadRoom($pdo, $code); $players = $state['players']; // Nachzügler (Zuschauer dieser Runde) zählen nicht für Voting/Verlauf/Statistik $activePlayers = array_filter($players, fn($p) => empty($p['lateJoin'])); $votedOut = resolveVotes(array_values($activePlayers), $liarKeys); if (empty($liarKeys)) { $outcome = 'no_liar'; } elseif (empty($votedOut)) { $outcome = 'imposters_win'; } elseif (empty(array_diff($liarKeys, $votedOut))) { $outcome = 'innocents_win'; } else { $outcome = 'imposters_win'; } $allPkeys = array_keys($players); $pdo->prepare( 'UPDATE gtl_rooms SET voted_out_keys=?, round_outcome=?, revealed=1, reveal_index=9999, revealed_keys=?, updated_at=? WHERE code=?' )->execute([json_encode($votedOut), $outcome, json_encode($allPkeys), $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]); $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 ($activePlayers 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'], ]); } } // Punkte + Profil-Stats $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 ($activePlayers as $p) { $wasImposter = in_array($p['pkey'], $liarKeys, true); $wasVotedOut = in_array($p['pkey'], $votedOut, true); $playerWon = $wasImposter ? !$wasVotedOut : ($outcome === 'innocents_win'); if ($playerWon) { $updScore->execute([$now, $code, $p['pkey']]); } 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'], ]); } return loadRoom($pdo, $code); } function requireAdminApi(PDO $pdo, $authUserId): void { if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401); $st = $pdo->prepare('SELECT role FROM gtl_users WHERE id = ?'); $st->execute([$authUserId]); if ($st->fetchColumn() !== 'admin') respond(['error' => 'Keine Berechtigung.'], 403); } $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]); // 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' => loadRoom($pdo, $code)]); break; case 'admin_spectate': 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 = 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]); 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)); // Admin spectators keep seeing imposters while polling (flag set via admin_spectate) $spectating = !empty($_SESSION['spectate'][$code]); $state = loadRoom($pdo, $code, $spectating); 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, 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' => 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': // 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' => loadRoom($pdo, $code)]); break; case 'reveal_answer': // 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' => loadRoom($pdo, $code)]); break; case 'reveal_questions': // 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' => loadRoom($pdo, $code)]); break; case 'reveal_next': // 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' => loadRoom($pdo, $code)]); 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 'send_sticker': // Eigenen Custom-Sticker fliegen lassen (wie ein Live-Emoji) if (!$authUserId) respond(['error' => 'Bitte erst einloggen.'], 401); $body = input(); $code = slugCode((string) ($body['code'] ?? '')); $stStmt = $pdo->prepare('SELECT sticker FROM gtl_users WHERE id=?'); $stStmt->execute([$authUserId]); $stickerFile = (string) ($stStmt->fetchColumn() ?: ''); if ($stickerFile === '' || !preg_match('/^[A-Za-z0-9_.\-]+$/', $stickerFile)) { respond(['error' => 'Kein gültiger Sticker vorhanden.'], 400); } $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[] = ['sticker' => 'uploads/sticker/' . $stickerFile, '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 'request_voting': // 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' => loadRoom($pdo, $code)]); break; case 'lock_vote': // 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 = performResolveRound($pdo, $code, $now); respond(['ok' => true, 'autoResolved' => true, 'state' => $newState]); } respond(['ok' => true, 'state' => loadRoom($pdo, $code)]); break; case 'update_weights': $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]); break; case 'resolve_round': // Manueller Trigger durch Host — nutzt den gemeinsamen Helper $body = input(); $code = slugCode((string) ($body['code'] ?? '')); $check = 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 = performResolveRound($pdo, $code, $now); respond(['ok' => true, 'state' => $newState]); 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, 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' => 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; case 'send_chat': $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]); break; // ── Fake-Werbung (Admin-Joke) ───────────────────────────────── case 'fake_ads': // Ö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]); break; case 'fake_ads_all': 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]); break; case 'fake_ad_create': 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()]); break; case 'fake_ad_toggle': 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]); break; case 'fake_ad_delete': requireAdminApi($pdo, $authUserId); $body = input(); $id = (int) ($body['id'] ?? 0); $pdo->prepare('DELETE FROM gtl_fake_ads WHERE id = ?')->execute([$id]); respond(['ok' => true]); break; default: respond(['error' => 'Unbekannte Aktion.'], 400); } } catch (Throwable $e) { respond(['error' => 'Serverfehler: ' . $e->getMessage()], 500); }