BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

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