BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

Store.php 61.0 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4require_once __DIR__ . '/Planets.php';
5require_once __DIR__ . '/Blocks.php';
6
7final class Store
8{
9 private PDO $pdo;
10 private int $txDepth = 0;
11
12 public function __construct(PDO $pdo)
13 {
14 $this->pdo = $pdo;
15 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
16 $this->migrate();
17 }
18
19 public static function open(?string $dir = null): self
20 {
21 $dir = $dir ?? dataDir();
22 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
23 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
24 }
25 $path = $dir . '/meteors.sqlite';
26 $pdo = new PDO('sqlite:' . $path, null, null, [
27 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
28 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
29 ]);
30 $pdo->exec('PRAGMA journal_mode = WAL');
31 $pdo->exec('PRAGMA foreign_keys = ON');
32 $pdo->exec('PRAGMA busy_timeout = 4000');
33 return new self($pdo);
34 }
35
36 private function migrate(): void
37 {
38 $this->pdo->exec(<<<'SQL'
39CREATE TABLE IF NOT EXISTS lobbies (
40 id TEXT PRIMARY KEY,
41 code TEXT UNIQUE NOT NULL,
42 host_id TEXT NOT NULL,
43 status TEXT NOT NULL DEFAULT 'waiting',
44 miss_chance REAL NOT NULL DEFAULT 0.30,
45 flight_duration REAL NOT NULL DEFAULT 1.2,
46 created INTEGER NOT NULL,
47 started INTEGER,
48 finished INTEGER
49);
50CREATE TABLE IF NOT EXISTS members (
51 lobby_id TEXT NOT NULL,
52 user_id TEXT NOT NULL,
53 name TEXT NOT NULL,
54 ready INTEGER NOT NULL DEFAULT 0,
55 eliminated INTEGER NOT NULL DEFAULT 0,
56 place INTEGER,
57 left_at INTEGER,
58 joined INTEGER NOT NULL,
59 last_seen INTEGER NOT NULL,
60 score INTEGER NOT NULL DEFAULT 0,
61 snapshot TEXT,
62 PRIMARY KEY (lobby_id, user_id)
63);
64CREATE TABLE IF NOT EXISTS shots (
65 id INTEGER PRIMARY KEY AUTOINCREMENT,
66 lobby_id TEXT NOT NULL,
67 from_user TEXT NOT NULL,
68 to_user TEXT,
69 color INTEGER NOT NULL,
70 client_id TEXT,
71 created REAL NOT NULL,
72 deliver_at REAL NOT NULL,
73 delivered INTEGER NOT NULL DEFAULT 0
74);
75CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
76SQL);
77 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
78 $this->ensureColumn('members', 'planet_json', 'TEXT');
79 $this->ensureColumn('shots', 'land_col', 'INTEGER');
80 $this->ensureColumn('shots', 'from_col', 'INTEGER');
81 $this->ensureColumn('shots', 'from_y', 'REAL');
82 $this->pdo->exec(<<<'SQL'
83CREATE TABLE IF NOT EXISTS profiles (
84 user_id TEXT PRIMARY KEY,
85 lifetime_points INTEGER NOT NULL DEFAULT 0,
86 locale TEXT,
87 updated INTEGER NOT NULL
88);
89CREATE TABLE IF NOT EXISTS point_awards (
90 award_key TEXT PRIMARY KEY,
91 user_id TEXT NOT NULL,
92 mode TEXT NOT NULL,
93 points INTEGER NOT NULL,
94 created INTEGER NOT NULL
95);
96CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id);
97CREATE TABLE IF NOT EXISTS play_sessions (
98 token TEXT PRIMARY KEY,
99 user_id TEXT NOT NULL,
100 mode TEXT NOT NULL,
101 started INTEGER NOT NULL,
102 finished INTEGER
103);
104CREATE TABLE IF NOT EXISTS custom_planets (
105 id TEXT PRIMARY KEY,
106 user_id TEXT NOT NULL,
107 name TEXT NOT NULL,
108 people TEXT NOT NULL,
109 jumps_to_clear REAL NOT NULL,
110 fall_time REAL NOT NULL,
111 rise_time REAL NOT NULL,
112 colors TEXT NOT NULL,
113 created INTEGER NOT NULL,
114 updated INTEGER NOT NULL
115);
116CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id);
117SQL);
118 $this->ensureColumn('profiles', 'last_planet', 'TEXT');
119 $this->ensureColumn('profiles', 'name', 'TEXT');
120 $this->ensureColumn('profiles', 'avatar', 'TEXT');
121 $this->pdo->exec(<<<'SQL'
122CREATE TABLE IF NOT EXISTS friends_cache (
123 viewer_id TEXT PRIMARY KEY,
124 payload TEXT NOT NULL,
125 fetched INTEGER NOT NULL
126);
127CREATE TABLE IF NOT EXISTS profiles_cache (
128 user_id TEXT PRIMARY KEY,
129 name TEXT NOT NULL,
130 avatar TEXT,
131 fetched INTEGER NOT NULL
132);
133SQL);
134 $this->ensureColumn('profiles', 'locale_explicit', 'INTEGER NOT NULL DEFAULT 0');
135 }
136
137 private function ensureColumn(string $table, string $column, string $ddl): void
138 {
139 $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
140 foreach ($cols as $c) {
141 if (($c['name'] ?? '') === $column) {
142 return;
143 }
144 }
145 $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl);
146 }
147
148 public function transaction(callable $fn): mixed
149 {
150 if ($this->txDepth > 0) {
151 return $fn();
152 }
153 $this->pdo->beginTransaction();
154 $this->txDepth++;
155 try {
156 $result = $fn();
157 $this->pdo->commit();
158 $this->txDepth--;
159 return $result;
160 } catch (Throwable $e) {
161 $this->txDepth--;
162 if ($this->pdo->inTransaction()) {
163 $this->pdo->rollBack();
164 }
165 throw $e;
166 }
167 }
168
169 /** Tests may freeze the clock without sleeping. */
170 public ?int $testNow = null;
171
172 private function now(): int
173 {
174 return $this->testNow ?? time();
175 }
176
177 private function nowf(): float
178 {
179 return microtime(true);
180 }
181
182 private function newId(): string
183 {
184 return bin2hex(random_bytes(12));
185 }
186
187 private function newCode(): string
188 {
189 $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
190 $len = strlen($alphabet);
191 for ($attempt = 0; $attempt < 16; $attempt++) {
192 $code = '';
193 for ($i = 0; $i < 4; $i++) {
194 $code .= $alphabet[random_int(0, $len - 1)];
195 }
196 $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');
197 $exists->execute([$code]);
198 if (!$exists->fetch()) {
199 return $code;
200 }
201 }
202 throw new RuntimeException('Kon geen unieke lobbycode maken.');
203 }
204
205 public function lobbyForUser(string $userId): ?array
206 {
207 $stmt = $this->pdo->prepare(
208 'SELECT l.* FROM lobbies l
209 JOIN members m ON m.lobby_id = l.id
210 WHERE m.user_id = ? AND m.left_at IS NULL
211 ORDER BY l.created DESC LIMIT 1'
212 );
213 $stmt->execute([$userId]);
214 $row = $stmt->fetch();
215 return $row ?: null;
216 }
217
218 public function getLobby(string $id): ?array
219 {
220 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');
221 $stmt->execute([$id]);
222 $row = $stmt->fetch();
223 return $row ?: null;
224 }
225
226 public function getLobbyByCode(string $code): ?array
227 {
228 $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');
229 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');
230 $stmt->execute([$code]);
231 $row = $stmt->fetch();
232 return $row ?: null;
233 }
234
235 /** @return list<array> */
236 public function members(string $lobbyId, bool $includeLeft = false): array
237 {
238 $sql = 'SELECT * FROM members WHERE lobby_id = ?';
239 if (!$includeLeft) {
240 $sql .= ' AND left_at IS NULL';
241 }
242 $sql .= ' ORDER BY joined ASC';
243 $stmt = $this->pdo->prepare($sql);
244 $stmt->execute([$lobbyId]);
245 return $stmt->fetchAll();
246 }
247
248 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array
249 {
250 return $this->transaction(function () use ($userId, $name, $missChance, $planetId) {
251 $existing = $this->lobbyForUser($userId);
252 if ($existing && $existing['status'] !== 'finished') {
253 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
254 }
255 if ($existing && $existing['status'] === 'finished') {
256 $this->leaveMember($existing['id'], $userId);
257 }
258 $id = $this->newId();
259 $code = $this->newCode();
260 $now = $this->now();
261 $miss = max(0.0, min(1.0, $missChance));
262 $this->pdo->prepare(
263 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
264 VALUES (?,?,?,?,?,?,?)'
265 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
266 $choice = $this->choosePlanet($userId, $planetId, false);
267 $this->pdo->prepare(
268 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json)
269 VALUES (?,?,?,0,?,?,?,?)'
270 )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
271 return $this->getLobby($id);
272 });
273 }
274
275 public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array
276 {
277 return $this->transaction(function () use ($userId, $name, $code, $planetId) {
278 $existing = $this->lobbyForUser($userId);
279 if ($existing && $existing['status'] !== 'finished') {
280 if (strcasecmp($existing['code'], $code) === 0) {
281 return $existing;
282 }
283 throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');
284 }
285 $lobby = $this->getLobbyByCode($code);
286 if (!$lobby) {
287 throw new RuntimeException('Onbekende lobbycode.');
288 }
289 if ($lobby['status'] !== 'waiting') {
290 throw new RuntimeException('Deze lobby is al begonnen.');
291 }
292 $members = $this->members($lobby['id']);
293 if (count($members) >= METEORS_MAX_PLAYERS) {
294 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
295 }
296 $now = $this->now();
297 $choice = $this->choosePlanet($userId, $planetId, false);
298 $this->pdo->prepare(
299 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json)
300 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?)
301 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
302 name = excluded.name,
303 ready = 0,
304 eliminated = 0,
305 place = NULL,
306 left_at = NULL,
307 joined = excluded.joined,
308 last_seen = excluded.last_seen,
309 score = 0,
310 snapshot = NULL,
311 planet_id = excluded.planet_id,
312 planet_json = excluded.planet_json'
313 )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
314 return $this->getLobby($lobby['id']);
315 });
316 }
317
318 private function leaveMember(string $lobbyId, string $userId): void
319 {
320 $this->pdo->prepare(
321 'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
322 )->execute([$this->now(), $lobbyId, $userId]);
323 $lobby = $this->getLobby($lobbyId);
324 if (!$lobby) {
325 return;
326 }
327 $remaining = $this->members($lobbyId);
328 if ($lobby['host_id'] === $userId) {
329 if ($remaining) {
330 $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')
331 ->execute([$remaining[0]['user_id'], $lobbyId]);
332 } elseif ($lobby['status'] === 'waiting') {
333 // Empty waiting lobby can stay; a later join by code still works until we want to close it.
334 }
335 }
336 if ($lobby['status'] === 'playing') {
337 $this->assignPlaceIfNeeded($lobbyId, $userId, true);
338 $this->maybeFinish($lobbyId);
339 }
340 }
341
342 public function leaveLobby(string $userId): void
343 {
344 $this->transaction(function () use ($userId) {
345 $lobby = $this->lobbyForUser($userId);
346 if (!$lobby) {
347 return;
348 }
349 $this->leaveMember($lobby['id'], $userId);
350 });
351 }
352
353 public function setReady(string $userId, bool $ready): array
354 {
355 return $this->transaction(function () use ($userId, $ready) {
356 $lobby = $this->lobbyForUser($userId);
357 if (!$lobby) {
358 throw new RuntimeException('Je zit niet in een lobby.');
359 }
360 if ($lobby['status'] !== 'waiting') {
361 throw new RuntimeException('Het spel is al begonnen.');
362 }
363 $this->pdo->prepare(
364 'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
365 )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);
366 return $this->getLobby($lobby['id']);
367 });
368 }
369
370 public function startGame(string $userId): array
371 {
372 return $this->transaction(function () use ($userId) {
373 $lobby = $this->lobbyForUser($userId);
374 if (!$lobby) {
375 throw new RuntimeException('Je zit niet in een lobby.');
376 }
377 if ($lobby['host_id'] !== $userId) {
378 throw new RuntimeException('Alleen de host kan het spel starten.');
379 }
380 if ($lobby['status'] !== 'waiting') {
381 throw new RuntimeException('Het spel is al begonnen.');
382 }
383 $members = $this->members($lobby['id']);
384 if (count($members) < 2) {
385 throw new RuntimeException('Er zijn minstens twee spelers nodig.');
386 }
387 foreach ($members as $m) {
388 if (!(int) $m['ready']) {
389 throw new RuntimeException('Niet iedereen is gereed.');
390 }
391 }
392 $this->pdo->prepare(
393 'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'
394 )->execute(['playing', $this->now(), $lobby['id']]);
395 $this->pdo->prepare(
396 'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL
397 WHERE lobby_id = ? AND left_at IS NULL'
398 )->execute([$lobby['id']]);
399 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);
400 return $this->getLobby($lobby['id']);
401 });
402 }
403
404 /** @param list<array{client_id?:string,color?:int}> $shots */
405 public function setPlanet(string $userId, string $planetId): array
406 {
407 return $this->transaction(function () use ($userId, $planetId) {
408 $lobby = $this->lobbyForUser($userId);
409 if (!$lobby) {
410 throw new RuntimeException('Je zit in geen lobby.');
411 }
412 if ($lobby['status'] !== 'waiting') {
413 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
414 }
415 $choice = $this->choosePlanet($userId, $planetId, true);
416 $this->pdo->prepare(
417 'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
418 )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]);
419 return $this->getLobby($lobby['id']);
420 });
421 }
422
423 /** @param array<string,mixed> $member */
424 public function missChanceForMember(array $member): float
425 {
426 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
427 return max(0.0, min(1.0, $this->testMissOverride));
428 }
429 if (!empty($member['planet_json'])) {
430 $data = json_decode((string) $member['planet_json'], true);
431 if (is_array($data)) {
432 return Planets::missChance($data);
433 }
434 }
435 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
436 return Planets::missChanceForId($id);
437 }
438
439 /** @var ?float Tests may force a miss chance without changing the catalog. */
440 public ?float $testMissOverride = null;
441
442 public function recordShots(string $userId, array $shots): array
443 {
444 return $this->transaction(function () use ($userId, $shots) {
445 $lobby = $this->lobbyForUser($userId);
446 if (!$lobby || $lobby['status'] !== 'playing') {
447 return [];
448 }
449 $me = $this->member($lobby['id'], $userId);
450 if (!$me || (int) $me['eliminated']) {
451 return [];
452 }
453 $targets = [];
454 foreach ($this->members($lobby['id']) as $m) {
455 if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {
456 $targets[] = $m;
457 }
458 }
459 $results = [];
460 $missChance = $this->missChanceForMember($me);
461 $flight = (float) $lobby['flight_duration'];
462 $now = $this->nowf();
463 $ins = $this->pdo->prepare(
464 'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col, from_col, from_y)
465 VALUES (?,?,?,?,?,?,?,0,?,?,?)'
466 );
467 foreach ($shots as $shot) {
468 $color = isset($shot['color']) ? (int) $shot['color'] : -1;
469 $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
470 $fromCol = isset($shot['col']) && $shot['col'] !== null && is_numeric($shot['col']) ? (int) $shot['col'] : null;
471 $fromY = isset($shot['y']) && $shot['y'] !== null && is_numeric($shot['y']) ? (float) $shot['y'] : null;
472 $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
473 $to = null;
474 $toName = null;
475 $landCol = null;
476 if (!$miss) {
477 $pick = $targets[random_int(0, count($targets) - 1)];
478 $to = $pick['user_id'];
479 $toName = $pick['name'];
480 $landCol = random_int(0, 9);
481 }
482 $deliver = $now + $flight;
483 $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol, $fromCol, $fromY]);
484 $results[] = [
485 'id' => (int) $this->pdo->lastInsertId(),
486 'client_id' => $clientId,
487 'from_id' => $userId,
488 'from_user' => $userId,
489 'miss' => $miss,
490 'target_id' => $to,
491 'target_name' => $toName,
492 'deliver_at' => $deliver,
493 'color' => $color,
494 'flight_duration' => $flight,
495 'age' => 0.0,
496 'land_col' => $landCol,
497 'col' => $fromCol,
498 'y' => $fromY,
499 ];
500 }
501 return $results;
502 });
503 }
504
505 /** @return list<array> undelivered shots whose time has come, marked delivered. */
506 public function takeIncoming(string $lobbyId, string $userId): array
507 {
508 $now = $this->nowf();
509 $stmt = $this->pdo->prepare(
510 'SELECT * FROM shots
511 WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?
512 ORDER BY deliver_at ASC, id ASC'
513 );
514 $stmt->execute([$lobbyId, $userId, $now]);
515 $rows = $stmt->fetchAll();
516 if (!$rows) {
517 return [];
518 }
519 $ids = array_column($rows, 'id');
520 $in = implode(',', array_fill(0, count($ids), '?'));
521 $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);
522 $incoming = [];
523 foreach ($rows as $r) {
524 $incoming[] = [
525 'id' => (int) $r['id'],
526 'color' => (int) $r['color'],
527 'from_user' => $r['from_user'],
528 'client_id' => $r['client_id'],
529 'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,
530 'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,
531 'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,
532 ];
533 }
534 return $incoming;
535 }
536
537 public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void
538 {
539 $lobby = $this->lobbyForUser($userId);
540 if (!$lobby || $lobby['status'] !== 'playing') {
541 return;
542 }
543 $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;
544 $fields = 'last_seen = ?';
545 $args = [$this->now()];
546 if ($json !== null) {
547 $fields .= ', snapshot = ?';
548 $args[] = $json;
549 }
550 if ($score !== null) {
551 $fields .= ', score = ?';
552 $args[] = $score;
553 }
554 $args[] = $lobby['id'];
555 $args[] = $userId;
556 $this->pdo->prepare(
557 "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"
558 )->execute($args);
559 if ($eliminated) {
560 $this->assignPlaceIfNeeded($lobby['id'], $userId, false);
561 $this->maybeFinish($lobby['id']);
562 }
563 }
564
565 public function member(string $lobbyId, string $userId): ?array
566 {
567 $stmt = $this->pdo->prepare(
568 'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'
569 );
570 $stmt->execute([$lobbyId, $userId]);
571 $row = $stmt->fetch();
572 return $row ?: null;
573 }
574
575 private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void
576 {
577 $m = $this->member($lobbyId, $userId);
578 if (!$m || $m['place'] !== null) {
579 return;
580 }
581 $active = 0;
582 foreach ($this->members($lobbyId) as $row) {
583 if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {
584 $active++;
585 }
586 }
587 // First out gets last place = number of current (incl. this) non-left players.
588 $total = count($this->members($lobbyId));
589 $alreadyPlaced = 0;
590 foreach ($this->members($lobbyId, true) as $row) {
591 if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {
592 if ($row['place'] !== null) {
593 $alreadyPlaced++;
594 }
595 }
596 }
597 $place = $active + 1; // remaining others + self → this player's place
598 $this->pdo->prepare(
599 'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'
600 )->execute([$place, $lobbyId, $userId]);
601 }
602
603 public function maybeFinish(string $lobbyId): void
604 {
605 $lobby = $this->getLobby($lobbyId);
606 if (!$lobby || $lobby['status'] !== 'playing') {
607 return;
608 }
609 $alive = [];
610 foreach ($this->members($lobbyId) as $m) {
611 if (!(int) $m['eliminated']) {
612 $alive[] = $m;
613 }
614 }
615 if (count($alive) > 1) {
616 return;
617 }
618 if (count($alive) === 1) {
619 $winner = $alive[0];
620 if ($winner['place'] === null) {
621 $this->pdo->prepare(
622 'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'
623 )->execute([$lobbyId, $winner['user_id']]);
624 }
625 }
626 $this->pdo->prepare(
627 'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'
628 )->execute(['finished', $this->now(), $lobbyId]);
629 }
630
631 public function maybeResetLobby(string $lobbyId): void
632 {
633 $lobby = $this->getLobby($lobbyId);
634 if (!$lobby || $lobby['status'] !== 'finished') {
635 return;
636 }
637 $finished = (int) ($lobby['finished'] ?? 0);
638 if ($finished === 0 || $this->now() < $finished + METEORS_PODIUM_SECONDS) {
639 return;
640 }
641 $this->pdo->prepare(
642 'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'
643 )->execute(['waiting', $lobbyId]);
644 $this->pdo->prepare(
645 'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0
646 WHERE lobby_id = ? AND left_at IS NULL'
647 )->execute([$lobbyId]);
648 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);
649 }
650
651 /**
652 * Shots still (or just) in flight, for every client in the lobby (t1125).
653 * `age` is seconds since `created`, so a late poll can join mid-arc.
654 * Window is flight_duration + 0.8 s (one poll slack).
655 *
656 * @return list<array>
657 */
658 public function recentFlights(string $lobbyId, ?float $flightDuration = null): array
659 {
660 $flight = $flightDuration !== null ? (float) $flightDuration : (float) METEORS_FLIGHT_DURATION;
661 $now = $this->nowf();
662 $window = $flight + 0.8;
663 $stmt = $this->pdo->prepare(
664 'SELECT * FROM shots
665 WHERE lobby_id = ? AND created >= ?
666 ORDER BY id ASC'
667 );
668 $stmt->execute([$lobbyId, $now - $window]);
669 $out = [];
670 foreach ($stmt->fetchAll() as $r) {
671 $to = $r['to_user'];
672 $out[] = [
673 'id' => (int) $r['id'],
674 'client_id' => $r['client_id'],
675 'from_id' => $r['from_user'],
676 'from_user' => $r['from_user'],
677 'target_id' => $to,
678 'miss' => $to === null || $to === '',
679 'color' => (int) $r['color'],
680 'flight_duration' => $flight,
681 'age' => $now - (float) $r['created'],
682 'deliver_at' => (float) $r['deliver_at'],
683 'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,
684 'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,
685 'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,
686 ];
687 }
688 return $out;
689 }
690
691 /** Public view of a lobby for the given user, including incoming shots. */
692 public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array
693 {
694 return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {
695 $touch = $this->lobbyForUser($userId);
696 if ($touch && $touch['status'] === 'finished') {
697 $this->maybeResetLobby($touch['id']);
698 }
699 if ($touch && $touch['status'] === 'playing') {
700 if ($snapshot !== null || $score !== null || $eliminated) {
701 $this->updateSnapshot($userId, $snapshot, $score, $eliminated);
702 } else {
703 $this->pdo->prepare(
704 'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
705 )->execute([$this->now(), $touch['id'], $userId]);
706 }
707 }
708 $shotResults = [];
709 if ($outgoing && $touch && $touch['status'] === 'playing') {
710 $shotResults = $this->recordShots($userId, $outgoing);
711 }
712 $lobby = $this->lobbyForUser($userId);
713 if (!$lobby) {
714 return [
715 'lobby' => null,
716 'incoming' => [],
717 'shot_results' => $shotResults,
718 'shot_flights' => [],
719 ];
720 }
721 $incoming = [];
722 if ($lobby['status'] === 'playing') {
723 $incoming = $this->takeIncoming($lobby['id'], $userId);
724 }
725 $flights = [];
726 if ($lobby['status'] === 'playing') {
727 $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
728 }
729 $this->maybeAwardOnlineLobby($lobby);
730 return [
731 'lobby' => $this->presentLobby($lobby, $userId),
732 'incoming' => $incoming,
733 'shot_results' => $shotResults,
734 'shot_flights' => $flights,
735 ];
736 });
737 }
738
739 public function presentLobby(array $lobby, string $userId): array
740 {
741 $members = $this->members($lobby['id']);
742 $players = [];
743 foreach ($members as $m) {
744 $snap = null;
745 if (is_string($m['snapshot']) && $m['snapshot'] !== '') {
746 $decoded = json_decode($m['snapshot'], true);
747 $snap = is_array($decoded) ? $decoded : null;
748 }
749 $players[] = [
750 'id' => $m['user_id'],
751 'name' => $m['name'],
752 'ready' => (bool) (int) $m['ready'],
753 'eliminated' => (bool) (int) $m['eliminated'],
754 'place' => $m['place'] !== null ? (int) $m['place'] : null,
755 'is_host' => $m['user_id'] === $lobby['host_id'],
756 'is_me' => $m['user_id'] === $userId,
757 'score' => (int) $m['score'],
758 'snapshot' => $m['user_id'] === $userId ? null : $snap,
759 'planet' => $this->presentMemberPlanet($m),
760 ];
761 }
762 $rankings = [];
763 if ($lobby['status'] === 'finished' || $lobby['finished']) {
764 $all = $this->members($lobby['id'], true);
765 foreach ($all as $m) {
766 if ($m['place'] !== null) {
767 $rankings[] = [
768 'place' => (int) $m['place'],
769 'id' => $m['user_id'],
770 'name' => $m['name'],
771 'score' => (int) $m['score'],
772 ];
773 }
774 }
775 usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);
776 }
777 $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);
778 return [
779 'id' => $lobby['id'],
780 'code' => $lobby['code'],
781 'status' => $lobby['status'],
782 'host_id' => $lobby['host_id'],
783 'miss_chance' => (float) $lobby['miss_chance'],
784 'flight_duration' => (float) $lobby['flight_duration'],
785 'players' => $players,
786 'all_ready' => $allReady,
787 'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,
788 'rankings' => $rankings,
789 'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,
790 'podium_seconds' => METEORS_PODIUM_SECONDS,
791 ];
792 }
793
794 public const MAX_CUSTOM_PLANETS = 30;
795 public const MAX_GAME_POINTS = 10000;
796 public const MAX_POINTS_PER_SEC = 4.0;
797 public const MIN_PLAY_SECONDS = 3;
798 public const PLAY_TOKEN_TTL = 21600;
799 public const NAME_MAX = 32;
800
801 /** @return array{planet_id:string,planet_json:?string} */
802 public function choosePlanet(string $userId, string $planetId, bool $strict): array
803 {
804 if ($planetId === '') {
805 if ($strict) {
806 throw new RuntimeException('Onbekende planeet.');
807 }
808 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
809 }
810 if (Planets::known($planetId)) {
811 return ['planet_id' => $planetId, 'planet_json' => null];
812 }
813 $row = $this->ownedCustom($userId, $planetId);
814 if ($row) {
815 return [
816 'planet_id' => $planetId,
817 'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE),
818 ];
819 }
820 if ($strict) {
821 throw new RuntimeException('Onbekende planeet.');
822 }
823 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
824 }
825
826 /** @param array<string,mixed> $member */
827 public function presentMemberPlanet(array $member): array
828 {
829 if (!empty($member['planet_json'])) {
830 $data = json_decode((string) $member['planet_json'], true);
831 if (is_array($data) && !empty($data['id'])) {
832 return Planets::presentData($data);
833 }
834 }
835 return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId()));
836 }
837
838 public function ensureProfile(string $userId): array
839 {
840 $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
841 $stmt->execute([$userId]);
842 $row = $stmt->fetch();
843 if ($row) {
844 return $row;
845 }
846 $now = $this->now();
847 $this->pdo->prepare(
848 'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)'
849 )->execute([$userId, $now]);
850 return [
851 'user_id' => $userId,
852 'lifetime_points' => 0,
853 'locale' => null,
854 'updated' => $now,
855 ];
856 }
857
858 public function lifetimePoints(string $userId): int
859 {
860 return (int) $this->ensureProfile($userId)['lifetime_points'];
861 }
862
863 /** Remember the player's display name and avatar (from auth / the session). */
864 public function touchProfile(string $userId, ?string $name = null, ?string $avatar = null): array
865 {
866 $this->ensureProfile($userId);
867 $sets = ['updated = ?'];
868 $args = [$this->now()];
869 if ($name !== null) {
870 $name = trim($name);
871 if ($name !== '' && !isPlaceholderName($userId, $name)
872 && mb_strlen($name) <= 64 && !preg_match('/[\x00-\x1F]/', $name)) {
873 $sets[] = 'name = ?';
874 $args[] = $name;
875 }
876 }
877 if ($avatar !== null) {
878 $sets[] = 'avatar = ?';
879 $args[] = safeAvatarUrl($avatar);
880 }
881 $args[] = $userId;
882 $this->pdo->prepare(
883 'UPDATE profiles SET ' . implode(', ', $sets) . ' WHERE user_id = ?'
884 )->execute($args);
885 return $this->ensureProfile($userId);
886 }
887
888 /**
889 * Global top players by lifetime_points (the profile total the reward
890 * screen counts up). Ties: name, then user_id.
891 *
892 * @return list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}>
893 */
894 public function topPlayers(int $limit = 10, ?string $viewerId = null): array
895 {
896 $limit = max(1, min(50, $limit));
897 $stmt = $this->pdo->prepare(
898 'SELECT user_id, lifetime_points, name, avatar FROM profiles
899 WHERE lifetime_points > 0
900 ORDER BY lifetime_points DESC, name COLLATE NOCASE ASC, user_id ASC
901 LIMIT ?'
902 );
903 $stmt->execute([$limit]);
904 return $this->presentLeaderboard($stmt->fetchAll() ?: [], $viewerId);
905 }
906
907 /**
908 * Friends-only leaderboard. The viewer is included and ranked among
909 * their friends (t1263). Players with 0 points, including the viewer
910 * and friends who never played, are omitted.
911 *
912 * @param list<array{id:string,name?:string,avatar?:?string}> $friends
913 * @return list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}>
914 */
915 public function friendsLeaderboard(array $friends, int $limit = 10, ?string $viewerId = null): array
916 {
917 $limit = max(1, min(50, $limit));
918 $byId = [];
919 foreach ($friends as $f) {
920 if (!is_array($f) || !isset($f['id']) || !is_string($f['id']) || $f['id'] === '') {
921 continue;
922 }
923 $byId[$f['id']] = $f;
924 }
925 if ($viewerId !== null && $viewerId !== '' && !isset($byId[$viewerId])) {
926 $byId[$viewerId] = ['id' => $viewerId];
927 }
928 if ($byId === []) {
929 return [];
930 }
931 $ids = array_keys($byId);
932 $placeholders = implode(',', array_fill(0, count($ids), '?'));
933 $stmt = $this->pdo->prepare(
934 "SELECT user_id, lifetime_points, name, avatar FROM profiles WHERE user_id IN ($placeholders)"
935 );
936 $stmt->execute($ids);
937 $found = [];
938 foreach ($stmt->fetchAll() ?: [] as $row) {
939 $found[$row['user_id']] = $row;
940 }
941 $rows = [];
942 foreach ($byId as $id => $f) {
943 $row = $found[$id] ?? null;
944 $fallbackName = isset($f['name']) && is_string($f['name']) ? $f['name'] : '';
945 $fallbackAvatar = isset($f['avatar']) && is_string($f['avatar']) ? $f['avatar'] : null;
946 $storedName = $row !== null ? trim((string) ($row['name'] ?? '')) : '';
947 if (isPlaceholderName($id, $storedName)) {
948 $storedName = '';
949 }
950 $storedAvatar = $row !== null ? ($row['avatar'] ?? '') : '';
951 $rows[] = [
952 'user_id' => $id,
953 'lifetime_points' => $row !== null ? (int) $row['lifetime_points'] : 0,
954 'name' => $storedName !== '' ? $storedName : $fallbackName,
955 'avatar' => $storedAvatar !== '' ? $storedAvatar : $fallbackAvatar,
956 ];
957 }
958 $list = $this->presentLeaderboard($rows, $viewerId);
959 return array_slice($list, 0, $limit);
960 }
961
962 /**
963 * @param list<array<string,mixed>> $rows
964 * @return list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}>
965 */
966 private function presentLeaderboard(array $rows, ?string $viewerId): array
967 {
968 $list = [];
969 foreach ($rows as $row) {
970 $id = (string) ($row['user_id'] ?? '');
971 $name = trim((string) ($row['name'] ?? ''));
972 if ($name === '') {
973 $name = str_contains($id, ':') ? substr($id, (int) strrpos($id, ':') + 1) : $id;
974 if ($name === '') {
975 $name = 'Player';
976 }
977 }
978 $points = (int) ($row['lifetime_points'] ?? 0);
979 if ($points <= 0) {
980 continue;
981 }
982 $list[] = [
983 'id' => $id,
984 'name' => $name,
985 'avatar' => safeAvatarUrl($row['avatar'] ?? null),
986 'points' => $points,
987 'you' => $viewerId !== null && $viewerId !== '' && $viewerId === $id,
988 ];
989 }
990 usort($list, static function (array $a, array $b): int {
991 $pc = $b['points'] <=> $a['points'];
992 if ($pc !== 0) {
993 return $pc;
994 }
995 $nc = strcasecmp($a['name'], $b['name']);
996 if ($nc !== 0) {
997 return $nc;
998 }
999 return strcmp($a['id'], $b['id']);
1000 });
1001 foreach ($list as $i => &$p) {
1002 $p['rank'] = $i + 1;
1003 }
1004 unset($p);
1005 return $list;
1006 }
1007
1008 /**
1009 * Overlay names/avatars from auth (friends list, the viewer, or an
1010 * earlier backfill) onto an already presented leaderboard. Placeholder
1011 * names such as "3" for auth:3 are replaced. Ties are re-sorted.
1012 *
1013 * @param list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}> $players
1014 * @param array<string,array{id?:string,name?:string,avatar?:?string}> $known
1015 * @return list<array{rank:int,id:string,name:string,avatar:?string,points:int,you:bool}>
1016 */
1017 public function applyIdentities(array $players, array $known): array
1018 {
1019 foreach ($players as &$p) {
1020 $id = (string) ($p['id'] ?? '');
1021 $k = $known[$id] ?? null;
1022 if (!is_array($k)) {
1023 continue;
1024 }
1025 $knownName = isset($k['name']) && is_string($k['name']) ? trim($k['name']) : '';
1026 if ($knownName !== '' && !isPlaceholderName($id, $knownName)
1027 && isPlaceholderName($id, (string) ($p['name'] ?? ''))) {
1028 $p['name'] = $knownName;
1029 }
1030 $knownAvatar = safeAvatarUrl($k['avatar'] ?? null);
1031 if ($knownAvatar !== null && empty($p['avatar'])) {
1032 $p['avatar'] = $knownAvatar;
1033 }
1034 }
1035 unset($p);
1036 usort($players, static function (array $a, array $b): int {
1037 $pc = $b['points'] <=> $a['points'];
1038 if ($pc !== 0) {
1039 return $pc;
1040 }
1041 $nc = strcasecmp((string) $a['name'], (string) $b['name']);
1042 if ($nc !== 0) {
1043 return $nc;
1044 }
1045 return strcmp((string) $a['id'], (string) $b['id']);
1046 });
1047 foreach ($players as $i => &$p) {
1048 $p['rank'] = $i + 1;
1049 }
1050 unset($p);
1051 return $players;
1052 }
1053
1054 /**
1055 * Write known auth names/avatars onto existing Meteors profiles.
1056 * Does not create profiles (friends who never played stay off the
1057 * global board). Placeholder names are not stored.
1058 *
1059 * @param list<array{id?:string,name?:string,avatar?:?string}> $identities
1060 */
1061 public function rememberIdentities(array $identities): int
1062 {
1063 $changed = 0;
1064 foreach ($identities as $item) {
1065 if (!is_array($item) || !isset($item['id']) || !is_string($item['id']) || $item['id'] === '') {
1066 continue;
1067 }
1068 $userId = $item['id'];
1069 $name = isset($item['name']) && is_string($item['name']) ? trim($item['name']) : '';
1070 if ($name !== '' && isPlaceholderName($userId, $name)) {
1071 $name = '';
1072 }
1073 $avatar = safeAvatarUrl($item['avatar'] ?? null);
1074 if ($name === '' && $avatar === null) {
1075 continue;
1076 }
1077 $stmt = $this->pdo->prepare('SELECT name, avatar FROM profiles WHERE user_id = ?');
1078 $stmt->execute([$userId]);
1079 $row = $stmt->fetch();
1080 if (!$row) {
1081 continue;
1082 }
1083 $sets = ['updated = ?'];
1084 $args = [$this->now()];
1085 $storedName = trim((string) ($row['name'] ?? ''));
1086 if ($name !== '' && ($storedName === '' || isPlaceholderName($userId, $storedName) || $storedName !== $name)) {
1087 $sets[] = 'name = ?';
1088 $args[] = $name;
1089 }
1090 $storedAvatar = $row['avatar'] ?? null;
1091 if ($avatar !== null && $avatar !== $storedAvatar) {
1092 $sets[] = 'avatar = ?';
1093 $args[] = $avatar;
1094 }
1095 if (count($sets) === 1) {
1096 continue;
1097 }
1098 $args[] = $userId;
1099 $this->pdo->prepare(
1100 'UPDATE profiles SET ' . implode(', ', $sets) . ' WHERE user_id = ?'
1101 )->execute($args);
1102 $changed++;
1103 }
1104 return $changed;
1105 }
1106
1107 /**
1108 * Cached GET /api/friends payload for a viewer, or null if missing/stale.
1109 *
1110 * @return list<array{id:string,name:string,avatar:?string}>|null
1111 */
1112 public function readFriendsCache(string $viewerId, ?int $now = null, bool $allowStale = false): ?array
1113 {
1114 $stmt = $this->pdo->prepare('SELECT payload, fetched FROM friends_cache WHERE viewer_id = ?');
1115 $stmt->execute([$viewerId]);
1116 $row = $stmt->fetch();
1117 if (!$row) {
1118 return null;
1119 }
1120 $now = $now ?? $this->now();
1121 $fetched = (int) $row['fetched'];
1122 if (!$allowStale && ($now - $fetched) > self::FRIENDS_CACHE_TTL) {
1123 return null;
1124 }
1125 $data = json_decode((string) $row['payload'], true);
1126 return is_array($data) ? $data : null;
1127 }
1128
1129 /** @param list<array{id:string,name:string,avatar:?string}> $friends */
1130 public function writeFriendsCache(string $viewerId, array $friends, ?int $fetchedAt = null): void
1131 {
1132 $this->pdo->prepare(
1133 'INSERT INTO friends_cache (viewer_id, payload, fetched) VALUES (?,?,?)
1134 ON CONFLICT(viewer_id) DO UPDATE SET payload = excluded.payload, fetched = excluded.fetched'
1135 )->execute([
1136 $viewerId,
1137 json_encode(array_values($friends), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
1138 $fetchedAt ?? $this->now(),
1139 ]);
1140 }
1141
1142 /**
1143 * Cached public auth profiles (GET /api/profiles). Fresh hits only
1144 * unless $allowStale is set (auth unreachable).
1145 *
1146 * @param list<string> $userIds
1147 * @return array<string, array{id:string,name:string,avatar:?string}>
1148 */
1149 public function readProfilesCache(array $userIds, ?int $now = null, bool $allowStale = false): array
1150 {
1151 $out = [];
1152 $now = $now ?? $this->now();
1153 foreach ($userIds as $id) {
1154 if (!is_string($id) || $id === '') {
1155 continue;
1156 }
1157 $stmt = $this->pdo->prepare('SELECT name, avatar, fetched FROM profiles_cache WHERE user_id = ?');
1158 $stmt->execute([$id]);
1159 $row = $stmt->fetch();
1160 if (!$row) {
1161 continue;
1162 }
1163 $fetched = (int) $row['fetched'];
1164 if (!$allowStale && ($now - $fetched) > self::PROFILES_CACHE_TTL) {
1165 continue;
1166 }
1167 $out[$id] = [
1168 'id' => $id,
1169 'name' => (string) $row['name'],
1170 'avatar' => isset($row['avatar']) && $row['avatar'] !== '' ? (string) $row['avatar'] : null,
1171 ];
1172 }
1173 return $out;
1174 }
1175
1176 /** @param list<array{id:string,name:string,avatar:?string}> $identities */
1177 public function writeProfilesCache(array $identities, ?int $fetchedAt = null): void
1178 {
1179 $fetchedAt = $fetchedAt ?? $this->now();
1180 $stmt = $this->pdo->prepare(
1181 'INSERT INTO profiles_cache (user_id, name, avatar, fetched) VALUES (?,?,?,?)
1182 ON CONFLICT(user_id) DO UPDATE SET name = excluded.name, avatar = excluded.avatar, fetched = excluded.fetched'
1183 );
1184 foreach ($identities as $row) {
1185 if (!is_array($row) || !isset($row['id'], $row['name']) || !is_string($row['id']) || $row['id'] === '') {
1186 continue;
1187 }
1188 $name = trim((string) $row['name']);
1189 if ($name === '') {
1190 continue;
1191 }
1192 $avatar = $row['avatar'] ?? null;
1193 $stmt->execute([
1194 $row['id'],
1195 $name,
1196 is_string($avatar) && $avatar !== '' ? $avatar : null,
1197 $fetchedAt,
1198 ]);
1199 }
1200 }
1201
1202 public function locale(string $userId): ?string
1203 {
1204 $v = $this->ensureProfile($userId)['locale'] ?? null;
1205 return is_string($v) && $v !== '' ? $v : null;
1206 }
1207
1208 public function localeExplicit(string $userId): bool
1209 {
1210 $row = $this->ensureProfile($userId);
1211 return (int) ($row['locale_explicit'] ?? 0) === 1;
1212 }
1213
1214 /** Seconds to reuse a viewer's auth friends list before refetching. */
1215 public const FRIENDS_CACHE_TTL = 600;
1216
1217 /** Seconds to reuse a public auth profile (name/avatar) before refetching. */
1218 public const PROFILES_CACHE_TTL = 600;
1219
1220 /** @var list<string> */
1221 public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
1222
1223 public function setLocale(string $userId, string $locale): string
1224 {
1225 $locale = normalizeAuthLocale($locale);
1226 if ($locale === null || !in_array($locale, self::LOCALES, true)) {
1227 throw new RuntimeException('Onbekende taal.');
1228 }
1229 $this->ensureProfile($userId);
1230 $this->pdo->prepare(
1231 'UPDATE profiles SET locale = ?, locale_explicit = 1, updated = ? WHERE user_id = ?'
1232 )->execute([$locale, $this->now(), $userId]);
1233 return $locale;
1234 }
1235
1236 /**
1237 * Last chosen planet (t1196): a standard planet id or one of the
1238 * user's own custom planets. Returns null when nothing is stored or the
1239 * stored custom planet no longer exists (graceful fallback).
1240 */
1241 public function lastPlanet(string $userId): ?string
1242 {
1243 $v = $this->ensureProfile($userId)['last_planet'] ?? null;
1244 if (!is_string($v) || $v === '') {
1245 return null;
1246 }
1247 if (Planets::known($v) || $this->ownedCustom($userId, $v)) {
1248 return $v;
1249 }
1250 return null;
1251 }
1252
1253 public function setLastPlanet(string $userId, string $planetId): string
1254 {
1255 $planetId = trim($planetId);
1256 if ($planetId === '' || strlen($planetId) > 64
1257 || !(Planets::known($planetId) || $this->ownedCustom($userId, $planetId))) {
1258 throw new RuntimeException('Onbekende planeet.');
1259 }
1260 $this->ensureProfile($userId);
1261 $this->pdo->prepare('UPDATE profiles SET last_planet = ?, updated = ? WHERE user_id = ?')
1262 ->execute([$planetId, $this->now(), $userId]);
1263 return $planetId;
1264 }
1265
1266 /**
1267 * Add points once for a unique award_key. Returns the new lifetime total.
1268 * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op.
1269 */
1270 public function awardPoints(string $userId, int $points, string $key, string $mode): int
1271 {
1272 return $this->transaction(function () use ($userId, $points, $key, $mode) {
1273 $this->ensureProfile($userId);
1274 $points = max(0, min(self::MAX_GAME_POINTS, $points));
1275 $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
1276 $stmt->execute([$key]);
1277 if ($stmt->fetch()) {
1278 return $this->lifetimePoints($userId);
1279 }
1280 $this->pdo->prepare(
1281 'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)'
1282 )->execute([$key, $userId, $mode, $points, $this->now()]);
1283 if ($points > 0) {
1284 $this->pdo->prepare(
1285 'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?'
1286 )->execute([$points, $this->now(), $userId]);
1287 }
1288 return $this->lifetimePoints($userId);
1289 });
1290 }
1291
1292 public function playBegin(string $userId, string $mode): array
1293 {
1294 if (!in_array($mode, ['solo', 'offline'], true)) {
1295 throw new RuntimeException('Onbekende speelmodus.');
1296 }
1297 $token = bin2hex(random_bytes(16));
1298 $this->pdo->prepare(
1299 'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)'
1300 )->execute([$token, $userId, $mode, $this->now()]);
1301 return ['token' => $token, 'started' => $this->now()];
1302 }
1303
1304 public function playFinish(string $userId, string $token, int $score): array
1305 {
1306 return $this->transaction(function () use ($userId, $token, $score) {
1307 $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?');
1308 $stmt->execute([$token]);
1309 $ses = $stmt->fetch();
1310 if (!$ses || $ses['user_id'] !== $userId) {
1311 throw new RuntimeException('Ongeldige speelsessie.');
1312 }
1313 $key = 'play:' . $token;
1314 if ($ses['finished'] !== null) {
1315 return [
1316 'lifetime_points' => $this->lifetimePoints($userId),
1317 'awarded' => 0,
1318 'already' => true,
1319 ];
1320 }
1321 $now = $this->now();
1322 $started = (int) $ses['started'];
1323 if ($now - $started > self::PLAY_TOKEN_TTL) {
1324 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
1325 ->execute([$now, $token]);
1326 throw new RuntimeException('Speelsessie is verlopen.');
1327 }
1328 $duration = max(0, $now - $started);
1329 $score = max(0, $score);
1330 $awarded = 0;
1331 if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) {
1332 $awarded = 0;
1333 } else {
1334 $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC);
1335 $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0)));
1336 }
1337 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
1338 ->execute([$now, $token]);
1339 $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']);
1340 return [
1341 'lifetime_points' => $total,
1342 'awarded' => $awarded,
1343 'already' => false,
1344 ];
1345 });
1346 }
1347
1348 /**
1349 * Award key for one player's online match. The lobby is reused after the
1350 * podium (maybeResetLobby), so the key must include the match start time
1351 * (t1278). Older keys were only lobby+user and blocked every rematch.
1352 *
1353 * @param array<string,mixed> $lobby
1354 */
1355 public function onlineAwardKey(array $lobby, string $userId): string
1356 {
1357 $id = (string) ($lobby['id'] ?? '');
1358 $started = (int) ($lobby['started'] ?? 0);
1359 if ($started > 0) {
1360 return 'online:' . $id . ':' . $started . ':' . $userId;
1361 }
1362 return 'online:' . $id . ':' . $userId;
1363 }
1364
1365 /**
1366 * Key to use for this match: the per-start key, unless this same match
1367 * was already awarded with the pre-t1278 lobby-only key (created at or
1368 * after started). That avoids a double award after deploy mid-podium.
1369 *
1370 * @param array<string,mixed> $lobby
1371 */
1372 public function onlineAwardKeyForMatch(array $lobby, string $userId): string
1373 {
1374 $newKey = $this->onlineAwardKey($lobby, $userId);
1375 $oldKey = 'online:' . ($lobby['id'] ?? '') . ':' . $userId;
1376 if ($newKey === $oldKey) {
1377 return $oldKey;
1378 }
1379 $started = (int) ($lobby['started'] ?? 0);
1380 $stmt = $this->pdo->prepare('SELECT created FROM point_awards WHERE award_key = ?');
1381 $stmt->execute([$oldKey]);
1382 $row = $stmt->fetch();
1383 if ($row && $started > 0 && (int) $row['created'] >= $started) {
1384 return $oldKey;
1385 }
1386 return $newKey;
1387 }
1388
1389 /**
1390 * Points already recorded for this user in the current online match, or
1391 * null when the match is still running and the player is not eliminated.
1392 *
1393 * @param array<string,mixed> $lobby
1394 */
1395 public function onlineAwardedFor(string $userId, array $lobby): ?int
1396 {
1397 $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
1398 $member = $this->member((string) ($lobby['id'] ?? ''), $userId);
1399 $eliminated = $member && (int) $member['eliminated'];
1400 if (!$finished && !$eliminated) {
1401 return null;
1402 }
1403 $key = $this->onlineAwardKeyForMatch($lobby, $userId);
1404 $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
1405 $stmt->execute([$key]);
1406 $row = $stmt->fetch();
1407 return $row ? (int) $row['points'] : 0;
1408 }
1409
1410 /** @param array<string,mixed> $lobby */
1411 public function maybeAwardOnlineLobby(array $lobby): void
1412 {
1413 $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
1414 foreach ($this->members($lobby['id'], true) as $m) {
1415 if (!$finished && empty($m['eliminated'])) {
1416 continue;
1417 }
1418 $uid = (string) $m['user_id'];
1419 $key = $this->onlineAwardKeyForMatch($lobby, $uid);
1420 $this->awardPoints($uid, (int) $m['score'], $key, 'online');
1421 }
1422 }
1423
1424 /** @return ?array<string,mixed> */
1425 public function ownedCustom(string $userId, string $id): ?array
1426 {
1427 $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?');
1428 $stmt->execute([$id, $userId]);
1429 $row = $stmt->fetch();
1430 return $row ?: null;
1431 }
1432
1433 /** @return list<array<string,mixed>> */
1434 public function listCustomPlanets(string $userId): array
1435 {
1436 $stmt = $this->pdo->prepare(
1437 'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC'
1438 );
1439 $stmt->execute([$userId]);
1440 $out = [];
1441 foreach ($stmt->fetchAll() as $row) {
1442 $out[] = $this->snapshotCustom($row);
1443 }
1444 return $out;
1445 }
1446
1447 public static function sanitizeName(string $raw, string $field): string
1448 {
1449 $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? '');
1450 $s = strip_tags($s);
1451 if ($s === '') {
1452 throw new RuntimeException('Vul een ' . $field . ' in.');
1453 }
1454 if (mb_strlen($s) > self::NAME_MAX) {
1455 $s = mb_substr($s, 0, self::NAME_MAX);
1456 }
1457 return $s;
1458 }
1459
1460 /**
1461 * Create or update a custom planet owned by $userId.
1462 * @param array<string,mixed> $data
1463 * @return array<string,mixed> snapshot
1464 */
1465 public function saveCustomPlanet(string $userId, array $data): array
1466 {
1467 return $this->transaction(function () use ($userId, $data) {
1468 $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam');
1469 $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam');
1470 $j = Planets::clampGravity((float) ($data['jumpsToClear'] ?? 2));
1471 $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5);
1472 $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3);
1473 $ids = $data['colors'] ?? $data['blocks'] ?? [];
1474 if (!is_array($ids) || count($ids) !== 5) {
1475 throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.');
1476 }
1477 $points = $this->lifetimePoints($userId);
1478 $blockIds = [];
1479 foreach ($ids as $entry) {
1480 if (is_array($entry)) {
1481 $bid = (string) ($entry['block'] ?? $entry['id'] ?? '');
1482 } else {
1483 $bid = (string) $entry;
1484 }
1485 if ($bid === '' || !Blocks::known($bid)) {
1486 throw new RuntimeException('Onbekend blokje.');
1487 }
1488 if (!Blocks::unlockedId($bid, $points)) {
1489 throw new RuntimeException('Dit blokje is nog niet ontgrendeld.');
1490 }
1491 if (in_array($bid, $blockIds, true)) {
1492 throw new RuntimeException('Elk blokje mag maar in één vak.');
1493 }
1494 $blockIds[] = $bid;
1495 }
1496 $now = $this->now();
1497 $id = isset($data['id']) ? (string) $data['id'] : '';
1498 if ($id !== '') {
1499 $row = $this->ownedCustom($userId, $id);
1500 if (!$row) {
1501 throw new RuntimeException('Onbekende planeet.');
1502 }
1503 $this->pdo->prepare(
1504 'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?'
1505 )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]);
1506 } else {
1507 $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?');
1508 $stmt->execute([$userId]);
1509 if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) {
1510 throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.');
1511 }
1512 $id = 'c_' . bin2hex(random_bytes(8));
1513 $this->pdo->prepare(
1514 'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated)
1515 VALUES (?,?,?,?,?,?,?,?,?,?)'
1516 )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]);
1517 }
1518 $row = $this->ownedCustom($userId, $id);
1519 if (!$row) {
1520 throw new RuntimeException('Opslaan is mislukt.');
1521 }
1522 return $this->snapshotCustom($row);
1523 });
1524 }
1525
1526 public function deleteCustomPlanet(string $userId, string $id): void
1527 {
1528 $row = $this->ownedCustom($userId, $id);
1529 if (!$row) {
1530 throw new RuntimeException('Onbekende planeet.');
1531 }
1532 $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?')
1533 ->execute([$id, $userId]);
1534 }
1535
1536 /** @param array<string,mixed> $row */
1537 public function snapshotCustom(array $row): array
1538 {
1539 $ids = json_decode((string) $row['colors'], true);
1540 if (!is_array($ids)) {
1541 $ids = [];
1542 }
1543 $colors = [];
1544 foreach ($ids as $i => $id) {
1545 $c = Blocks::asColor((string) $id, (int) $i);
1546 if ($c === null) {
1547 continue;
1548 }
1549 $colors[] = $c;
1550 }
1551 $p = [
1552 'id' => (string) $row['id'],
1553 'name' => (string) $row['name'],
1554 'people' => (string) $row['people'],
1555 // t1199: old custom planets below 2 clamp up on load.
1556 'jumpsToClear' => Planets::clampGravity((float) $row['jumps_to_clear']),
1557 'fallTime' => (float) $row['fall_time'],
1558 'riseTime' => (float) $row['rise_time'],
1559 'colors' => $colors,
1560 'custom' => true,
1561 'owner_id' => (string) $row['user_id'],
1562 ];
1563 return Planets::presentData($p);
1564 }
1565
1566 public function profilePayload(string $userId): array
1567 {
1568 $points = $this->lifetimePoints($userId);
1569 return [
1570 'lifetime_points' => $points,
1571 'locale' => $this->locale($userId),
1572 'locale_explicit' => $this->localeExplicit($userId),
1573 'last_planet' => $this->lastPlanet($userId),
1574 'blocks' => Blocks::present($points),
1575 'planets' => $this->listCustomPlanets($userId),
1576 ];
1577 }
1578
1579 private static function clampFloat(float $value, float $lo, float $hi): float
1580 {
1581 return max($lo, min($hi, $value));
1582 }
1583
1584
1585}