| 1 | <?php |
| 2 | declare(strict_types=1); |
| 3 | |
| 4 | require_once __DIR__ . '/Engine.php'; |
| 5 | require_once __DIR__ . '/I18n.php'; |
| 6 | |
| 7 | final 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 . '/allianties.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' |
| 39 | CREATE TABLE IF NOT EXISTS games ( |
| 40 | id TEXT PRIMARY KEY, |
| 41 | code TEXT UNIQUE NOT NULL, |
| 42 | host_id TEXT NOT NULL, |
| 43 | status TEXT NOT NULL, |
| 44 | payload TEXT NOT NULL, |
| 45 | updated INTEGER NOT NULL |
| 46 | ); |
| 47 | CREATE INDEX IF NOT EXISTS games_status ON games (status); |
| 48 | CREATE TABLE IF NOT EXISTS members ( |
| 49 | game_id TEXT NOT NULL, |
| 50 | user_id TEXT NOT NULL, |
| 51 | PRIMARY KEY (game_id, user_id) |
| 52 | ); |
| 53 | CREATE INDEX IF NOT EXISTS members_user ON members (user_id); |
| 54 | CREATE TABLE IF NOT EXISTS profiles ( |
| 55 | user_id TEXT PRIMARY KEY, |
| 56 | locale TEXT, |
| 57 | avatar TEXT, |
| 58 | name TEXT, |
| 59 | updated INTEGER NOT NULL |
| 60 | ); |
| 61 | SQL); |
| 62 | } |
| 63 | |
| 64 | /** @template T @param callable():T $fn @return T */ |
| 65 | public function tx(callable $fn): mixed |
| 66 | { |
| 67 | if ($this->txDepth === 0) { |
| 68 | $this->pdo->exec('BEGIN IMMEDIATE'); |
| 69 | } |
| 70 | $this->txDepth++; |
| 71 | try { |
| 72 | $result = $fn(); |
| 73 | $this->txDepth--; |
| 74 | if ($this->txDepth === 0) { |
| 75 | $this->pdo->exec('COMMIT'); |
| 76 | } |
| 77 | return $result; |
| 78 | } catch (Throwable $e) { |
| 79 | if ($this->txDepth > 0) { |
| 80 | $this->txDepth = 0; |
| 81 | try { |
| 82 | $this->pdo->exec('ROLLBACK'); |
| 83 | } catch (Throwable $ignored) { |
| 84 | } |
| 85 | } |
| 86 | throw $e; |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | public function now(): int |
| 91 | { |
| 92 | return Engine::now(); |
| 93 | } |
| 94 | |
| 95 | private function save(array $game): void |
| 96 | { |
| 97 | $now = $this->now(); |
| 98 | $stmt = $this->pdo->prepare( |
| 99 | 'INSERT INTO games (id, code, host_id, status, payload, updated) |
| 100 | VALUES (:id, :code, :host, :status, :payload, :updated) |
| 101 | ON CONFLICT(id) DO UPDATE SET |
| 102 | code = excluded.code, |
| 103 | host_id = excluded.host_id, |
| 104 | status = excluded.status, |
| 105 | payload = excluded.payload, |
| 106 | updated = excluded.updated' |
| 107 | ); |
| 108 | $stmt->execute([ |
| 109 | ':id' => $game['id'], |
| 110 | ':code' => $game['code'], |
| 111 | ':host' => $game['host_id'], |
| 112 | ':status' => $game['status'], |
| 113 | ':payload' => json_encode($game, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), |
| 114 | ':updated' => $now, |
| 115 | ]); |
| 116 | $this->pdo->prepare('DELETE FROM members WHERE game_id = ?')->execute([$game['id']]); |
| 117 | $ins = $this->pdo->prepare('INSERT INTO members (game_id, user_id) VALUES (?, ?)'); |
| 118 | foreach ($game['players'] as $p) { |
| 119 | $ins->execute([$game['id'], $p['id']]); |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | private function deleteGame(string $id): void |
| 124 | { |
| 125 | $this->pdo->prepare('DELETE FROM members WHERE game_id = ?')->execute([$id]); |
| 126 | $this->pdo->prepare('DELETE FROM games WHERE id = ?')->execute([$id]); |
| 127 | } |
| 128 | |
| 129 | public function load(string $id): ?array |
| 130 | { |
| 131 | $stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?'); |
| 132 | $stmt->execute([$id]); |
| 133 | $row = $stmt->fetch(); |
| 134 | if (!$row) { |
| 135 | return null; |
| 136 | } |
| 137 | $game = json_decode((string) $row['payload'], true); |
| 138 | return is_array($game) ? $game : null; |
| 139 | } |
| 140 | |
| 141 | public function loadByCode(string $code): ?array |
| 142 | { |
| 143 | $code = self::normalizeCode($code); |
| 144 | $stmt = $this->pdo->prepare('SELECT payload FROM games WHERE code = ?'); |
| 145 | $stmt->execute([$code]); |
| 146 | $row = $stmt->fetch(); |
| 147 | if (!$row) { |
| 148 | return null; |
| 149 | } |
| 150 | $game = json_decode((string) $row['payload'], true); |
| 151 | return is_array($game) ? $game : null; |
| 152 | } |
| 153 | |
| 154 | public static function normalizeCode(string $code): string |
| 155 | { |
| 156 | $code = strtoupper(trim($code)); |
| 157 | // Generated codes use Crockford-ish chars (no 0/O/I/1/L). Map lookalikes. |
| 158 | $code = strtr($code, ['O' => '0', 'I' => '1', 'L' => '1']); |
| 159 | $code = preg_replace('/[^A-Z0-9]/', '', $code) ?? ''; |
| 160 | return $code; |
| 161 | } |
| 162 | |
| 163 | /** |
| 164 | * Load, apply due events, run $fn, save. $fn receives and returns the game |
| 165 | * (or null to delete). Locked with BEGIN IMMEDIATE. |
| 166 | * |
| 167 | * @param callable(array):(?array) $fn |
| 168 | */ |
| 169 | public function mutate(string $id, callable $fn): ?array |
| 170 | { |
| 171 | return $this->tx(function () use ($id, $fn) { |
| 172 | $stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?'); |
| 173 | $stmt->execute([$id]); |
| 174 | $row = $stmt->fetch(); |
| 175 | if (!$row) { |
| 176 | throw new RuntimeException('unknown_code'); |
| 177 | } |
| 178 | $game = json_decode((string) $row['payload'], true); |
| 179 | if (!is_array($game)) { |
| 180 | throw new RuntimeException('unknown_code'); |
| 181 | } |
| 182 | $game = Engine::applyDue($game, $this->now()); |
| 183 | $game = $fn($game); |
| 184 | if ($game === null) { |
| 185 | $this->deleteGame($id); |
| 186 | return null; |
| 187 | } |
| 188 | $this->save($game); |
| 189 | return $game; |
| 190 | }); |
| 191 | } |
| 192 | |
| 193 | public function createLobby(string $userId, string $name, ?string $avatar, array $rules = []): array |
| 194 | { |
| 195 | return $this->tx(function () use ($userId, $name, $avatar, $rules) { |
| 196 | $now = $this->now(); |
| 197 | $id = Engine::generateId(); |
| 198 | $code = $this->uniqueCode(); |
| 199 | $game = Engine::newLobby($id, $code, $userId, $name, $avatar, $rules, $now); |
| 200 | $this->save($game); |
| 201 | $this->touchProfile($userId, $name, $avatar); |
| 202 | return $game; |
| 203 | }); |
| 204 | } |
| 205 | |
| 206 | private function uniqueCode(): string |
| 207 | { |
| 208 | for ($i = 0; $i < 16; $i++) { |
| 209 | $code = Engine::generateCode(); |
| 210 | $stmt = $this->pdo->prepare('SELECT 1 FROM games WHERE code = ?'); |
| 211 | $stmt->execute([$code]); |
| 212 | if (!$stmt->fetch()) { |
| 213 | return $code; |
| 214 | } |
| 215 | } |
| 216 | throw new RuntimeException('generic'); |
| 217 | } |
| 218 | |
| 219 | public function joinByCode(string $userId, string $name, ?string $avatar, string $code): array |
| 220 | { |
| 221 | $code = self::normalizeCode($code); |
| 222 | if (strlen($code) < 4) { |
| 223 | throw new RuntimeException('unknown_code'); |
| 224 | } |
| 225 | return $this->tx(function () use ($userId, $name, $avatar, $code) { |
| 226 | $stmt = $this->pdo->prepare('SELECT id, payload FROM games WHERE code = ?'); |
| 227 | $stmt->execute([$code]); |
| 228 | $row = $stmt->fetch(); |
| 229 | if (!$row) { |
| 230 | throw new RuntimeException('unknown_code'); |
| 231 | } |
| 232 | $game = json_decode((string) $row['payload'], true); |
| 233 | if (!is_array($game)) { |
| 234 | throw new RuntimeException('unknown_code'); |
| 235 | } |
| 236 | $game = Engine::applyDue($game, $this->now()); |
| 237 | if ($game['status'] === 'lobby') { |
| 238 | $game = Engine::join($game, $userId, $name, $avatar, $this->now()); |
| 239 | $this->save($game); |
| 240 | } elseif (Engine::playerIndex($game, $userId) === null) { |
| 241 | throw new RuntimeException('game_started'); |
| 242 | } else { |
| 243 | $this->save($game); // persist any due distributions |
| 244 | } |
| 245 | $this->touchProfile($userId, $name, $avatar); |
| 246 | return $game; |
| 247 | }); |
| 248 | } |
| 249 | |
| 250 | public function leaveLobby(string $userId, string $gameId): ?array |
| 251 | { |
| 252 | return $this->mutate($gameId, function (array $game) use ($userId) { |
| 253 | return Engine::leaveLobby($game, $userId, $this->now()); |
| 254 | }); |
| 255 | } |
| 256 | |
| 257 | public function setRules(string $userId, string $gameId, array $rules): array |
| 258 | { |
| 259 | $game = $this->mutate($gameId, function (array $game) use ($userId, $rules) { |
| 260 | return Engine::setLobbyRules($game, $userId, $rules); |
| 261 | }); |
| 262 | if ($game === null) { |
| 263 | throw new RuntimeException('unknown_code'); |
| 264 | } |
| 265 | return $game; |
| 266 | } |
| 267 | |
| 268 | public function startGame(string $userId, string $gameId): array |
| 269 | { |
| 270 | $game = $this->mutate($gameId, function (array $game) use ($userId) { |
| 271 | return Engine::start($game, $userId, $this->now()); |
| 272 | }); |
| 273 | if ($game === null) { |
| 274 | throw new RuntimeException('unknown_code'); |
| 275 | } |
| 276 | return $game; |
| 277 | } |
| 278 | |
| 279 | public function act(string $userId, string $gameId, array $action): array |
| 280 | { |
| 281 | $game = $this->mutate($gameId, function (array $game) use ($userId, $action) { |
| 282 | return Engine::applyAction($game, $userId, $action, $this->now()); |
| 283 | }); |
| 284 | if ($game === null) { |
| 285 | throw new RuntimeException('unknown_code'); |
| 286 | } |
| 287 | return $game; |
| 288 | } |
| 289 | |
| 290 | public function setNote(string $userId, string $gameId, string $subjectId, string $text): array |
| 291 | { |
| 292 | $game = $this->mutate($gameId, function (array $game) use ($userId, $subjectId, $text) { |
| 293 | return Engine::setNote($game, $userId, $subjectId, $text); |
| 294 | }); |
| 295 | if ($game === null) { |
| 296 | throw new RuntimeException('unknown_code'); |
| 297 | } |
| 298 | return $game; |
| 299 | } |
| 300 | |
| 301 | public function addMessage(string $userId, string $gameId, string $toId, string $text): array |
| 302 | { |
| 303 | $game = $this->mutate($gameId, function (array $game) use ($userId, $toId, $text) { |
| 304 | return Engine::addMessage($game, $userId, $toId, $text, $this->now()); |
| 305 | }); |
| 306 | if ($game === null) { |
| 307 | throw new RuntimeException('unknown_code'); |
| 308 | } |
| 309 | return $game; |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Local-dev helper: set next_distribution_at to $at (or now) so applyDue |
| 314 | * runs on the next mutate/present. |
| 315 | */ |
| 316 | public function debugAdvance(string $userId, string $gameId, ?int $at = null, int $days = 1): array |
| 317 | { |
| 318 | if (!localDev()) { |
| 319 | throw new RuntimeException('generic'); |
| 320 | } |
| 321 | $at = $at ?? $this->now(); |
| 322 | $game = $this->mutate($gameId, function (array $game) use ($userId, $at, $days) { |
| 323 | if (Engine::playerIndex($game, $userId) === null) { |
| 324 | throw new RuntimeException('not_in_game'); |
| 325 | } |
| 326 | if ($game['status'] !== 'running') { |
| 327 | throw new RuntimeException('game_finished'); |
| 328 | } |
| 329 | // Walk `$days` midnights into the past relative to "now" by |
| 330 | // setting next_distribution_at to a due timestamp, then applyDue |
| 331 | // already ran at the start of mutate — so we set it and apply again. |
| 332 | $target = $at; |
| 333 | $game['next_distribution_at'] = $target; |
| 334 | for ($i = 0; $i < max(1, $days); $i++) { |
| 335 | $game = Engine::applyDue($game, (int) $game['next_distribution_at']); |
| 336 | // applyDue moves next to the following midnight; to apply more, |
| 337 | // pull it back to "due" by using that new next as the time. |
| 338 | if ($i < $days - 1 && $game['status'] === 'running') { |
| 339 | $game = Engine::applyDue($game, (int) $game['next_distribution_at']); |
| 340 | } |
| 341 | } |
| 342 | return $game; |
| 343 | }); |
| 344 | if ($game === null) { |
| 345 | throw new RuntimeException('unknown_code'); |
| 346 | } |
| 347 | return $game; |
| 348 | } |
| 349 | |
| 350 | public function present(string $userId, string $gameId): array |
| 351 | { |
| 352 | $game = $this->mutate($gameId, function (array $game) use ($userId) { |
| 353 | if (Engine::playerIndex($game, $userId) === null) { |
| 354 | throw new RuntimeException('not_in_game'); |
| 355 | } |
| 356 | return $game; |
| 357 | }); |
| 358 | if ($game === null) { |
| 359 | throw new RuntimeException('unknown_code'); |
| 360 | } |
| 361 | return $this->view($game, $userId); |
| 362 | } |
| 363 | |
| 364 | public function view(array $game, string $userId): array |
| 365 | { |
| 366 | if ($game['status'] === 'lobby') { |
| 367 | return Engine::lobbyView($game, $userId); |
| 368 | } |
| 369 | return Engine::present($game, $userId, $this->now()); |
| 370 | } |
| 371 | |
| 372 | public function sync(string $userId, string $gameId, int $since): array |
| 373 | { |
| 374 | return $this->tx(function () use ($userId, $gameId, $since) { |
| 375 | $stmt = $this->pdo->prepare('SELECT payload FROM games WHERE id = ?'); |
| 376 | $stmt->execute([$gameId]); |
| 377 | $row = $stmt->fetch(); |
| 378 | if (!$row) { |
| 379 | throw new RuntimeException('unknown_code'); |
| 380 | } |
| 381 | $game = json_decode((string) $row['payload'], true); |
| 382 | if (!is_array($game) || Engine::playerIndex($game, $userId) === null) { |
| 383 | throw new RuntimeException('not_in_game'); |
| 384 | } |
| 385 | $before = (int) ($game['version'] ?? 0); |
| 386 | $due = Engine::applyDue($game, $this->now()); |
| 387 | if ($due !== $game || (int) ($due['version'] ?? 0) !== $before) { |
| 388 | $this->save($due); |
| 389 | $game = $due; |
| 390 | } else { |
| 391 | $game = $due; |
| 392 | } |
| 393 | $version = (int) ($game['version'] ?? 0); |
| 394 | $now = $this->now(); |
| 395 | $light = [ |
| 396 | 'ok' => true, |
| 397 | 'changed' => $version !== $since, |
| 398 | 'version' => $version, |
| 399 | 'server_now' => $now, |
| 400 | 'status' => $game['status'], |
| 401 | 'next_distribution_at' => $game['next_distribution_at'] ?? null, |
| 402 | 'ceasefire' => Engine::ceasefireInfo($game, $now), |
| 403 | 'day' => (int) ($game['day'] ?? 0), |
| 404 | ]; |
| 405 | if ($version !== $since) { |
| 406 | $light['game'] = $this->view($game, $userId); |
| 407 | } |
| 408 | return $light; |
| 409 | }); |
| 410 | } |
| 411 | |
| 412 | /** @return list<array> */ |
| 413 | public function listFor(string $userId): array |
| 414 | { |
| 415 | $stmt = $this->pdo->prepare( |
| 416 | 'SELECT g.payload FROM members m JOIN games g ON g.id = m.game_id |
| 417 | WHERE m.user_id = ? ORDER BY g.updated DESC' |
| 418 | ); |
| 419 | $stmt->execute([$userId]); |
| 420 | $out = []; |
| 421 | $now = $this->now(); |
| 422 | foreach ($stmt->fetchAll() as $row) { |
| 423 | $game = json_decode((string) $row['payload'], true); |
| 424 | if (!is_array($game)) { |
| 425 | continue; |
| 426 | } |
| 427 | // Don't mutate here (listing is read-mostly); applyDue is cheap and |
| 428 | // in-memory only so the menu stays accurate if a day rolled over. |
| 429 | $game = Engine::applyDue($game, $now); |
| 430 | $me = Engine::player($game, $userId); |
| 431 | $alive = count(Engine::living($game)); |
| 432 | $out[] = [ |
| 433 | 'id' => $game['id'], |
| 434 | 'code' => $game['code'], |
| 435 | 'status' => $game['status'], |
| 436 | 'host_id' => $game['host_id'], |
| 437 | 'is_host' => $game['host_id'] === $userId, |
| 438 | 'players' => count($game['players']), |
| 439 | 'alive' => $alive, |
| 440 | 'day' => (int) ($game['day'] ?? 0), |
| 441 | 'winner_id' => $game['winner_id'] ?? null, |
| 442 | 'draw' => !empty($game['draw']), |
| 443 | 'you_alive' => $me ? !empty($me['alive']) : false, |
| 444 | 'you_won' => ($game['winner_id'] ?? null) === $userId, |
| 445 | 'names' => array_map(fn ($p) => [ |
| 446 | 'id' => $p['id'], |
| 447 | 'name' => $p['name'], |
| 448 | 'color' => $p['color'] ?? null, |
| 449 | 'avatar' => $p['avatar'] ?? null, |
| 450 | ], $game['players']), |
| 451 | 'updated_at' => $game['started_at'] ?? $game['created_at'] ?? 0, |
| 452 | 'rules' => $game['rules'] ?? Engine::defaultRules(), |
| 453 | ]; |
| 454 | } |
| 455 | return $out; |
| 456 | } |
| 457 | |
| 458 | public function ensureProfile(string $userId): array |
| 459 | { |
| 460 | $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?'); |
| 461 | $stmt->execute([$userId]); |
| 462 | $row = $stmt->fetch(); |
| 463 | if ($row) { |
| 464 | return $row; |
| 465 | } |
| 466 | $this->pdo->prepare( |
| 467 | 'INSERT INTO profiles (user_id, locale, avatar, name, updated) VALUES (?, NULL, NULL, NULL, ?)' |
| 468 | )->execute([$userId, $this->now()]); |
| 469 | return [ |
| 470 | 'user_id' => $userId, |
| 471 | 'locale' => null, |
| 472 | 'avatar' => null, |
| 473 | 'name' => null, |
| 474 | 'updated' => $this->now(), |
| 475 | ]; |
| 476 | } |
| 477 | |
| 478 | public function touchProfile(string $userId, string $name, ?string $avatar): void |
| 479 | { |
| 480 | $this->ensureProfile($userId); |
| 481 | $this->pdo->prepare( |
| 482 | 'UPDATE profiles SET name = ?, avatar = COALESCE(?, avatar), updated = ? WHERE user_id = ?' |
| 483 | )->execute([$name, $avatar, $this->now(), $userId]); |
| 484 | } |
| 485 | |
| 486 | public function locale(string $userId): ?string |
| 487 | { |
| 488 | $v = $this->ensureProfile($userId)['locale'] ?? null; |
| 489 | return is_string($v) && $v !== '' ? $v : null; |
| 490 | } |
| 491 | |
| 492 | public function setLocale(string $userId, string $locale): string |
| 493 | { |
| 494 | $locale = strtolower($locale); |
| 495 | if ($locale === 'zh-hans' || $locale === 'zh-cn') { |
| 496 | $locale = 'zh'; |
| 497 | } |
| 498 | if (!in_array($locale, I18n::LOCALES, true)) { |
| 499 | throw new RuntimeException('generic'); |
| 500 | } |
| 501 | $this->ensureProfile($userId); |
| 502 | $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?') |
| 503 | ->execute([$locale, $this->now(), $userId]); |
| 504 | return $locale; |
| 505 | } |
| 506 | } |
projects-timfalken-com allianties