pdo = $pdo; $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->migrate(); } public static function open(?string $dir = null): self { $dir = $dir ?? dataDir(); if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) { throw new RuntimeException('De datamap moet schrijfbaar zijn.'); } $path = $dir . '/meteors.sqlite'; $pdo = new PDO('sqlite:' . $path, null, null, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]); $pdo->exec('PRAGMA journal_mode = WAL'); $pdo->exec('PRAGMA foreign_keys = ON'); $pdo->exec('PRAGMA busy_timeout = 4000'); return new self($pdo); } private function migrate(): void { $this->pdo->exec(<<<'SQL' CREATE TABLE IF NOT EXISTS lobbies ( id TEXT PRIMARY KEY, code TEXT UNIQUE NOT NULL, host_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'waiting', miss_chance REAL NOT NULL DEFAULT 0.30, flight_duration REAL NOT NULL DEFAULT 1.2, created INTEGER NOT NULL, started INTEGER, finished INTEGER ); CREATE TABLE IF NOT EXISTS members ( lobby_id TEXT NOT NULL, user_id TEXT NOT NULL, name TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0, eliminated INTEGER NOT NULL DEFAULT 0, place INTEGER, left_at INTEGER, joined INTEGER NOT NULL, last_seen INTEGER NOT NULL, score INTEGER NOT NULL DEFAULT 0, snapshot TEXT, PRIMARY KEY (lobby_id, user_id) ); CREATE TABLE IF NOT EXISTS shots ( id INTEGER PRIMARY KEY AUTOINCREMENT, lobby_id TEXT NOT NULL, from_user TEXT NOT NULL, to_user TEXT, color INTEGER NOT NULL, client_id TEXT, created REAL NOT NULL, deliver_at REAL NOT NULL, delivered INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at); SQL); $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'"); $this->ensureColumn('members', 'planet_json', 'TEXT'); $this->ensureColumn('shots', 'land_col', 'INTEGER'); $this->ensureColumn('shots', 'from_col', 'INTEGER'); $this->ensureColumn('shots', 'from_y', 'REAL'); $this->pdo->exec(<<<'SQL' CREATE TABLE IF NOT EXISTS profiles ( user_id TEXT PRIMARY KEY, lifetime_points INTEGER NOT NULL DEFAULT 0, locale TEXT, updated INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS point_awards ( award_key TEXT PRIMARY KEY, user_id TEXT NOT NULL, mode TEXT NOT NULL, points INTEGER NOT NULL, created INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id); CREATE TABLE IF NOT EXISTS play_sessions ( token TEXT PRIMARY KEY, user_id TEXT NOT NULL, mode TEXT NOT NULL, started INTEGER NOT NULL, finished INTEGER ); CREATE TABLE IF NOT EXISTS custom_planets ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, name TEXT NOT NULL, people TEXT NOT NULL, jumps_to_clear REAL NOT NULL, fall_time REAL NOT NULL, rise_time REAL NOT NULL, colors TEXT NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id); SQL); $this->ensureColumn('profiles', 'last_planet', 'TEXT'); $this->ensureColumn('profiles', 'name', 'TEXT'); $this->ensureColumn('profiles', 'avatar', 'TEXT'); $this->pdo->exec(<<<'SQL' CREATE TABLE IF NOT EXISTS friends_cache ( viewer_id TEXT PRIMARY KEY, payload TEXT NOT NULL, fetched INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS profiles_cache ( user_id TEXT PRIMARY KEY, name TEXT NOT NULL, avatar TEXT, fetched INTEGER NOT NULL ); SQL); $this->ensureColumn('profiles', 'locale_explicit', 'INTEGER NOT NULL DEFAULT 0'); } private function ensureColumn(string $table, string $column, string $ddl): void { $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(); foreach ($cols as $c) { if (($c['name'] ?? '') === $column) { return; } } $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl); } public function transaction(callable $fn): mixed { if ($this->txDepth > 0) { return $fn(); } $this->pdo->beginTransaction(); $this->txDepth++; try { $result = $fn(); $this->pdo->commit(); $this->txDepth--; return $result; } catch (Throwable $e) { $this->txDepth--; if ($this->pdo->inTransaction()) { $this->pdo->rollBack(); } throw $e; } } /** Tests may freeze the clock without sleeping. */ public ?int $testNow = null; private function now(): int { return $this->testNow ?? time(); } private function nowf(): float { return microtime(true); } private function newId(): string { return bin2hex(random_bytes(12)); } private function newCode(): string { $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; $len = strlen($alphabet); for ($attempt = 0; $attempt < 16; $attempt++) { $code = ''; for ($i = 0; $i < 4; $i++) { $code .= $alphabet[random_int(0, $len - 1)]; } $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?'); $exists->execute([$code]); if (!$exists->fetch()) { return $code; } } throw new RuntimeException('Kon geen unieke lobbycode maken.'); } public function lobbyForUser(string $userId): ?array { $stmt = $this->pdo->prepare( 'SELECT l.* FROM lobbies l JOIN members m ON m.lobby_id = l.id WHERE m.user_id = ? AND m.left_at IS NULL ORDER BY l.created DESC LIMIT 1' ); $stmt->execute([$userId]); $row = $stmt->fetch(); return $row ?: null; } public function getLobby(string $id): ?array { $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?'); $stmt->execute([$id]); $row = $stmt->fetch(); return $row ?: null; } public function getLobbyByCode(string $code): ?array { $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? ''); $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?'); $stmt->execute([$code]); $row = $stmt->fetch(); return $row ?: null; } /** @return list */ public function members(string $lobbyId, bool $includeLeft = false): array { $sql = 'SELECT * FROM members WHERE lobby_id = ?'; if (!$includeLeft) { $sql .= ' AND left_at IS NULL'; } $sql .= ' ORDER BY joined ASC'; $stmt = $this->pdo->prepare($sql); $stmt->execute([$lobbyId]); return $stmt->fetchAll(); } public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array { return $this->transaction(function () use ($userId, $name, $missChance, $planetId) { $existing = $this->lobbyForUser($userId); if ($existing && $existing['status'] !== 'finished') { throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.'); } if ($existing && $existing['status'] === 'finished') { $this->leaveMember($existing['id'], $userId); } $id = $this->newId(); $code = $this->newCode(); $now = $this->now(); $miss = max(0.0, min(1.0, $missChance)); $this->pdo->prepare( 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created) VALUES (?,?,?,?,?,?,?)' )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]); $choice = $this->choosePlanet($userId, $planetId, false); $this->pdo->prepare( 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json) VALUES (?,?,?,0,?,?,?,?)' )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]); return $this->getLobby($id); }); } public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array { return $this->transaction(function () use ($userId, $name, $code, $planetId) { $existing = $this->lobbyForUser($userId); if ($existing && $existing['status'] !== 'finished') { if (strcasecmp($existing['code'], $code) === 0) { return $existing; } throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.'); } $lobby = $this->getLobbyByCode($code); if (!$lobby) { throw new RuntimeException('Onbekende lobbycode.'); } if ($lobby['status'] !== 'waiting') { throw new RuntimeException('Deze lobby is al begonnen.'); } $members = $this->members($lobby['id']); if (count($members) >= METEORS_MAX_PLAYERS) { throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).'); } $now = $this->now(); $choice = $this->choosePlanet($userId, $planetId, false); $this->pdo->prepare( 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json) VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?) ON CONFLICT(lobby_id, user_id) DO UPDATE SET name = excluded.name, ready = 0, eliminated = 0, place = NULL, left_at = NULL, joined = excluded.joined, last_seen = excluded.last_seen, score = 0, snapshot = NULL, planet_id = excluded.planet_id, planet_json = excluded.planet_json' )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]); return $this->getLobby($lobby['id']); }); } private function leaveMember(string $lobbyId, string $userId): void { $this->pdo->prepare( 'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$this->now(), $lobbyId, $userId]); $lobby = $this->getLobby($lobbyId); if (!$lobby) { return; } $remaining = $this->members($lobbyId); if ($lobby['host_id'] === $userId) { if ($remaining) { $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?') ->execute([$remaining[0]['user_id'], $lobbyId]); } elseif ($lobby['status'] === 'waiting') { // Empty waiting lobby can stay; a later join by code still works until we want to close it. } } if ($lobby['status'] === 'playing') { $this->assignPlaceIfNeeded($lobbyId, $userId, true); $this->maybeFinish($lobbyId); } } public function leaveLobby(string $userId): void { $this->transaction(function () use ($userId) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { return; } $this->leaveMember($lobby['id'], $userId); }); } public function setReady(string $userId, bool $ready): array { return $this->transaction(function () use ($userId, $ready) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { throw new RuntimeException('Je zit niet in een lobby.'); } if ($lobby['status'] !== 'waiting') { throw new RuntimeException('Het spel is al begonnen.'); } $this->pdo->prepare( 'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]); return $this->getLobby($lobby['id']); }); } public function startGame(string $userId): array { return $this->transaction(function () use ($userId) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { throw new RuntimeException('Je zit niet in een lobby.'); } if ($lobby['host_id'] !== $userId) { throw new RuntimeException('Alleen de host kan het spel starten.'); } if ($lobby['status'] !== 'waiting') { throw new RuntimeException('Het spel is al begonnen.'); } $members = $this->members($lobby['id']); if (count($members) < 2) { throw new RuntimeException('Er zijn minstens twee spelers nodig.'); } foreach ($members as $m) { if (!(int) $m['ready']) { throw new RuntimeException('Niet iedereen is gereed.'); } } $this->pdo->prepare( 'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?' )->execute(['playing', $this->now(), $lobby['id']]); $this->pdo->prepare( 'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL WHERE lobby_id = ? AND left_at IS NULL' )->execute([$lobby['id']]); $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]); return $this->getLobby($lobby['id']); }); } /** @param list $shots */ public function setPlanet(string $userId, string $planetId): array { return $this->transaction(function () use ($userId, $planetId) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { throw new RuntimeException('Je zit in geen lobby.'); } if ($lobby['status'] !== 'waiting') { throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.'); } $choice = $this->choosePlanet($userId, $planetId, true); $this->pdo->prepare( 'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]); return $this->getLobby($lobby['id']); }); } /** @param array $member */ public function missChanceForMember(array $member): float { if (isset($this->testMissOverride) && is_float($this->testMissOverride)) { return max(0.0, min(1.0, $this->testMissOverride)); } if (!empty($member['planet_json'])) { $data = json_decode((string) $member['planet_json'], true); if (is_array($data)) { return Planets::missChance($data); } } $id = (string) ($member['planet_id'] ?? Planets::defaultId()); return Planets::missChanceForId($id); } /** @var ?float Tests may force a miss chance without changing the catalog. */ public ?float $testMissOverride = null; public function recordShots(string $userId, array $shots): array { return $this->transaction(function () use ($userId, $shots) { $lobby = $this->lobbyForUser($userId); if (!$lobby || $lobby['status'] !== 'playing') { return []; } $me = $this->member($lobby['id'], $userId); if (!$me || (int) $me['eliminated']) { return []; } $targets = []; foreach ($this->members($lobby['id']) as $m) { if ($m['user_id'] !== $userId && !(int) $m['eliminated']) { $targets[] = $m; } } $results = []; $missChance = $this->missChanceForMember($me); $flight = (float) $lobby['flight_duration']; $now = $this->nowf(); $ins = $this->pdo->prepare( 'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col, from_col, from_y) VALUES (?,?,?,?,?,?,?,0,?,?,?)' ); foreach ($shots as $shot) { $color = isset($shot['color']) ? (int) $shot['color'] : -1; $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? ''); $fromCol = isset($shot['col']) && $shot['col'] !== null && is_numeric($shot['col']) ? (int) $shot['col'] : null; $fromY = isset($shot['y']) && $shot['y'] !== null && is_numeric($shot['y']) ? (float) $shot['y'] : null; $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance; $to = null; $toName = null; $landCol = null; if (!$miss) { $pick = $targets[random_int(0, count($targets) - 1)]; $to = $pick['user_id']; $toName = $pick['name']; $landCol = random_int(0, 9); } $deliver = $now + $flight; $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol, $fromCol, $fromY]); $results[] = [ 'id' => (int) $this->pdo->lastInsertId(), 'client_id' => $clientId, 'from_id' => $userId, 'from_user' => $userId, 'miss' => $miss, 'target_id' => $to, 'target_name' => $toName, 'deliver_at' => $deliver, 'color' => $color, 'flight_duration' => $flight, 'age' => 0.0, 'land_col' => $landCol, 'col' => $fromCol, 'y' => $fromY, ]; } return $results; }); } /** @return list undelivered shots whose time has come, marked delivered. */ public function takeIncoming(string $lobbyId, string $userId): array { $now = $this->nowf(); $stmt = $this->pdo->prepare( 'SELECT * FROM shots WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ? ORDER BY deliver_at ASC, id ASC' ); $stmt->execute([$lobbyId, $userId, $now]); $rows = $stmt->fetchAll(); if (!$rows) { return []; } $ids = array_column($rows, 'id'); $in = implode(',', array_fill(0, count($ids), '?')); $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids); $incoming = []; foreach ($rows as $r) { $incoming[] = [ 'id' => (int) $r['id'], 'color' => (int) $r['color'], 'from_user' => $r['from_user'], 'client_id' => $r['client_id'], 'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null, 'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null, 'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null, ]; } return $incoming; } public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void { $lobby = $this->lobbyForUser($userId); if (!$lobby || $lobby['status'] !== 'playing') { return; } $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null; $fields = 'last_seen = ?'; $args = [$this->now()]; if ($json !== null) { $fields .= ', snapshot = ?'; $args[] = $json; } if ($score !== null) { $fields .= ', score = ?'; $args[] = $score; } $args[] = $lobby['id']; $args[] = $userId; $this->pdo->prepare( "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL" )->execute($args); if ($eliminated) { $this->assignPlaceIfNeeded($lobby['id'], $userId, false); $this->maybeFinish($lobby['id']); } } public function member(string $lobbyId, string $userId): ?array { $stmt = $this->pdo->prepare( 'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?' ); $stmt->execute([$lobbyId, $userId]); $row = $stmt->fetch(); return $row ?: null; } private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void { $m = $this->member($lobbyId, $userId); if (!$m || $m['place'] !== null) { return; } $active = 0; foreach ($this->members($lobbyId) as $row) { if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) { $active++; } } // First out gets last place = number of current (incl. this) non-left players. $total = count($this->members($lobbyId)); $alreadyPlaced = 0; foreach ($this->members($lobbyId, true) as $row) { if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) { if ($row['place'] !== null) { $alreadyPlaced++; } } } $place = $active + 1; // remaining others + self → this player's place $this->pdo->prepare( 'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?' )->execute([$place, $lobbyId, $userId]); } public function maybeFinish(string $lobbyId): void { $lobby = $this->getLobby($lobbyId); if (!$lobby || $lobby['status'] !== 'playing') { return; } $alive = []; foreach ($this->members($lobbyId) as $m) { if (!(int) $m['eliminated']) { $alive[] = $m; } } if (count($alive) > 1) { return; } if (count($alive) === 1) { $winner = $alive[0]; if ($winner['place'] === null) { $this->pdo->prepare( 'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?' )->execute([$lobbyId, $winner['user_id']]); } } $this->pdo->prepare( 'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?' )->execute(['finished', $this->now(), $lobbyId]); } public function maybeResetLobby(string $lobbyId): void { $lobby = $this->getLobby($lobbyId); if (!$lobby || $lobby['status'] !== 'finished') { return; } $finished = (int) ($lobby['finished'] ?? 0); if ($finished === 0 || $this->now() < $finished + METEORS_PODIUM_SECONDS) { return; } $this->pdo->prepare( 'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?' )->execute(['waiting', $lobbyId]); $this->pdo->prepare( 'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0 WHERE lobby_id = ? AND left_at IS NULL' )->execute([$lobbyId]); $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]); } /** * Shots still (or just) in flight, for every client in the lobby (t1125). * `age` is seconds since `created`, so a late poll can join mid-arc. * Window is flight_duration + 0.8 s (one poll slack). * * @return list */ public function recentFlights(string $lobbyId, ?float $flightDuration = null): array { $flight = $flightDuration !== null ? (float) $flightDuration : (float) METEORS_FLIGHT_DURATION; $now = $this->nowf(); $window = $flight + 0.8; $stmt = $this->pdo->prepare( 'SELECT * FROM shots WHERE lobby_id = ? AND created >= ? ORDER BY id ASC' ); $stmt->execute([$lobbyId, $now - $window]); $out = []; foreach ($stmt->fetchAll() as $r) { $to = $r['to_user']; $out[] = [ 'id' => (int) $r['id'], 'client_id' => $r['client_id'], 'from_id' => $r['from_user'], 'from_user' => $r['from_user'], 'target_id' => $to, 'miss' => $to === null || $to === '', 'color' => (int) $r['color'], 'flight_duration' => $flight, 'age' => $now - (float) $r['created'], 'deliver_at' => (float) $r['deliver_at'], 'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null, 'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null, 'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null, ]; } return $out; } /** Public view of a lobby for the given user, including incoming shots. */ public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array { return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) { $touch = $this->lobbyForUser($userId); if ($touch && $touch['status'] === 'finished') { $this->maybeResetLobby($touch['id']); } if ($touch && $touch['status'] === 'playing') { if ($snapshot !== null || $score !== null || $eliminated) { $this->updateSnapshot($userId, $snapshot, $score, $eliminated); } else { $this->pdo->prepare( 'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$this->now(), $touch['id'], $userId]); } } $shotResults = []; if ($outgoing && $touch && $touch['status'] === 'playing') { $shotResults = $this->recordShots($userId, $outgoing); } $lobby = $this->lobbyForUser($userId); if (!$lobby) { return [ 'lobby' => null, 'incoming' => [], 'shot_results' => $shotResults, 'shot_flights' => [], ]; } $incoming = []; if ($lobby['status'] === 'playing') { $incoming = $this->takeIncoming($lobby['id'], $userId); } $flights = []; if ($lobby['status'] === 'playing') { $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']); } $this->maybeAwardOnlineLobby($lobby); return [ 'lobby' => $this->presentLobby($lobby, $userId), 'incoming' => $incoming, 'shot_results' => $shotResults, 'shot_flights' => $flights, ]; }); } public function presentLobby(array $lobby, string $userId): array { $members = $this->members($lobby['id']); $players = []; foreach ($members as $m) { $snap = null; if (is_string($m['snapshot']) && $m['snapshot'] !== '') { $decoded = json_decode($m['snapshot'], true); $snap = is_array($decoded) ? $decoded : null; } $players[] = [ 'id' => $m['user_id'], 'name' => $m['name'], 'ready' => (bool) (int) $m['ready'], 'eliminated' => (bool) (int) $m['eliminated'], 'place' => $m['place'] !== null ? (int) $m['place'] : null, 'is_host' => $m['user_id'] === $lobby['host_id'], 'is_me' => $m['user_id'] === $userId, 'score' => (int) $m['score'], 'snapshot' => $m['user_id'] === $userId ? null : $snap, 'planet' => $this->presentMemberPlanet($m), ]; } $rankings = []; if ($lobby['status'] === 'finished' || $lobby['finished']) { $all = $this->members($lobby['id'], true); foreach ($all as $m) { if ($m['place'] !== null) { $rankings[] = [ 'place' => (int) $m['place'], 'id' => $m['user_id'], 'name' => $m['name'], 'score' => (int) $m['score'], ]; } } usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']); } $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true); return [ 'id' => $lobby['id'], 'code' => $lobby['code'], 'status' => $lobby['status'], 'host_id' => $lobby['host_id'], 'miss_chance' => (float) $lobby['miss_chance'], 'flight_duration' => (float) $lobby['flight_duration'], 'players' => $players, 'all_ready' => $allReady, 'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2, 'rankings' => $rankings, 'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null, 'podium_seconds' => METEORS_PODIUM_SECONDS, ]; } public const MAX_CUSTOM_PLANETS = 30; public const MAX_GAME_POINTS = 10000; public const MAX_POINTS_PER_SEC = 4.0; public const MIN_PLAY_SECONDS = 3; public const PLAY_TOKEN_TTL = 21600; public const NAME_MAX = 32; /** @return array{planet_id:string,planet_json:?string} */ public function choosePlanet(string $userId, string $planetId, bool $strict): array { if ($planetId === '') { if ($strict) { throw new RuntimeException('Onbekende planeet.'); } return ['planet_id' => Planets::defaultId(), 'planet_json' => null]; } if (Planets::known($planetId)) { return ['planet_id' => $planetId, 'planet_json' => null]; } $row = $this->ownedCustom($userId, $planetId); if ($row) { return [ 'planet_id' => $planetId, 'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE), ]; } if ($strict) { throw new RuntimeException('Onbekende planeet.'); } return ['planet_id' => Planets::defaultId(), 'planet_json' => null]; } /** @param array $member */ public function presentMemberPlanet(array $member): array { if (!empty($member['planet_json'])) { $data = json_decode((string) $member['planet_json'], true); if (is_array($data) && !empty($data['id'])) { return Planets::presentData($data); } } return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId())); } public function ensureProfile(string $userId): array { $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?'); $stmt->execute([$userId]); $row = $stmt->fetch(); if ($row) { return $row; } $now = $this->now(); $this->pdo->prepare( 'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)' )->execute([$userId, $now]); return [ 'user_id' => $userId, 'lifetime_points' => 0, 'locale' => null, 'updated' => $now, ]; } public function lifetimePoints(string $userId): int { return (int) $this->ensureProfile($userId)['lifetime_points']; } /** Remember the player's display name and avatar (from auth / the session). */ public function touchProfile(string $userId, ?string $name = null, ?string $avatar = null): array { $this->ensureProfile($userId); $sets = ['updated = ?']; $args = [$this->now()]; if ($name !== null) { $name = trim($name); if ($name !== '' && !isPlaceholderName($userId, $name) && mb_strlen($name) <= 64 && !preg_match('/[\x00-\x1F]/', $name)) { $sets[] = 'name = ?'; $args[] = $name; } } if ($avatar !== null) { $sets[] = 'avatar = ?'; $args[] = safeAvatarUrl($avatar); } $args[] = $userId; $this->pdo->prepare( 'UPDATE profiles SET ' . implode(', ', $sets) . ' WHERE user_id = ?' )->execute($args); return $this->ensureProfile($userId); } /** * Global top players by lifetime_points (the profile total the reward * screen counts up). Ties: name, then user_id. * * @return list */ public function topPlayers(int $limit = 10, ?string $viewerId = null): array { $limit = max(1, min(50, $limit)); $stmt = $this->pdo->prepare( 'SELECT user_id, lifetime_points, name, avatar FROM profiles WHERE lifetime_points > 0 ORDER BY lifetime_points DESC, name COLLATE NOCASE ASC, user_id ASC LIMIT ?' ); $stmt->execute([$limit]); return $this->presentLeaderboard($stmt->fetchAll() ?: [], $viewerId); } /** * Friends-only leaderboard. The viewer is included and ranked among * their friends (t1263). Players with 0 points, including the viewer * and friends who never played, are omitted. * * @param list $friends * @return list */ public function friendsLeaderboard(array $friends, int $limit = 10, ?string $viewerId = null): array { $limit = max(1, min(50, $limit)); $byId = []; foreach ($friends as $f) { if (!is_array($f) || !isset($f['id']) || !is_string($f['id']) || $f['id'] === '') { continue; } $byId[$f['id']] = $f; } if ($viewerId !== null && $viewerId !== '' && !isset($byId[$viewerId])) { $byId[$viewerId] = ['id' => $viewerId]; } if ($byId === []) { return []; } $ids = array_keys($byId); $placeholders = implode(',', array_fill(0, count($ids), '?')); $stmt = $this->pdo->prepare( "SELECT user_id, lifetime_points, name, avatar FROM profiles WHERE user_id IN ($placeholders)" ); $stmt->execute($ids); $found = []; foreach ($stmt->fetchAll() ?: [] as $row) { $found[$row['user_id']] = $row; } $rows = []; foreach ($byId as $id => $f) { $row = $found[$id] ?? null; $fallbackName = isset($f['name']) && is_string($f['name']) ? $f['name'] : ''; $fallbackAvatar = isset($f['avatar']) && is_string($f['avatar']) ? $f['avatar'] : null; $storedName = $row !== null ? trim((string) ($row['name'] ?? '')) : ''; if (isPlaceholderName($id, $storedName)) { $storedName = ''; } $storedAvatar = $row !== null ? ($row['avatar'] ?? '') : ''; $rows[] = [ 'user_id' => $id, 'lifetime_points' => $row !== null ? (int) $row['lifetime_points'] : 0, 'name' => $storedName !== '' ? $storedName : $fallbackName, 'avatar' => $storedAvatar !== '' ? $storedAvatar : $fallbackAvatar, ]; } $list = $this->presentLeaderboard($rows, $viewerId); return array_slice($list, 0, $limit); } /** * @param list> $rows * @return list */ private function presentLeaderboard(array $rows, ?string $viewerId): array { $list = []; foreach ($rows as $row) { $id = (string) ($row['user_id'] ?? ''); $name = trim((string) ($row['name'] ?? '')); if ($name === '') { $name = str_contains($id, ':') ? substr($id, (int) strrpos($id, ':') + 1) : $id; if ($name === '') { $name = 'Player'; } } $points = (int) ($row['lifetime_points'] ?? 0); if ($points <= 0) { continue; } $list[] = [ 'id' => $id, 'name' => $name, 'avatar' => safeAvatarUrl($row['avatar'] ?? null), 'points' => $points, 'you' => $viewerId !== null && $viewerId !== '' && $viewerId === $id, ]; } usort($list, static function (array $a, array $b): int { $pc = $b['points'] <=> $a['points']; if ($pc !== 0) { return $pc; } $nc = strcasecmp($a['name'], $b['name']); if ($nc !== 0) { return $nc; } return strcmp($a['id'], $b['id']); }); foreach ($list as $i => &$p) { $p['rank'] = $i + 1; } unset($p); return $list; } /** * Overlay names/avatars from auth (friends list, the viewer, or an * earlier backfill) onto an already presented leaderboard. Placeholder * names such as "3" for auth:3 are replaced. Ties are re-sorted. * * @param list $players * @param array $known * @return list */ public function applyIdentities(array $players, array $known): array { foreach ($players as &$p) { $id = (string) ($p['id'] ?? ''); $k = $known[$id] ?? null; if (!is_array($k)) { continue; } $knownName = isset($k['name']) && is_string($k['name']) ? trim($k['name']) : ''; if ($knownName !== '' && !isPlaceholderName($id, $knownName) && isPlaceholderName($id, (string) ($p['name'] ?? ''))) { $p['name'] = $knownName; } $knownAvatar = safeAvatarUrl($k['avatar'] ?? null); if ($knownAvatar !== null && empty($p['avatar'])) { $p['avatar'] = $knownAvatar; } } unset($p); usort($players, static function (array $a, array $b): int { $pc = $b['points'] <=> $a['points']; if ($pc !== 0) { return $pc; } $nc = strcasecmp((string) $a['name'], (string) $b['name']); if ($nc !== 0) { return $nc; } return strcmp((string) $a['id'], (string) $b['id']); }); foreach ($players as $i => &$p) { $p['rank'] = $i + 1; } unset($p); return $players; } /** * Write known auth names/avatars onto existing Meteors profiles. * Does not create profiles (friends who never played stay off the * global board). Placeholder names are not stored. * * @param list $identities */ public function rememberIdentities(array $identities): int { $changed = 0; foreach ($identities as $item) { if (!is_array($item) || !isset($item['id']) || !is_string($item['id']) || $item['id'] === '') { continue; } $userId = $item['id']; $name = isset($item['name']) && is_string($item['name']) ? trim($item['name']) : ''; if ($name !== '' && isPlaceholderName($userId, $name)) { $name = ''; } $avatar = safeAvatarUrl($item['avatar'] ?? null); if ($name === '' && $avatar === null) { continue; } $stmt = $this->pdo->prepare('SELECT name, avatar FROM profiles WHERE user_id = ?'); $stmt->execute([$userId]); $row = $stmt->fetch(); if (!$row) { continue; } $sets = ['updated = ?']; $args = [$this->now()]; $storedName = trim((string) ($row['name'] ?? '')); if ($name !== '' && ($storedName === '' || isPlaceholderName($userId, $storedName) || $storedName !== $name)) { $sets[] = 'name = ?'; $args[] = $name; } $storedAvatar = $row['avatar'] ?? null; if ($avatar !== null && $avatar !== $storedAvatar) { $sets[] = 'avatar = ?'; $args[] = $avatar; } if (count($sets) === 1) { continue; } $args[] = $userId; $this->pdo->prepare( 'UPDATE profiles SET ' . implode(', ', $sets) . ' WHERE user_id = ?' )->execute($args); $changed++; } return $changed; } /** * Cached GET /api/friends payload for a viewer, or null if missing/stale. * * @return list|null */ public function readFriendsCache(string $viewerId, ?int $now = null, bool $allowStale = false): ?array { $stmt = $this->pdo->prepare('SELECT payload, fetched FROM friends_cache WHERE viewer_id = ?'); $stmt->execute([$viewerId]); $row = $stmt->fetch(); if (!$row) { return null; } $now = $now ?? $this->now(); $fetched = (int) $row['fetched']; if (!$allowStale && ($now - $fetched) > self::FRIENDS_CACHE_TTL) { return null; } $data = json_decode((string) $row['payload'], true); return is_array($data) ? $data : null; } /** @param list $friends */ public function writeFriendsCache(string $viewerId, array $friends, ?int $fetchedAt = null): void { $this->pdo->prepare( 'INSERT INTO friends_cache (viewer_id, payload, fetched) VALUES (?,?,?) ON CONFLICT(viewer_id) DO UPDATE SET payload = excluded.payload, fetched = excluded.fetched' )->execute([ $viewerId, json_encode(array_values($friends), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), $fetchedAt ?? $this->now(), ]); } /** * Cached public auth profiles (GET /api/profiles). Fresh hits only * unless $allowStale is set (auth unreachable). * * @param list $userIds * @return array */ public function readProfilesCache(array $userIds, ?int $now = null, bool $allowStale = false): array { $out = []; $now = $now ?? $this->now(); foreach ($userIds as $id) { if (!is_string($id) || $id === '') { continue; } $stmt = $this->pdo->prepare('SELECT name, avatar, fetched FROM profiles_cache WHERE user_id = ?'); $stmt->execute([$id]); $row = $stmt->fetch(); if (!$row) { continue; } $fetched = (int) $row['fetched']; if (!$allowStale && ($now - $fetched) > self::PROFILES_CACHE_TTL) { continue; } $out[$id] = [ 'id' => $id, 'name' => (string) $row['name'], 'avatar' => isset($row['avatar']) && $row['avatar'] !== '' ? (string) $row['avatar'] : null, ]; } return $out; } /** @param list $identities */ public function writeProfilesCache(array $identities, ?int $fetchedAt = null): void { $fetchedAt = $fetchedAt ?? $this->now(); $stmt = $this->pdo->prepare( 'INSERT INTO profiles_cache (user_id, name, avatar, fetched) VALUES (?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET name = excluded.name, avatar = excluded.avatar, fetched = excluded.fetched' ); foreach ($identities as $row) { if (!is_array($row) || !isset($row['id'], $row['name']) || !is_string($row['id']) || $row['id'] === '') { continue; } $name = trim((string) $row['name']); if ($name === '') { continue; } $avatar = $row['avatar'] ?? null; $stmt->execute([ $row['id'], $name, is_string($avatar) && $avatar !== '' ? $avatar : null, $fetchedAt, ]); } } public function locale(string $userId): ?string { $v = $this->ensureProfile($userId)['locale'] ?? null; return is_string($v) && $v !== '' ? $v : null; } public function localeExplicit(string $userId): bool { $row = $this->ensureProfile($userId); return (int) ($row['locale_explicit'] ?? 0) === 1; } /** Seconds to reuse a viewer's auth friends list before refetching. */ public const FRIENDS_CACHE_TTL = 600; /** Seconds to reuse a public auth profile (name/avatar) before refetching. */ public const PROFILES_CACHE_TTL = 600; /** @var list */ public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es']; public function setLocale(string $userId, string $locale): string { $locale = normalizeAuthLocale($locale); if ($locale === null || !in_array($locale, self::LOCALES, true)) { throw new RuntimeException('Onbekende taal.'); } $this->ensureProfile($userId); $this->pdo->prepare( 'UPDATE profiles SET locale = ?, locale_explicit = 1, updated = ? WHERE user_id = ?' )->execute([$locale, $this->now(), $userId]); return $locale; } /** * Last chosen planet (t1196): a standard planet id or one of the * user's own custom planets. Returns null when nothing is stored or the * stored custom planet no longer exists (graceful fallback). */ public function lastPlanet(string $userId): ?string { $v = $this->ensureProfile($userId)['last_planet'] ?? null; if (!is_string($v) || $v === '') { return null; } if (Planets::known($v) || $this->ownedCustom($userId, $v)) { return $v; } return null; } public function setLastPlanet(string $userId, string $planetId): string { $planetId = trim($planetId); if ($planetId === '' || strlen($planetId) > 64 || !(Planets::known($planetId) || $this->ownedCustom($userId, $planetId))) { throw new RuntimeException('Onbekende planeet.'); } $this->ensureProfile($userId); $this->pdo->prepare('UPDATE profiles SET last_planet = ?, updated = ? WHERE user_id = ?') ->execute([$planetId, $this->now(), $userId]); return $planetId; } /** * Add points once for a unique award_key. Returns the new lifetime total. * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op. */ public function awardPoints(string $userId, int $points, string $key, string $mode): int { return $this->transaction(function () use ($userId, $points, $key, $mode) { $this->ensureProfile($userId); $points = max(0, min(self::MAX_GAME_POINTS, $points)); $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?'); $stmt->execute([$key]); if ($stmt->fetch()) { return $this->lifetimePoints($userId); } $this->pdo->prepare( 'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)' )->execute([$key, $userId, $mode, $points, $this->now()]); if ($points > 0) { $this->pdo->prepare( 'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?' )->execute([$points, $this->now(), $userId]); } return $this->lifetimePoints($userId); }); } public function playBegin(string $userId, string $mode): array { if (!in_array($mode, ['solo', 'offline'], true)) { throw new RuntimeException('Onbekende speelmodus.'); } $token = bin2hex(random_bytes(16)); $this->pdo->prepare( 'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)' )->execute([$token, $userId, $mode, $this->now()]); return ['token' => $token, 'started' => $this->now()]; } public function playFinish(string $userId, string $token, int $score): array { return $this->transaction(function () use ($userId, $token, $score) { $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?'); $stmt->execute([$token]); $ses = $stmt->fetch(); if (!$ses || $ses['user_id'] !== $userId) { throw new RuntimeException('Ongeldige speelsessie.'); } $key = 'play:' . $token; if ($ses['finished'] !== null) { return [ 'lifetime_points' => $this->lifetimePoints($userId), 'awarded' => 0, 'already' => true, ]; } $now = $this->now(); $started = (int) $ses['started']; if ($now - $started > self::PLAY_TOKEN_TTL) { $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?') ->execute([$now, $token]); throw new RuntimeException('Speelsessie is verlopen.'); } $duration = max(0, $now - $started); $score = max(0, $score); $awarded = 0; if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) { $awarded = 0; } else { $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC); $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0))); } $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?') ->execute([$now, $token]); $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']); return [ 'lifetime_points' => $total, 'awarded' => $awarded, 'already' => false, ]; }); } /** * Award key for one player's online match. The lobby is reused after the * podium (maybeResetLobby), so the key must include the match start time * (t1278). Older keys were only lobby+user and blocked every rematch. * * @param array $lobby */ public function onlineAwardKey(array $lobby, string $userId): string { $id = (string) ($lobby['id'] ?? ''); $started = (int) ($lobby['started'] ?? 0); if ($started > 0) { return 'online:' . $id . ':' . $started . ':' . $userId; } return 'online:' . $id . ':' . $userId; } /** * Key to use for this match: the per-start key, unless this same match * was already awarded with the pre-t1278 lobby-only key (created at or * after started). That avoids a double award after deploy mid-podium. * * @param array $lobby */ public function onlineAwardKeyForMatch(array $lobby, string $userId): string { $newKey = $this->onlineAwardKey($lobby, $userId); $oldKey = 'online:' . ($lobby['id'] ?? '') . ':' . $userId; if ($newKey === $oldKey) { return $oldKey; } $started = (int) ($lobby['started'] ?? 0); $stmt = $this->pdo->prepare('SELECT created FROM point_awards WHERE award_key = ?'); $stmt->execute([$oldKey]); $row = $stmt->fetch(); if ($row && $started > 0 && (int) $row['created'] >= $started) { return $oldKey; } return $newKey; } /** * Points already recorded for this user in the current online match, or * null when the match is still running and the player is not eliminated. * * @param array $lobby */ public function onlineAwardedFor(string $userId, array $lobby): ?int { $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']); $member = $this->member((string) ($lobby['id'] ?? ''), $userId); $eliminated = $member && (int) $member['eliminated']; if (!$finished && !$eliminated) { return null; } $key = $this->onlineAwardKeyForMatch($lobby, $userId); $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?'); $stmt->execute([$key]); $row = $stmt->fetch(); return $row ? (int) $row['points'] : 0; } /** @param array $lobby */ public function maybeAwardOnlineLobby(array $lobby): void { $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']); foreach ($this->members($lobby['id'], true) as $m) { if (!$finished && empty($m['eliminated'])) { continue; } $uid = (string) $m['user_id']; $key = $this->onlineAwardKeyForMatch($lobby, $uid); $this->awardPoints($uid, (int) $m['score'], $key, 'online'); } } /** @return ?array */ public function ownedCustom(string $userId, string $id): ?array { $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?'); $stmt->execute([$id, $userId]); $row = $stmt->fetch(); return $row ?: null; } /** @return list> */ public function listCustomPlanets(string $userId): array { $stmt = $this->pdo->prepare( 'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC' ); $stmt->execute([$userId]); $out = []; foreach ($stmt->fetchAll() as $row) { $out[] = $this->snapshotCustom($row); } return $out; } public static function sanitizeName(string $raw, string $field): string { $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? ''); $s = strip_tags($s); if ($s === '') { throw new RuntimeException('Vul een ' . $field . ' in.'); } if (mb_strlen($s) > self::NAME_MAX) { $s = mb_substr($s, 0, self::NAME_MAX); } return $s; } /** * Create or update a custom planet owned by $userId. * @param array $data * @return array snapshot */ public function saveCustomPlanet(string $userId, array $data): array { return $this->transaction(function () use ($userId, $data) { $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam'); $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam'); $j = Planets::clampGravity((float) ($data['jumpsToClear'] ?? 2)); $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5); $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3); $ids = $data['colors'] ?? $data['blocks'] ?? []; if (!is_array($ids) || count($ids) !== 5) { throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.'); } $points = $this->lifetimePoints($userId); $blockIds = []; foreach ($ids as $entry) { if (is_array($entry)) { $bid = (string) ($entry['block'] ?? $entry['id'] ?? ''); } else { $bid = (string) $entry; } if ($bid === '' || !Blocks::known($bid)) { throw new RuntimeException('Onbekend blokje.'); } if (!Blocks::unlockedId($bid, $points)) { throw new RuntimeException('Dit blokje is nog niet ontgrendeld.'); } if (in_array($bid, $blockIds, true)) { throw new RuntimeException('Elk blokje mag maar in één vak.'); } $blockIds[] = $bid; } $now = $this->now(); $id = isset($data['id']) ? (string) $data['id'] : ''; if ($id !== '') { $row = $this->ownedCustom($userId, $id); if (!$row) { throw new RuntimeException('Onbekende planeet.'); } $this->pdo->prepare( 'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?' )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]); } else { $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?'); $stmt->execute([$userId]); if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) { throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.'); } $id = 'c_' . bin2hex(random_bytes(8)); $this->pdo->prepare( 'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated) VALUES (?,?,?,?,?,?,?,?,?,?)' )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]); } $row = $this->ownedCustom($userId, $id); if (!$row) { throw new RuntimeException('Opslaan is mislukt.'); } return $this->snapshotCustom($row); }); } public function deleteCustomPlanet(string $userId, string $id): void { $row = $this->ownedCustom($userId, $id); if (!$row) { throw new RuntimeException('Onbekende planeet.'); } $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?') ->execute([$id, $userId]); } /** @param array $row */ public function snapshotCustom(array $row): array { $ids = json_decode((string) $row['colors'], true); if (!is_array($ids)) { $ids = []; } $colors = []; foreach ($ids as $i => $id) { $c = Blocks::asColor((string) $id, (int) $i); if ($c === null) { continue; } $colors[] = $c; } $p = [ 'id' => (string) $row['id'], 'name' => (string) $row['name'], 'people' => (string) $row['people'], // t1199: old custom planets below 2 clamp up on load. 'jumpsToClear' => Planets::clampGravity((float) $row['jumps_to_clear']), 'fallTime' => (float) $row['fall_time'], 'riseTime' => (float) $row['rise_time'], 'colors' => $colors, 'custom' => true, 'owner_id' => (string) $row['user_id'], ]; return Planets::presentData($p); } public function profilePayload(string $userId): array { $points = $this->lifetimePoints($userId); return [ 'lifetime_points' => $points, 'locale' => $this->locale($userId), 'locale_explicit' => $this->localeExplicit($userId), 'last_planet' => $this->lastPlanet($userId), 'blocks' => Blocks::present($points), 'planets' => $this->listCustomPlanets($userId), ]; } private static function clampFloat(float $value, float $lo, float $hi): float { return max($lo, min($hi, $value)); } }