BlueGit

projects-timfalken-com meteors

feat: lifetime points, anti-cheat, and custom planet API (t1139)

Logged-in play awards score to a server-side profile (solo at game over,
each Offline Strijd round, Online on elimination). Tokens clamp obvious
cheating. Players can CRUD up to 30 custom planets; lobby set/create/join
stores a snapshot so mid-match edits cannot change a running game.

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
40f2cf5823351185c21d6b8b047e4b6e381dfe25
Parent
7638a860
3 files changed +498 −16
server/api.php +57 −1
@@ -18,8 +18,16 @@ try {
18 18
19 19 if ($action === 'me' || $action === '') {
20 20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
21 $profile = [
22 'lifetime_points' => 0,
23 'locale' => null,
24 'blocks' => [],
25 'planets' => [],
26 ];
21 27 if ($user) {
22 $view = Store::open()->viewFor($user['id']);
28 $store = Store::open();
29 $view = $store->viewFor($user['id']);
30 $profile = $store->profilePayload($user['id']);
23 31 }
24 32 jsonOut([
25 33 'ok' => true,
@@ -35,6 +43,10 @@ try {
35 43 'flight_duration' => METEORS_FLIGHT_DURATION,
36 44 'login_url' => 'auth.php',
37 45 'logout_url' => 'logout.php',
46 'lifetime_points' => $profile['lifetime_points'],
47 'locale' => $profile['locale'],
48 'blocks' => $profile['blocks'],
49 'planets' => $profile['planets'],
38 50 ]);
39 51 }
40 52
@@ -97,6 +109,7 @@ try {
97 109 $eliminated = !empty($body['eliminated']);
98 110 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
99 111 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
112 $profile = $store->profilePayload($userId);
100 113 jsonOut([
101 114 'ok' => true,
102 115 'csrf' => csrfToken(),
@@ -105,8 +118,51 @@ try {
105 118 'incoming' => $view['incoming'],
106 119 'shot_results' => $view['shot_results'],
107 120 'shot_flights' => $view['shot_flights'] ?? [],
121 'lifetime_points' => $profile['lifetime_points'],
122 'locale' => $profile['locale'],
123 'blocks' => $profile['blocks'],
124 'planets' => $profile['planets'],
108 125 ]);
109 126
127 case 'play_begin':
128 $mode = (string) ($body['mode'] ?? 'solo');
129 $ses = $store->playBegin($userId, $mode);
130 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'token' => $ses['token']]);
131
132 case 'play_finish':
133 $token = (string) ($body['token'] ?? '');
134 $score = isset($body['score']) ? (int) $body['score'] : 0;
135 $result = $store->playFinish($userId, $token, $score);
136 jsonOut([
137 'ok' => true,
138 'csrf' => csrfToken(),
139 'lifetime_points' => $result['lifetime_points'],
140 'awarded' => $result['awarded'],
141 'already' => $result['already'],
142 'blocks' => Blocks::present($result['lifetime_points']),
143 ]);
144
145 case 'planet_save':
146 $snap = $store->saveCustomPlanet($userId, is_array($body['planet'] ?? null) ? $body['planet'] : $body);
147 jsonOut([
148 'ok' => true,
149 'csrf' => csrfToken(),
150 'planet' => $snap,
151 'planets' => $store->listCustomPlanets($userId),
152 ]);
153
154 case 'planet_delete':
155 $store->deleteCustomPlanet($userId, (string) ($body['id'] ?? $body['planet_id'] ?? ''));
156 jsonOut([
157 'ok' => true,
158 'csrf' => csrfToken(),
159 'planets' => $store->listCustomPlanets($userId),
160 ]);
161
162 case 'set_locale':
163 $locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
164 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);
165
110 166 default:
111 167 jsonFail('Onbekende actie.', 404);
112 168 }
@@ -18,8 +18,16 @@ try {
18
18
19 if ($action === 'me' || $action === '') {
19 if ($action === 'me' || $action === '') {
20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
21 $profile = [
22 'lifetime_points' => 0,
23 'locale' => null,
24 'blocks' => [],
25 'planets' => [],
26 ];
21 if ($user) {
27 if ($user) {
22 $view = Store::open()->viewFor($user['id']);
28 $store = Store::open();
29 $view = $store->viewFor($user['id']);
30 $profile = $store->profilePayload($user['id']);
23 }
31 }
24 jsonOut([
32 jsonOut([
25 'ok' => true,
33 'ok' => true,
@@ -35,6 +43,10 @@ try {
35 'flight_duration' => METEORS_FLIGHT_DURATION,
43 'flight_duration' => METEORS_FLIGHT_DURATION,
36 'login_url' => 'auth.php',
44 'login_url' => 'auth.php',
37 'logout_url' => 'logout.php',
45 'logout_url' => 'logout.php',
46 'lifetime_points' => $profile['lifetime_points'],
47 'locale' => $profile['locale'],
48 'blocks' => $profile['blocks'],
49 'planets' => $profile['planets'],
38 ]);
50 ]);
39 }
51 }
40
52
@@ -97,6 +109,7 @@ try {
97 $eliminated = !empty($body['eliminated']);
109 $eliminated = !empty($body['eliminated']);
98 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
110 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
99 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
111 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
112 $profile = $store->profilePayload($userId);
100 jsonOut([
113 jsonOut([
101 'ok' => true,
114 'ok' => true,
102 'csrf' => csrfToken(),
115 'csrf' => csrfToken(),
@@ -105,8 +118,51 @@ try {
105 'incoming' => $view['incoming'],
118 'incoming' => $view['incoming'],
106 'shot_results' => $view['shot_results'],
119 'shot_results' => $view['shot_results'],
107 'shot_flights' => $view['shot_flights'] ?? [],
120 'shot_flights' => $view['shot_flights'] ?? [],
121 'lifetime_points' => $profile['lifetime_points'],
122 'locale' => $profile['locale'],
123 'blocks' => $profile['blocks'],
124 'planets' => $profile['planets'],
108 ]);
125 ]);
109
126
127 case 'play_begin':
128 $mode = (string) ($body['mode'] ?? 'solo');
129 $ses = $store->playBegin($userId, $mode);
130 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'token' => $ses['token']]);
131
132 case 'play_finish':
133 $token = (string) ($body['token'] ?? '');
134 $score = isset($body['score']) ? (int) $body['score'] : 0;
135 $result = $store->playFinish($userId, $token, $score);
136 jsonOut([
137 'ok' => true,
138 'csrf' => csrfToken(),
139 'lifetime_points' => $result['lifetime_points'],
140 'awarded' => $result['awarded'],
141 'already' => $result['already'],
142 'blocks' => Blocks::present($result['lifetime_points']),
143 ]);
144
145 case 'planet_save':
146 $snap = $store->saveCustomPlanet($userId, is_array($body['planet'] ?? null) ? $body['planet'] : $body);
147 jsonOut([
148 'ok' => true,
149 'csrf' => csrfToken(),
150 'planet' => $snap,
151 'planets' => $store->listCustomPlanets($userId),
152 ]);
153
154 case 'planet_delete':
155 $store->deleteCustomPlanet($userId, (string) ($body['id'] ?? $body['planet_id'] ?? ''));
156 jsonOut([
157 'ok' => true,
158 'csrf' => csrfToken(),
159 'planets' => $store->listCustomPlanets($userId),
160 ]);
161
162 case 'set_locale':
163 $locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
164 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);
165
110 default:
166 default:
111 jsonFail('Onbekende actie.', 404);
167 jsonFail('Onbekende actie.', 404);
112 }
168 }
server/lib/Planets.php +33 −0
@@ -149,6 +149,39 @@ final class Planets
149 149 ];
150 150 }
151 151
152 /** Present a raw planet array (catalog or a validated custom snapshot). */
153 public static function presentData(array $p): array
154 {
155 $d = self::displayValues($p);
156 $colors = [];
157 foreach ($p['colors'] ?? [] as $c) {
158 if (!is_array($c)) {
159 continue;
160 }
161 $colors[] = [
162 'id' => (int) ($c['id'] ?? 0),
163 'block' => (string) ($c['block'] ?? $c['name'] ?? ''),
164 'name' => (string) ($c['name'] ?? ''),
165 'hex' => (string) ($c['hex'] ?? '#888'),
166 'shape' => (string) ($c['shape'] ?? ''),
167 'image' => (string) ($c['image'] ?? ''),
168 ];
169 }
170 return [
171 'id' => (string) ($p['id'] ?? ''),
172 'name' => (string) ($p['name'] ?? ''),
173 'people' => (string) ($p['people'] ?? ''),
174 'jumpsToClear' => (float) ($p['jumpsToClear'] ?? 2),
175 'fallTime' => (float) ($p['fallTime'] ?? 3),
176 'riseTime' => (float) ($p['riseTime'] ?? 1.5),
177 'miss_chance' => $d['missChance'],
178 'display' => $d,
179 'colors' => $colors,
180 'custom' => !empty($p['custom']),
181 'owner_id' => isset($p['owner_id']) ? (string) $p['owner_id'] : null,
182 ];
183 }
184
152 185 private static function clamp(float $value, float $lo, float $hi): float
153 186 {
154 187 return max($lo, min($hi, $value));
@@ -149,6 +149,39 @@ final class Planets
149 ];
149 ];
150 }
150 }
151
151
152 /** Present a raw planet array (catalog or a validated custom snapshot). */
153 public static function presentData(array $p): array
154 {
155 $d = self::displayValues($p);
156 $colors = [];
157 foreach ($p['colors'] ?? [] as $c) {
158 if (!is_array($c)) {
159 continue;
160 }
161 $colors[] = [
162 'id' => (int) ($c['id'] ?? 0),
163 'block' => (string) ($c['block'] ?? $c['name'] ?? ''),
164 'name' => (string) ($c['name'] ?? ''),
165 'hex' => (string) ($c['hex'] ?? '#888'),
166 'shape' => (string) ($c['shape'] ?? ''),
167 'image' => (string) ($c['image'] ?? ''),
168 ];
169 }
170 return [
171 'id' => (string) ($p['id'] ?? ''),
172 'name' => (string) ($p['name'] ?? ''),
173 'people' => (string) ($p['people'] ?? ''),
174 'jumpsToClear' => (float) ($p['jumpsToClear'] ?? 2),
175 'fallTime' => (float) ($p['fallTime'] ?? 3),
176 'riseTime' => (float) ($p['riseTime'] ?? 1.5),
177 'miss_chance' => $d['missChance'],
178 'display' => $d,
179 'colors' => $colors,
180 'custom' => !empty($p['custom']),
181 'owner_id' => isset($p['owner_id']) ? (string) $p['owner_id'] : null,
182 ];
183 }
184
152 private static function clamp(float $value, float $lo, float $hi): float
185 private static function clamp(float $value, float $lo, float $hi): float
153 {
186 {
154 return max($lo, min($hi, $value));
187 return max($lo, min($hi, $value));
server/lib/Store.php +408 −15
@@ -2,6 +2,7 @@
2 2 declare(strict_types=1);
3 3
4 4 require_once __DIR__ . '/Planets.php';
5 require_once __DIR__ . '/Blocks.php';
5 6
6 7 final class Store
7 8 {
@@ -74,9 +75,46 @@ CREATE TABLE IF NOT EXISTS shots (
74 75 CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
75 76 SQL);
76 77 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
78 $this->ensureColumn('members', 'planet_json', 'TEXT');
77 79 $this->ensureColumn('shots', 'land_col', 'INTEGER');
78 80 $this->ensureColumn('shots', 'from_col', 'INTEGER');
79 81 $this->ensureColumn('shots', 'from_y', 'REAL');
82 $this->pdo->exec(<<<'SQL'
83 CREATE 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 );
89 CREATE 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 );
96 CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id);
97 CREATE 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 );
104 CREATE 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 );
116 CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id);
117 SQL);
80 118 }
81 119
82 120 private function ensureColumn(string $table, string $column, string $ddl): void
@@ -111,9 +149,12 @@ SQL);
111 149 }
112 150 }
113 151
152 /** Tests may freeze the clock without sleeping. */
153 public ?int $testNow = null;
154
114 155 private function now(): int
115 156 {
116 return time();
157 return $this->testNow ?? time();
117 158 }
118 159
119 160 private function nowf(): float
@@ -205,11 +246,11 @@ SQL);
205 246 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
206 247 VALUES (?,?,?,?,?,?,?)'
207 248 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
208 $planet = Planets::known($planetId) ? $planetId : Planets::defaultId();
249 $choice = $this->choosePlanet($userId, $planetId, false);
209 250 $this->pdo->prepare(
210 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
211 VALUES (?,?,?,0,?,?,?)'
212 )->execute([$id, $userId, $name, $now, $now, $planet]);
251 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json)
252 VALUES (?,?,?,0,?,?,?,?)'
253 )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
213 254 return $this->getLobby($id);
214 255 });
215 256 }
@@ -236,9 +277,10 @@ SQL);
236 277 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
237 278 }
238 279 $now = $this->now();
280 $choice = $this->choosePlanet($userId, $planetId, false);
239 281 $this->pdo->prepare(
240 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id)
241 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
282 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json)
283 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?)
242 284 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
243 285 name = excluded.name,
244 286 ready = 0,
@@ -249,8 +291,9 @@ SQL);
249 291 last_seen = excluded.last_seen,
250 292 score = 0,
251 293 snapshot = NULL,
252 planet_id = excluded.planet_id'
253 )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
294 planet_id = excluded.planet_id,
295 planet_json = excluded.planet_json'
296 )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
254 297 return $this->getLobby($lobby['id']);
255 298 });
256 299 }
@@ -352,12 +395,10 @@ SQL);
352 395 if ($lobby['status'] !== 'waiting') {
353 396 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
354 397 }
355 if (!Planets::known($planetId)) {
356 throw new RuntimeException('Onbekende planeet.');
357 }
398 $choice = $this->choosePlanet($userId, $planetId, true);
358 399 $this->pdo->prepare(
359 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
360 )->execute([$planetId, $this->now(), $lobby['id'], $userId]);
400 'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
401 )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]);
361 402 return $this->getLobby($lobby['id']);
362 403 });
363 404 }
@@ -368,6 +409,12 @@ SQL);
368 409 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
369 410 return max(0.0, min(1.0, $this->testMissOverride));
370 411 }
412 if (!empty($member['planet_json'])) {
413 $data = json_decode((string) $member['planet_json'], true);
414 if (is_array($data)) {
415 return Planets::missChance($data);
416 }
417 }
371 418 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
372 419 return Planets::missChanceForId($id);
373 420 }
@@ -662,6 +709,7 @@ SQL);
662 709 if ($lobby['status'] === 'playing') {
663 710 $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
664 711 }
712 $this->maybeAwardOnlineLobby($lobby);
665 713 return [
666 714 'lobby' => $this->presentLobby($lobby, $userId),
667 715 'incoming' => $incoming,
@@ -691,7 +739,7 @@ SQL);
691 739 'is_me' => $m['user_id'] === $userId,
692 740 'score' => (int) $m['score'],
693 741 'snapshot' => $m['user_id'] === $userId ? null : $snap,
694 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())),
742 'planet' => $this->presentMemberPlanet($m),
695 743 ];
696 744 }
697 745 $rankings = [];
@@ -725,4 +773,349 @@ SQL);
725 773 'podium_seconds' => METEORS_PODIUM_SECONDS,
726 774 ];
727 775 }
776
777 public const MAX_CUSTOM_PLANETS = 30;
778 public const MAX_GAME_POINTS = 10000;
779 public const MAX_POINTS_PER_SEC = 4.0;
780 public const MIN_PLAY_SECONDS = 3;
781 public const PLAY_TOKEN_TTL = 21600;
782 public const NAME_MAX = 32;
783
784 /** @return array{planet_id:string,planet_json:?string} */
785 public function choosePlanet(string $userId, string $planetId, bool $strict): array
786 {
787 if ($planetId === '') {
788 if ($strict) {
789 throw new RuntimeException('Onbekende planeet.');
790 }
791 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
792 }
793 if (Planets::known($planetId)) {
794 return ['planet_id' => $planetId, 'planet_json' => null];
795 }
796 $row = $this->ownedCustom($userId, $planetId);
797 if ($row) {
798 return [
799 'planet_id' => $planetId,
800 'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE),
801 ];
802 }
803 if ($strict) {
804 throw new RuntimeException('Onbekende planeet.');
805 }
806 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
807 }
808
809 /** @param array<string,mixed> $member */
810 public function presentMemberPlanet(array $member): array
811 {
812 if (!empty($member['planet_json'])) {
813 $data = json_decode((string) $member['planet_json'], true);
814 if (is_array($data) && !empty($data['id'])) {
815 return Planets::presentData($data);
816 }
817 }
818 return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId()));
819 }
820
821 public function ensureProfile(string $userId): array
822 {
823 $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
824 $stmt->execute([$userId]);
825 $row = $stmt->fetch();
826 if ($row) {
827 return $row;
828 }
829 $now = $this->now();
830 $this->pdo->prepare(
831 'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)'
832 )->execute([$userId, $now]);
833 return [
834 'user_id' => $userId,
835 'lifetime_points' => 0,
836 'locale' => null,
837 'updated' => $now,
838 ];
839 }
840
841 public function lifetimePoints(string $userId): int
842 {
843 return (int) $this->ensureProfile($userId)['lifetime_points'];
844 }
845
846 public function locale(string $userId): ?string
847 {
848 $v = $this->ensureProfile($userId)['locale'] ?? null;
849 return is_string($v) && $v !== '' ? $v : null;
850 }
851
852 /** @var list<string> */
853 public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
854
855 public function setLocale(string $userId, string $locale): string
856 {
857 $locale = strtolower($locale);
858 if (!in_array($locale, self::LOCALES, true)) {
859 throw new RuntimeException('Onbekende taal.');
860 }
861 $this->ensureProfile($userId);
862 $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
863 ->execute([$locale, $this->now(), $userId]);
864 return $locale;
865 }
866
867 /**
868 * Add points once for a unique award_key. Returns the new lifetime total.
869 * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op.
870 */
871 public function awardPoints(string $userId, int $points, string $key, string $mode): int
872 {
873 return $this->transaction(function () use ($userId, $points, $key, $mode) {
874 $this->ensureProfile($userId);
875 $points = max(0, min(self::MAX_GAME_POINTS, $points));
876 $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
877 $stmt->execute([$key]);
878 if ($stmt->fetch()) {
879 return $this->lifetimePoints($userId);
880 }
881 $this->pdo->prepare(
882 'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)'
883 )->execute([$key, $userId, $mode, $points, $this->now()]);
884 if ($points > 0) {
885 $this->pdo->prepare(
886 'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?'
887 )->execute([$points, $this->now(), $userId]);
888 }
889 return $this->lifetimePoints($userId);
890 });
891 }
892
893 public function playBegin(string $userId, string $mode): array
894 {
895 if (!in_array($mode, ['solo', 'offline'], true)) {
896 throw new RuntimeException('Onbekende speelmodus.');
897 }
898 $token = bin2hex(random_bytes(16));
899 $this->pdo->prepare(
900 'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)'
901 )->execute([$token, $userId, $mode, $this->now()]);
902 return ['token' => $token, 'started' => $this->now()];
903 }
904
905 public function playFinish(string $userId, string $token, int $score): array
906 {
907 return $this->transaction(function () use ($userId, $token, $score) {
908 $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?');
909 $stmt->execute([$token]);
910 $ses = $stmt->fetch();
911 if (!$ses || $ses['user_id'] !== $userId) {
912 throw new RuntimeException('Ongeldige speelsessie.');
913 }
914 $key = 'play:' . $token;
915 if ($ses['finished'] !== null) {
916 return [
917 'lifetime_points' => $this->lifetimePoints($userId),
918 'awarded' => 0,
919 'already' => true,
920 ];
921 }
922 $now = $this->now();
923 $started = (int) $ses['started'];
924 if ($now - $started > self::PLAY_TOKEN_TTL) {
925 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
926 ->execute([$now, $token]);
927 throw new RuntimeException('Speelsessie is verlopen.');
928 }
929 $duration = max(0, $now - $started);
930 $score = max(0, $score);
931 $awarded = 0;
932 if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) {
933 $awarded = 0;
934 } else {
935 $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC);
936 $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0)));
937 }
938 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
939 ->execute([$now, $token]);
940 $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']);
941 return [
942 'lifetime_points' => $total,
943 'awarded' => $awarded,
944 'already' => false,
945 ];
946 });
947 }
948
949 /** @param array<string,mixed> $lobby */
950 public function maybeAwardOnlineLobby(array $lobby): void
951 {
952 $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
953 foreach ($this->members($lobby['id'], true) as $m) {
954 if (!$finished && empty($m['eliminated'])) {
955 continue;
956 }
957 $uid = (string) $m['user_id'];
958 $key = 'online:' . $lobby['id'] . ':' . $uid;
959 $this->awardPoints($uid, (int) $m['score'], $key, 'online');
960 }
961 }
962
963 /** @return ?array<string,mixed> */
964 public function ownedCustom(string $userId, string $id): ?array
965 {
966 $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?');
967 $stmt->execute([$id, $userId]);
968 $row = $stmt->fetch();
969 return $row ?: null;
970 }
971
972 /** @return list<array<string,mixed>> */
973 public function listCustomPlanets(string $userId): array
974 {
975 $stmt = $this->pdo->prepare(
976 'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC'
977 );
978 $stmt->execute([$userId]);
979 $out = [];
980 foreach ($stmt->fetchAll() as $row) {
981 $out[] = $this->snapshotCustom($row);
982 }
983 return $out;
984 }
985
986 public static function sanitizeName(string $raw, string $field): string
987 {
988 $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? '');
989 $s = strip_tags($s);
990 if ($s === '') {
991 throw new RuntimeException('Vul een ' . $field . ' in.');
992 }
993 if (mb_strlen($s) > self::NAME_MAX) {
994 $s = mb_substr($s, 0, self::NAME_MAX);
995 }
996 return $s;
997 }
998
999 /**
1000 * Create or update a custom planet owned by $userId.
1001 * @param array<string,mixed> $data
1002 * @return array<string,mixed> snapshot
1003 */
1004 public function saveCustomPlanet(string $userId, array $data): array
1005 {
1006 return $this->transaction(function () use ($userId, $data) {
1007 $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam');
1008 $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam');
1009 $j = self::clampFloat((float) ($data['jumpsToClear'] ?? 2), 1, 4);
1010 $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5);
1011 $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3);
1012 $ids = $data['colors'] ?? $data['blocks'] ?? [];
1013 if (!is_array($ids) || count($ids) !== 5) {
1014 throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.');
1015 }
1016 $points = $this->lifetimePoints($userId);
1017 $blockIds = [];
1018 foreach ($ids as $entry) {
1019 if (is_array($entry)) {
1020 $bid = (string) ($entry['block'] ?? $entry['id'] ?? '');
1021 } else {
1022 $bid = (string) $entry;
1023 }
1024 if ($bid === '' || !Blocks::known($bid)) {
1025 throw new RuntimeException('Onbekend blokje.');
1026 }
1027 if (!Blocks::unlockedId($bid, $points)) {
1028 throw new RuntimeException('Dit blokje is nog niet ontgrendeld.');
1029 }
1030 if (in_array($bid, $blockIds, true)) {
1031 throw new RuntimeException('Elk blokje mag maar in één vak.');
1032 }
1033 $blockIds[] = $bid;
1034 }
1035 $now = $this->now();
1036 $id = isset($data['id']) ? (string) $data['id'] : '';
1037 if ($id !== '') {
1038 $row = $this->ownedCustom($userId, $id);
1039 if (!$row) {
1040 throw new RuntimeException('Onbekende planeet.');
1041 }
1042 $this->pdo->prepare(
1043 'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?'
1044 )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]);
1045 } else {
1046 $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?');
1047 $stmt->execute([$userId]);
1048 if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) {
1049 throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.');
1050 }
1051 $id = 'c_' . bin2hex(random_bytes(8));
1052 $this->pdo->prepare(
1053 'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated)
1054 VALUES (?,?,?,?,?,?,?,?,?,?)'
1055 )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]);
1056 }
1057 $row = $this->ownedCustom($userId, $id);
1058 if (!$row) {
1059 throw new RuntimeException('Opslaan is mislukt.');
1060 }
1061 return $this->snapshotCustom($row);
1062 });
1063 }
1064
1065 public function deleteCustomPlanet(string $userId, string $id): void
1066 {
1067 $row = $this->ownedCustom($userId, $id);
1068 if (!$row) {
1069 throw new RuntimeException('Onbekende planeet.');
1070 }
1071 $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?')
1072 ->execute([$id, $userId]);
1073 }
1074
1075 /** @param array<string,mixed> $row */
1076 public function snapshotCustom(array $row): array
1077 {
1078 $ids = json_decode((string) $row['colors'], true);
1079 if (!is_array($ids)) {
1080 $ids = [];
1081 }
1082 $colors = [];
1083 foreach ($ids as $i => $id) {
1084 $c = Blocks::asColor((string) $id, (int) $i);
1085 if ($c === null) {
1086 continue;
1087 }
1088 $colors[] = $c;
1089 }
1090 $p = [
1091 'id' => (string) $row['id'],
1092 'name' => (string) $row['name'],
1093 'people' => (string) $row['people'],
1094 'jumpsToClear' => (float) $row['jumps_to_clear'],
1095 'fallTime' => (float) $row['fall_time'],
1096 'riseTime' => (float) $row['rise_time'],
1097 'colors' => $colors,
1098 'custom' => true,
1099 'owner_id' => (string) $row['user_id'],
1100 ];
1101 return Planets::presentData($p);
1102 }
1103
1104 public function profilePayload(string $userId): array
1105 {
1106 $points = $this->lifetimePoints($userId);
1107 return [
1108 'lifetime_points' => $points,
1109 'locale' => $this->locale($userId),
1110 'blocks' => Blocks::present($points),
1111 'planets' => $this->listCustomPlanets($userId),
1112 ];
1113 }
1114
1115 private static function clampFloat(float $value, float $lo, float $hi): float
1116 {
1117 return max($lo, min($hi, $value));
1118 }
1119
1120
728 1121 }
@@ -2,6 +2,7 @@
2declare(strict_types=1);
2declare(strict_types=1);
3
3
4require_once __DIR__ . '/Planets.php';
4require_once __DIR__ . '/Planets.php';
5require_once __DIR__ . '/Blocks.php';
5
6
6final class Store
7final class Store
7{
8{
@@ -74,9 +75,46 @@ CREATE TABLE IF NOT EXISTS shots (
74CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
75CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
75SQL);
76SQL);
76 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
77 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
78 $this->ensureColumn('members', 'planet_json', 'TEXT');
77 $this->ensureColumn('shots', 'land_col', 'INTEGER');
79 $this->ensureColumn('shots', 'land_col', 'INTEGER');
78 $this->ensureColumn('shots', 'from_col', 'INTEGER');
80 $this->ensureColumn('shots', 'from_col', 'INTEGER');
79 $this->ensureColumn('shots', 'from_y', 'REAL');
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);
80 }
118 }
81
119
82 private function ensureColumn(string $table, string $column, string $ddl): void
120 private function ensureColumn(string $table, string $column, string $ddl): void
@@ -111,9 +149,12 @@ SQL);
111 }
149 }
112 }
150 }
113
151
152 /** Tests may freeze the clock without sleeping. */
153 public ?int $testNow = null;
154
114 private function now(): int
155 private function now(): int
115 {
156 {
116 return time();
157 return $this->testNow ?? time();
117 }
158 }
118
159
119 private function nowf(): float
160 private function nowf(): float
@@ -205,11 +246,11 @@ SQL);
205 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
246 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
206 VALUES (?,?,?,?,?,?,?)'
247 VALUES (?,?,?,?,?,?,?)'
207 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
248 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
208 $planet = Planets::known($planetId) ? $planetId : Planets::defaultId();
249 $choice = $this->choosePlanet($userId, $planetId, false);
209 $this->pdo->prepare(
250 $this->pdo->prepare(
210 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
251 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json)
211 VALUES (?,?,?,0,?,?,?)'
252 VALUES (?,?,?,0,?,?,?,?)'
212 )->execute([$id, $userId, $name, $now, $now, $planet]);
253 )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
213 return $this->getLobby($id);
254 return $this->getLobby($id);
214 });
255 });
215 }
256 }
@@ -236,9 +277,10 @@ SQL);
236 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
277 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
237 }
278 }
238 $now = $this->now();
279 $now = $this->now();
280 $choice = $this->choosePlanet($userId, $planetId, false);
239 $this->pdo->prepare(
281 $this->pdo->prepare(
240 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id)
282 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json)
241 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
283 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?)
242 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
284 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
243 name = excluded.name,
285 name = excluded.name,
244 ready = 0,
286 ready = 0,
@@ -249,8 +291,9 @@ SQL);
249 last_seen = excluded.last_seen,
291 last_seen = excluded.last_seen,
250 score = 0,
292 score = 0,
251 snapshot = NULL,
293 snapshot = NULL,
252 planet_id = excluded.planet_id'
294 planet_id = excluded.planet_id,
253 )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
295 planet_json = excluded.planet_json'
296 )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
254 return $this->getLobby($lobby['id']);
297 return $this->getLobby($lobby['id']);
255 });
298 });
256 }
299 }
@@ -352,12 +395,10 @@ SQL);
352 if ($lobby['status'] !== 'waiting') {
395 if ($lobby['status'] !== 'waiting') {
353 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
396 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
354 }
397 }
355 if (!Planets::known($planetId)) {
398 $choice = $this->choosePlanet($userId, $planetId, true);
356 throw new RuntimeException('Onbekende planeet.');
357 }
358 $this->pdo->prepare(
399 $this->pdo->prepare(
359 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
400 'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
360 )->execute([$planetId, $this->now(), $lobby['id'], $userId]);
401 )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]);
361 return $this->getLobby($lobby['id']);
402 return $this->getLobby($lobby['id']);
362 });
403 });
363 }
404 }
@@ -368,6 +409,12 @@ SQL);
368 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
409 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
369 return max(0.0, min(1.0, $this->testMissOverride));
410 return max(0.0, min(1.0, $this->testMissOverride));
370 }
411 }
412 if (!empty($member['planet_json'])) {
413 $data = json_decode((string) $member['planet_json'], true);
414 if (is_array($data)) {
415 return Planets::missChance($data);
416 }
417 }
371 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
418 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
372 return Planets::missChanceForId($id);
419 return Planets::missChanceForId($id);
373 }
420 }
@@ -662,6 +709,7 @@ SQL);
662 if ($lobby['status'] === 'playing') {
709 if ($lobby['status'] === 'playing') {
663 $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
710 $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
664 }
711 }
712 $this->maybeAwardOnlineLobby($lobby);
665 return [
713 return [
666 'lobby' => $this->presentLobby($lobby, $userId),
714 'lobby' => $this->presentLobby($lobby, $userId),
667 'incoming' => $incoming,
715 'incoming' => $incoming,
@@ -691,7 +739,7 @@ SQL);
691 'is_me' => $m['user_id'] === $userId,
739 'is_me' => $m['user_id'] === $userId,
692 'score' => (int) $m['score'],
740 'score' => (int) $m['score'],
693 'snapshot' => $m['user_id'] === $userId ? null : $snap,
741 'snapshot' => $m['user_id'] === $userId ? null : $snap,
694 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())),
742 'planet' => $this->presentMemberPlanet($m),
695 ];
743 ];
696 }
744 }
697 $rankings = [];
745 $rankings = [];
@@ -725,4 +773,349 @@ SQL);
725 'podium_seconds' => METEORS_PODIUM_SECONDS,
773 'podium_seconds' => METEORS_PODIUM_SECONDS,
726 ];
774 ];
727 }
775 }
776
777 public const MAX_CUSTOM_PLANETS = 30;
778 public const MAX_GAME_POINTS = 10000;
779 public const MAX_POINTS_PER_SEC = 4.0;
780 public const MIN_PLAY_SECONDS = 3;
781 public const PLAY_TOKEN_TTL = 21600;
782 public const NAME_MAX = 32;
783
784 /** @return array{planet_id:string,planet_json:?string} */
785 public function choosePlanet(string $userId, string $planetId, bool $strict): array
786 {
787 if ($planetId === '') {
788 if ($strict) {
789 throw new RuntimeException('Onbekende planeet.');
790 }
791 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
792 }
793 if (Planets::known($planetId)) {
794 return ['planet_id' => $planetId, 'planet_json' => null];
795 }
796 $row = $this->ownedCustom($userId, $planetId);
797 if ($row) {
798 return [
799 'planet_id' => $planetId,
800 'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE),
801 ];
802 }
803 if ($strict) {
804 throw new RuntimeException('Onbekende planeet.');
805 }
806 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
807 }
808
809 /** @param array<string,mixed> $member */
810 public function presentMemberPlanet(array $member): array
811 {
812 if (!empty($member['planet_json'])) {
813 $data = json_decode((string) $member['planet_json'], true);
814 if (is_array($data) && !empty($data['id'])) {
815 return Planets::presentData($data);
816 }
817 }
818 return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId()));
819 }
820
821 public function ensureProfile(string $userId): array
822 {
823 $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
824 $stmt->execute([$userId]);
825 $row = $stmt->fetch();
826 if ($row) {
827 return $row;
828 }
829 $now = $this->now();
830 $this->pdo->prepare(
831 'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)'
832 )->execute([$userId, $now]);
833 return [
834 'user_id' => $userId,
835 'lifetime_points' => 0,
836 'locale' => null,
837 'updated' => $now,
838 ];
839 }
840
841 public function lifetimePoints(string $userId): int
842 {
843 return (int) $this->ensureProfile($userId)['lifetime_points'];
844 }
845
846 public function locale(string $userId): ?string
847 {
848 $v = $this->ensureProfile($userId)['locale'] ?? null;
849 return is_string($v) && $v !== '' ? $v : null;
850 }
851
852 /** @var list<string> */
853 public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
854
855 public function setLocale(string $userId, string $locale): string
856 {
857 $locale = strtolower($locale);
858 if (!in_array($locale, self::LOCALES, true)) {
859 throw new RuntimeException('Onbekende taal.');
860 }
861 $this->ensureProfile($userId);
862 $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
863 ->execute([$locale, $this->now(), $userId]);
864 return $locale;
865 }
866
867 /**
868 * Add points once for a unique award_key. Returns the new lifetime total.
869 * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op.
870 */
871 public function awardPoints(string $userId, int $points, string $key, string $mode): int
872 {
873 return $this->transaction(function () use ($userId, $points, $key, $mode) {
874 $this->ensureProfile($userId);
875 $points = max(0, min(self::MAX_GAME_POINTS, $points));
876 $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
877 $stmt->execute([$key]);
878 if ($stmt->fetch()) {
879 return $this->lifetimePoints($userId);
880 }
881 $this->pdo->prepare(
882 'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)'
883 )->execute([$key, $userId, $mode, $points, $this->now()]);
884 if ($points > 0) {
885 $this->pdo->prepare(
886 'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?'
887 )->execute([$points, $this->now(), $userId]);
888 }
889 return $this->lifetimePoints($userId);
890 });
891 }
892
893 public function playBegin(string $userId, string $mode): array
894 {
895 if (!in_array($mode, ['solo', 'offline'], true)) {
896 throw new RuntimeException('Onbekende speelmodus.');
897 }
898 $token = bin2hex(random_bytes(16));
899 $this->pdo->prepare(
900 'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)'
901 )->execute([$token, $userId, $mode, $this->now()]);
902 return ['token' => $token, 'started' => $this->now()];
903 }
904
905 public function playFinish(string $userId, string $token, int $score): array
906 {
907 return $this->transaction(function () use ($userId, $token, $score) {
908 $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?');
909 $stmt->execute([$token]);
910 $ses = $stmt->fetch();
911 if (!$ses || $ses['user_id'] !== $userId) {
912 throw new RuntimeException('Ongeldige speelsessie.');
913 }
914 $key = 'play:' . $token;
915 if ($ses['finished'] !== null) {
916 return [
917 'lifetime_points' => $this->lifetimePoints($userId),
918 'awarded' => 0,
919 'already' => true,
920 ];
921 }
922 $now = $this->now();
923 $started = (int) $ses['started'];
924 if ($now - $started > self::PLAY_TOKEN_TTL) {
925 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
926 ->execute([$now, $token]);
927 throw new RuntimeException('Speelsessie is verlopen.');
928 }
929 $duration = max(0, $now - $started);
930 $score = max(0, $score);
931 $awarded = 0;
932 if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) {
933 $awarded = 0;
934 } else {
935 $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC);
936 $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0)));
937 }
938 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
939 ->execute([$now, $token]);
940 $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']);
941 return [
942 'lifetime_points' => $total,
943 'awarded' => $awarded,
944 'already' => false,
945 ];
946 });
947 }
948
949 /** @param array<string,mixed> $lobby */
950 public function maybeAwardOnlineLobby(array $lobby): void
951 {
952 $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
953 foreach ($this->members($lobby['id'], true) as $m) {
954 if (!$finished && empty($m['eliminated'])) {
955 continue;
956 }
957 $uid = (string) $m['user_id'];
958 $key = 'online:' . $lobby['id'] . ':' . $uid;
959 $this->awardPoints($uid, (int) $m['score'], $key, 'online');
960 }
961 }
962
963 /** @return ?array<string,mixed> */
964 public function ownedCustom(string $userId, string $id): ?array
965 {
966 $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?');
967 $stmt->execute([$id, $userId]);
968 $row = $stmt->fetch();
969 return $row ?: null;
970 }
971
972 /** @return list<array<string,mixed>> */
973 public function listCustomPlanets(string $userId): array
974 {
975 $stmt = $this->pdo->prepare(
976 'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC'
977 );
978 $stmt->execute([$userId]);
979 $out = [];
980 foreach ($stmt->fetchAll() as $row) {
981 $out[] = $this->snapshotCustom($row);
982 }
983 return $out;
984 }
985
986 public static function sanitizeName(string $raw, string $field): string
987 {
988 $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? '');
989 $s = strip_tags($s);
990 if ($s === '') {
991 throw new RuntimeException('Vul een ' . $field . ' in.');
992 }
993 if (mb_strlen($s) > self::NAME_MAX) {
994 $s = mb_substr($s, 0, self::NAME_MAX);
995 }
996 return $s;
997 }
998
999 /**
1000 * Create or update a custom planet owned by $userId.
1001 * @param array<string,mixed> $data
1002 * @return array<string,mixed> snapshot
1003 */
1004 public function saveCustomPlanet(string $userId, array $data): array
1005 {
1006 return $this->transaction(function () use ($userId, $data) {
1007 $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam');
1008 $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam');
1009 $j = self::clampFloat((float) ($data['jumpsToClear'] ?? 2), 1, 4);
1010 $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5);
1011 $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3);
1012 $ids = $data['colors'] ?? $data['blocks'] ?? [];
1013 if (!is_array($ids) || count($ids) !== 5) {
1014 throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.');
1015 }
1016 $points = $this->lifetimePoints($userId);
1017 $blockIds = [];
1018 foreach ($ids as $entry) {
1019 if (is_array($entry)) {
1020 $bid = (string) ($entry['block'] ?? $entry['id'] ?? '');
1021 } else {
1022 $bid = (string) $entry;
1023 }
1024 if ($bid === '' || !Blocks::known($bid)) {
1025 throw new RuntimeException('Onbekend blokje.');
1026 }
1027 if (!Blocks::unlockedId($bid, $points)) {
1028 throw new RuntimeException('Dit blokje is nog niet ontgrendeld.');
1029 }
1030 if (in_array($bid, $blockIds, true)) {
1031 throw new RuntimeException('Elk blokje mag maar in één vak.');
1032 }
1033 $blockIds[] = $bid;
1034 }
1035 $now = $this->now();
1036 $id = isset($data['id']) ? (string) $data['id'] : '';
1037 if ($id !== '') {
1038 $row = $this->ownedCustom($userId, $id);
1039 if (!$row) {
1040 throw new RuntimeException('Onbekende planeet.');
1041 }
1042 $this->pdo->prepare(
1043 'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?'
1044 )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]);
1045 } else {
1046 $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?');
1047 $stmt->execute([$userId]);
1048 if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) {
1049 throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.');
1050 }
1051 $id = 'c_' . bin2hex(random_bytes(8));
1052 $this->pdo->prepare(
1053 'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated)
1054 VALUES (?,?,?,?,?,?,?,?,?,?)'
1055 )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]);
1056 }
1057 $row = $this->ownedCustom($userId, $id);
1058 if (!$row) {
1059 throw new RuntimeException('Opslaan is mislukt.');
1060 }
1061 return $this->snapshotCustom($row);
1062 });
1063 }
1064
1065 public function deleteCustomPlanet(string $userId, string $id): void
1066 {
1067 $row = $this->ownedCustom($userId, $id);
1068 if (!$row) {
1069 throw new RuntimeException('Onbekende planeet.');
1070 }
1071 $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?')
1072 ->execute([$id, $userId]);
1073 }
1074
1075 /** @param array<string,mixed> $row */
1076 public function snapshotCustom(array $row): array
1077 {
1078 $ids = json_decode((string) $row['colors'], true);
1079 if (!is_array($ids)) {
1080 $ids = [];
1081 }
1082 $colors = [];
1083 foreach ($ids as $i => $id) {
1084 $c = Blocks::asColor((string) $id, (int) $i);
1085 if ($c === null) {
1086 continue;
1087 }
1088 $colors[] = $c;
1089 }
1090 $p = [
1091 'id' => (string) $row['id'],
1092 'name' => (string) $row['name'],
1093 'people' => (string) $row['people'],
1094 'jumpsToClear' => (float) $row['jumps_to_clear'],
1095 'fallTime' => (float) $row['fall_time'],
1096 'riseTime' => (float) $row['rise_time'],
1097 'colors' => $colors,
1098 'custom' => true,
1099 'owner_id' => (string) $row['user_id'],
1100 ];
1101 return Planets::presentData($p);
1102 }
1103
1104 public function profilePayload(string $userId): array
1105 {
1106 $points = $this->lifetimePoints($userId);
1107 return [
1108 'lifetime_points' => $points,
1109 'locale' => $this->locale($userId),
1110 'blocks' => Blocks::present($points),
1111 'planets' => $this->listCustomPlanets($userId),
1112 ];
1113 }
1114
1115 private static function clampFloat(float $value, float $lo, float $hi): float
1116 {
1117 return max($lo, min($hi, $value));
1118 }
1119
1120
728}
1121}