BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

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