BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / bootstrap.php

bootstrap.php

feat: scaffold Synhex hex tactics on the Microchess lobby shell
timfa project_86226080_bot_b6e0858ac0a12dc6d49a8d25b3b0be9b · pushed by timfa · 2 months ago
24f20754 History
bootstrap.php 24.5 KiB Download Raw
1<?php
2declare(strict_types=1);
3require_once __DIR__.'/HexGrid.php';
4require_once __DIR__.'/SynhexSim.php';
5require_once __DIR__.'/SynhexMatch.php';
6require_once __DIR__.'/Push.php';
7require_once __DIR__.'/PieceColors.php';
8ini_set('display_errors','0');
9ini_set('log_errors','1');
10ini_set('error_log',dirname(__DIR__).'/data/php-errors.log');
11header('X-Content-Type-Options: nosniff');
12header('Referrer-Policy: same-origin');
13header("Content-Security-Policy: default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
14header('Cache-Control: no-store');
15
16function db(): PDO {
17 static $db;
18 if ($db) return $db;
19 $db=new PDO('sqlite:'.dirname(__DIR__).'/data/synhex.sqlite',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
20 $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
21 $db->exec('CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL);
22 CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL);
23 CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL);
24 CREATE TABLE IF NOT EXISTS friends (a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), PRIMARY KEY(a,b), CHECK(a<b));
25 CREATE TABLE IF NOT EXISTS friend_requests (a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), sender TEXT NOT NULL REFERENCES users(id), created INTEGER NOT NULL, PRIMARY KEY(a,b), CHECK(a<b), CHECK(sender=a OR sender=b));
26 CREATE TABLE IF NOT EXISTS links (token TEXT PRIMARY KEY, owner TEXT NOT NULL REFERENCES users(id), kind TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0);
27 CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), status TEXT NOT NULL, white TEXT, state TEXT, winner TEXT, reason TEXT, exit_a INTEGER DEFAULT 0, exit_b INTEGER DEFAULT 0, rematch_a INTEGER DEFAULT 0, rematch_b INTEGER DEFAULT 0, draw_offer TEXT, version INTEGER DEFAULT 0, created INTEGER NOT NULL);
28 CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL);
29 CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);');
30 $db->exec('CREATE TABLE IF NOT EXISTS push_subscriptions (endpoint TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), p256dh TEXT NOT NULL, auth TEXT NOT NULL, updated INTEGER NOT NULL); CREATE INDEX IF NOT EXISTS push_user ON push_subscriptions(user_id);');
31 $db->exec('CREATE TABLE IF NOT EXISTS notification_intro (user_id TEXT PRIMARY KEY REFERENCES users(id), seen_at INTEGER NOT NULL);');
32 $columns=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
33 if (!in_array('activity_at',$columns,true)) {
34 $db->exec('BEGIN IMMEDIATE');
35 try {
36 if (!in_array('activity_at',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
37 $db->exec('ALTER TABLE games ADD COLUMN activity_at INTEGER');
38 $db->exec("UPDATE games SET activity_at=CAST(strftime('%s','now') AS INTEGER) WHERE activity_at IS NULL");
39 }
40 $db->exec('COMMIT');
41 } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; }
42 }
43 // Replace legacy triggers once, including databases already migrated on newer SQLite.
44 $legacy=$db->query("SELECT sql FROM sqlite_master WHERE type='trigger' AND name IN ('games_activity_insert','games_activity_update')")->fetchAll(PDO::FETCH_COLUMN);
45 if (array_filter($legacy,static fn(string $sql): bool => stripos($sql,'unixepoch(')!==false)) {
46 $db->exec('BEGIN IMMEDIATE');
47 try {
48 $db->exec('DROP TRIGGER IF EXISTS games_activity_insert; DROP TRIGGER IF EXISTS games_activity_update;');
49 activityTriggers($db);
50 $db->exec('COMMIT');
51 } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; }
52 } else {
53 activityTriggers($db);
54 }
55 // Assign existing accounts once as well as newly created accounts.
56 foreach ($db->query('SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM user_avatars)')->fetchAll(PDO::FETCH_COLUMN) as $id) {
57 $avatars=avatarCatalog();
58 $q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)');
59 $q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
60 }
61 $db->exec('CREATE TABLE IF NOT EXISTS ratings (user_id TEXT PRIMARY KEY REFERENCES users(id), rating INTEGER NOT NULL DEFAULT 1200, played INTEGER NOT NULL DEFAULT 0);
62 CREATE TABLE IF NOT EXISTS rating_changes (result_id INTEGER PRIMARY KEY REFERENCES results(id), a_before INTEGER NOT NULL, b_before INTEGER NOT NULL, delta INTEGER NOT NULL);
63 CREATE TABLE IF NOT EXISTS matchmaking (user_id TEXT PRIMARY KEY REFERENCES users(id), joined INTEGER NOT NULL);
64 CREATE TABLE IF NOT EXISTS matchmaking_clock (id INTEGER PRIMARY KEY CHECK(id=1), checked INTEGER NOT NULL);
65 INSERT OR IGNORE INTO matchmaking_clock VALUES(1,0);');
66 $db->exec('CREATE TABLE IF NOT EXISTS replays (result_id INTEGER PRIMARY KEY REFERENCES results(id), white TEXT NOT NULL, moves BLOB NOT NULL);
67 CREATE INDEX IF NOT EXISTS results_ended ON results(ended);
68 CREATE TABLE IF NOT EXISTS replay_links (result_id INTEGER PRIMARY KEY REFERENCES replays(result_id), token TEXT NOT NULL UNIQUE);');
69 $db->exec('CREATE TABLE IF NOT EXISTS user_piece_colors (
70 user_id TEXT PRIMARY KEY REFERENCES users(id),
71 color_mode TEXT NOT NULL DEFAULT \'default\' CHECK(color_mode IN (\'default\',\'custom\')),
72 preferred_color TEXT NOT NULL DEFAULT \'White\',
73 alternative_color TEXT NOT NULL DEFAULT \'Black\',
74 disable_custom_colours INTEGER NOT NULL DEFAULT 0,
75 CHECK(preferred_color IN (\'White\',\'Black\',\'Red\',\'Blue\',\'Green\',\'Yellow\')),
76 CHECK(alternative_color IN (\'White\',\'Black\',\'Red\',\'Blue\',\'Green\',\'Yellow\')),
77 CHECK(preferred_color <> alternative_color)
78 );');
79 $pieceColorCols=$db->query('PRAGMA table_info(user_piece_colors)')->fetchAll(PDO::FETCH_COLUMN,1);
80 if (!in_array('disable_custom_colours',$pieceColorCols,true)) {
81 $db->exec('ALTER TABLE user_piece_colors ADD COLUMN disable_custom_colours INTEGER NOT NULL DEFAULT 0');
82 }
83 $gameCols=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
84 if (!in_array('piece_skin_white',$gameCols,true)) {
85 $db->exec('BEGIN IMMEDIATE');
86 try {
87 $gameCols=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
88 if (!in_array('piece_skin_white',$gameCols,true)) {
89 $db->exec('ALTER TABLE games ADD COLUMN piece_skin_white TEXT');
90 $db->exec('ALTER TABLE games ADD COLUMN piece_skin_black TEXT');
91 }
92 $db->exec('COMMIT');
93 } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; }
94 }
95 $replayCols=$db->query('PRAGMA table_info(replays)')->fetchAll(PDO::FETCH_COLUMN,1);
96 if (!in_array('piece_skin_white',$replayCols,true)) {
97 $db->exec('BEGIN IMMEDIATE');
98 try {
99 $replayCols=$db->query('PRAGMA table_info(replays)')->fetchAll(PDO::FETCH_COLUMN,1);
100 if (!in_array('piece_skin_white',$replayCols,true)) {
101 $db->exec('ALTER TABLE replays ADD COLUMN piece_skin_white TEXT');
102 $db->exec('ALTER TABLE replays ADD COLUMN piece_skin_black TEXT');
103 }
104 $db->exec('COMMIT');
105 } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; }
106 }
107
108 if (!in_array('turn_order',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
109 $db->exec('BEGIN IMMEDIATE');
110 try {
111 if (!in_array('turn_order',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
112 $db->exec('ALTER TABLE games ADD COLUMN turn_order INTEGER NOT NULL DEFAULT 0');
113 $db->exec('UPDATE games SET turn_order=id');
114 }
115 $db->exec('COMMIT');
116 } catch (Throwable $e) {$db->exec('ROLLBACK');throw $e;}
117 }
118 $db->exec("CREATE TRIGGER IF NOT EXISTS games_turn_insert AFTER INSERT ON games BEGIN UPDATE games SET turn_order=(SELECT COALESCE(MAX(turn_order),0)+1 FROM games) WHERE id=NEW.id; END;
119 CREATE TRIGGER IF NOT EXISTS games_turn_update AFTER UPDATE OF state ON games WHEN NEW.state IS NOT OLD.state BEGIN UPDATE games SET turn_order=(SELECT COALESCE(MAX(turn_order),0)+1 FROM games) WHERE id=NEW.id; END;");
120 $q=$db->query("SELECT r.id,r.state,g.white FROM results r JOIN games g ON g.id=r.game_id WHERE r.state=g.state AND g.status='ended' AND NOT EXISTS (SELECT 1 FROM replays p WHERE p.result_id=r.id)");
121 foreach ($q->fetchAll() as $r) {
122 $position=json_decode($r['state'],true);
123 if (!empty($position['history'])) {
124 try {saveReplay((int)$r['id'],$r['white'],$position);} catch (PDOException $e) {if ($e->getCode()!=='23000') throw $e;}
125 }
126 }
127
128 return $db;
129}
130function activityTriggers(PDO $db): void {
131 $db->exec("CREATE TRIGGER IF NOT EXISTS games_activity_insert AFTER INSERT ON games BEGIN UPDATE games SET activity_at=CAST(strftime('%s','now') AS INTEGER) WHERE id=NEW.id; END;
132 CREATE TRIGGER IF NOT EXISTS games_activity_update AFTER UPDATE OF version ON games BEGIN UPDATE games SET activity_at=CAST(strftime('%s','now') AS INTEGER) WHERE id=NEW.id; END;");
133}
134function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
135function profile(string $id): array {
136 $p=query('SELECT u.*,a.avatar,COALESCE(r.rating,1200) AS rating,COALESCE(r.played,0) AS ratedGames,COALESCE(c.color_mode,\'default\') AS colorMode,COALESCE(c.preferred_color,\'White\') AS preferredColor,COALESCE(c.alternative_color,\'Black\') AS alternativeColor,COALESCE(c.disable_custom_colours,0) AS disableCustomColours FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id LEFT JOIN ratings r ON r.user_id=u.id LEFT JOIN user_piece_colors c ON c.user_id=u.id WHERE u.id=?',[$id])->fetch();
137 if ($p) { $p['disableCustomColours'] = !empty($p['disableCustomColours']); }
138 return $p;
139}
140function avatarCatalog(): array {
141 static $avatars;
142 return $avatars ??= json_decode(file_get_contents(dirname(__DIR__).'/assets/avatars/catalog.json'),true,512,JSON_THROW_ON_ERROR);
143}
144final class DatabaseSessions implements SessionHandlerInterface {
145 public function open(string $path,string $name): bool {return true;}
146 public function close(): bool {return true;}
147 public function read(string $id): string|false {return query('SELECT payload FROM sessions WHERE id=? AND expires>?',[$id,time()])->fetchColumn()?:'';}
148 public function write(string $id,string $data): bool {query('INSERT OR REPLACE INTO sessions VALUES(?,?,?)',[$id,$data,time()+86400]);return true;}
149 public function destroy(string $id): bool {query('DELETE FROM sessions WHERE id=?',[$id]);return true;}
150 public function gc(int $max_lifetime): int|false {return query('DELETE FROM sessions WHERE expires<?',[time()])->rowCount();}
151}
152function localDev(): bool {
153 $host=parse_url('http://'.($_SERVER['HTTP_HOST']??''),PHP_URL_HOST);
154 return is_string($host) && in_array(strtolower($host),['localhost','127.0.0.1','[::1]'],true) && in_array($_SERVER['REMOTE_ADDR']??'', ['127.0.0.1','::1'],true);
155}
156function config(): array {
157 static $c;
158 if ($c !== null) return $c;
159 $path=dirname(__DIR__).'/data/config.php';
160 $lock=fopen(dirname(__DIR__).'/data/config.lock','c');
161 if ($lock===false) throw new RuntimeException('The data directory must be writable to initialize configuration.');
162 try {
163 if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock configuration.');
164 if (!file_exists($path)) {
165 $template="<?php\n// Fill in OAuth values on this server. Empty fields use environment variables.\n// Game balance knobs live in lib/game-config.php; optional overrides of those keys may be added here.\nreturn [\n 'base_url' => '',\n 'client_id' => '',\n 'client_secret' => '',\n];\n";
166 if (file_put_contents($path,$template)!==strlen($template)) throw new RuntimeException('Unable to create data/config.php.');
167 }
168 $values=require $path;
169 if (!is_array($values)) throw new RuntimeException('data/config.php must return an array.');
170 } finally {
171 flock($lock,LOCK_UN);
172 fclose($lock);
173 }
174 foreach (['base_url'=>'SYNHEX_BASE_URL','client_id'=>'SYNHEX_CLIENT_ID','client_secret'=>'SYNHEX_CLIENT_SECRET'] as $key=>$env) {
175 if (($values[$key]??'')==='') $values[$key]=getenv($env)?:'';
176 }
177 return $c=$values;
178}
179function gameConfig(): array {
180 static $g;
181 if ($g !== null) return $g;
182 $path=__DIR__.'/game-config.php';
183 $defaults=require $path;
184 if (!is_array($defaults)) throw new RuntimeException('lib/game-config.php must return an array.');
185 $overlay=config();
186 foreach ($defaults as $key=>$value) {
187 if (in_array($key,['base_url','client_id','client_secret'],true)) continue;
188 if (array_key_exists($key,$overlay) && $overlay[$key]!=='' && $overlay[$key]!==null) $defaults[$key]=$overlay[$key];
189 }
190 return $g=$defaults;
191}
192function baseUrl(): string {
193 if (localDev()) return 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/');
194 $base=rtrim(config()['base_url'],'/');
195 if (!str_starts_with($base,'https://')) throw new RuntimeException("Set 'base_url' in data/config.php to this application's production HTTPS URL, or set SYNHEX_BASE_URL. The data directory is excluded from deployment; update this file on the production server separately.");
196 return $base;
197}
198function assetVersion(): string {
199 static $v;
200 if ($v !== null) return $v;
201 $file=dirname(__DIR__).'/asset-version.txt';
202 if (is_readable($file)) {
203 $hash=trim((string)file_get_contents($file));
204 if ($hash!=='' && preg_match('/^[0-9a-f]{7,64}$/i',$hash)) return $v=$hash;
205 }
206 $env=getenv('CI_COMMIT_SHA')?:getenv('SYNHEX_ASSET_VERSION')?:'';
207 if (is_string($env) && preg_match('/^[0-9a-f]{7,64}$/i',trim($env))) return $v=trim($env);
208 $git=dirname(__DIR__,2).'/.git';
209 if (is_dir($git)) {
210 $out=@shell_exec('git -C '.escapeshellarg(dirname($git)).' rev-parse HEAD 2>/dev/null');
211 if (is_string($out) && preg_match('/^[0-9a-f]{7,64}$/i',trim($out))) return $v=trim($out);
212 }
213 $js=dirname(__DIR__).'/assets/app.js';
214 return $v=is_file($js)?(string)filemtime($js):'0';
215}
216function assetUrl(string $path): string {
217 $path=ltrim($path,'/');
218 $v=rawurlencode(assetVersion());
219 return str_contains($path,'?')?$path.'&v='.$v:$path.'?v='.$v;
220}
221function authRequest(string $path,?array $form=null,?string $token=null): array {
222 $ch=curl_init('https://auth.timfalken.com'.$path);
223 $headers=['Accept: application/json','User-Agent: Synhex/1.0'];
224 if ($token) $headers[]='Authorization: Bearer '.$token;
225 curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>$headers]);
226 if ($form!==null) curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($form)]);
227 $body=curl_exec($ch); $status=curl_getinfo($ch,CURLINFO_RESPONSE_CODE);
228 $data=is_string($body)?json_decode($body,true):null;
229 if ($status!==200 || !is_array($data)) throw new RuntimeException('Authentication service unavailable or session expired. Please sign in again.');
230 return $data;
231}
232function loginUser(string $id,string $name): void {
233 query('INSERT INTO users VALUES(?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name',[$id,$name]);
234 $avatars=avatarCatalog();
235 query('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)',[$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
236 session_regenerate_id(true); $_SESSION['user']=$id; $_SESSION['csrf']=bin2hex(random_bytes(24));
237}
238// Generate the editable configuration on the first page request, including localhost.
239config();
240session_name('synhex_session');
241ini_set('session.use_strict_mode','1');
242$sessionLifetime=86400;
243$sessionPath=rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/';
244$sessionSecure=!localDev();
245session_set_cookie_params(['lifetime'=>$sessionLifetime,'path'=>$sessionPath,'secure'=>$sessionSecure,'httponly'=>true,'samesite'=>'Lax']);
246session_set_save_handler(new DatabaseSessions(),true);
247session_start();
248// Refresh browser cookie expiry on each request so activity slides the 24h lifetime.
249if (session_status()===PHP_SESSION_ACTIVE && session_id()!=='') {
250 setcookie(session_name(),session_id(),[
251 'expires'=>time()+$sessionLifetime,
252 'path'=>$sessionPath,
253 'secure'=>$sessionSecure,
254 'httponly'=>true,
255 'samesite'=>'Lax',
256 ]);
257}
258if (localDev() && !in_array($_SESSION['user']??'', ['local:test_user_1','local:test_user_2'],true)) {
259 unset($_SESSION['token'],$_SESSION['expires'],$_SESSION['validated']);
260 loginUser('local:test_user_1','test_user_1');
261}
262function user(): string {
263 if (!isset($_SESSION['user'])) fail('Please sign in.',401);
264 if (!localDev() && (($_SESSION['expires']??0)<time())) {unset($_SESSION['user']);fail('Your session expired. Please sign in again.',401);}
265 return $_SESSION['user'];
266}
267function fail(string $message,int $status=400): never {http_response_code($status);header('Content-Type: application/json');echo json_encode(['error'=>$message]);exit;}
268function jsonOut(mixed $data): never {header('Content-Type: application/json');echo json_encode($data,JSON_THROW_ON_ERROR);exit;}
269function pair(string $a,string $b): array { $p=[$a,$b];sort($p,SORT_STRING);return $p; }
270function rivalry(string $u,string $other): array {
271 $r=query('SELECT COUNT(*) AS total,COALESCE(SUM(winner=?),0) AS wins,COALESCE(SUM(winner IS NULL),0) AS ties FROM results WHERE (a=? AND b=?) OR (a=? AND b=?)',[$u,$u,$other,$other,$u])->fetch();
272 return ['wins'=>(int)$r['wins'],'losses'=>(int)$r['total']-(int)$r['wins']-(int)$r['ties'],'ties'=>(int)$r['ties']];
273}
274function befriend(string $a,string $b): void {
275 $p=pair($a,$b);
276 query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
277 query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
278}
279function saveReplay(int $result,string $white,array $s,string $skinWhite='White',string $skinBlack='Black'): void {
280 $payload=json_encode(['version'=>1,'state'=>$s],JSON_THROW_ON_ERROR);
281 $q=db()->prepare('INSERT INTO replays(result_id,white,moves,piece_skin_white,piece_skin_black) VALUES(?,?,?,?,?)');
282 $q->bindValue(1,$result);$q->bindValue(2,$white);$q->bindValue(3,$payload,PDO::PARAM_LOB);$q->bindValue(4,$skinWhite);$q->bindValue(5,$skinBlack);$q->execute();
283 query("UPDATE results SET state='{}' WHERE id=?",[$result]);
284}
285function replayLink(int $id): string {
286 query('INSERT OR IGNORE INTO replay_links(result_id,token) VALUES(?,?)',[$id,bin2hex(random_bytes(24))]);
287 return query('SELECT token FROM replay_links WHERE result_id=?',[$id])->fetchColumn();
288}
289function replayPlayers(array $r): array {
290 $black=$r['white']===$r['a']?$r['b']:$r['a'];
291 return ['whiteName'=>profile($r['white'])['name'],'blackName'=>profile($black)['name']];
292}
293function replayPositions(string $packed): array {
294 $data=json_decode($packed,true);
295 if (!is_array($data) || (int)($data['version']??0)!==1 || !isset($data['state'])) return [];
296 return SynhexMatch::replayFrames($data['state']);
297}
298function finishGame(array $g,?string $winner,string $reason,array $s): void {
299 $final=$s;$final['history']=[];
300 $finished=query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=? AND status='active' AND version=?",[$winner,$reason,json_encode($final),$g['id'],$g['version']]);
301 if ($finished->rowCount()!==1) throw new DomainException('The game has changed. Please try again.');
302 query('INSERT INTO results(game_id,a,b,winner,reason,state,ended) VALUES(?,?,?,?,?,?,?)',[$g['id'],$g['a'],$g['b'],$winner,$reason,json_encode($s),time()]);
303 $result=(int)db()->lastInsertId();
304 $skins=gamePieceSkins($g);saveReplay($result,$g['white'],$s,$skins['white'],$skins['black']);
305 $a=(int)profile($g['a'])['rating'];$b=(int)profile($g['b'])['rating'];
306 $score=$winner===null?0.5:($winner===$g['a']?1:0);
307 $delta=(int)round(32*($score-1/(1+10**(($b-$a)/400))));
308 query('INSERT INTO rating_changes VALUES(?,?,?,?)',[$result,$a,$b,$delta]);
309 foreach ([[$g['a'],$a+$delta],[$g['b'],$b-$delta]] as [$id,$rating]) {
310 query('INSERT INTO ratings(user_id,rating,played) VALUES(?,?,1) ON CONFLICT(user_id) DO UPDATE SET rating=excluded.rating,played=ratings.played+1',[$id,$rating]);
311 }
312}
313// Called inside BEGIN IMMEDIATE: selecting pairs and consuming entries is atomic.
314function matchPlayers(bool $force=false): void {
315 $now=time();
316 if (!$force && (int)query('SELECT checked FROM matchmaking_clock WHERE id=1')->fetchColumn()>$now-60) return;
317 query('UPDATE matchmaking_clock SET checked=? WHERE id=1',[$now]);
318 $pool=query('SELECT m.*,COALESCE(r.rating,1200) AS rating FROM matchmaking m LEFT JOIN ratings r ON r.user_id=m.user_id WHERE m.joined>? ORDER BY m.joined,m.user_id',[$now-86400])->fetchAll();
319 $used=[];
320 foreach ($pool as $a) {
321 if (isset($used[$a['user_id']])) continue;
322 $best=null;$distance=PHP_INT_MAX;
323 foreach ($pool as $b) {
324 if ($a['user_id']===$b['user_id'] || isset($used[$b['user_id']])) continue;
325 $gap=abs($a['rating']-$b['rating']);
326 $limit=min(500,100+50*intdiv(max(0,$now-$a['joined']),60),100+50*intdiv(max(0,$now-$b['joined']),60));
327 if ($gap<=$limit && $gap<$distance) {$best=$b;$distance=$gap;}
328 }
329 if ($best===null) continue;
330 startGame($a['user_id'],$best['user_id']);
331 query('DELETE FROM matchmaking WHERE user_id IN (?,?)',[$a['user_id'],$best['user_id']]);
332 $used[$a['user_id']]=$used[$best['user_id']]=true;
333 }
334}
335function startGame(string $a,string $b): int {
336 $white=random_int(0,1)?$a:$b;
337 query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,$white,json_encode(SynhexMatch::initial()),time()]);
338 $id=(int)db()->lastInsertId();
339 assignGamePieceSkins($id,$white,$white===$a?$b:$a);
340 pushGame($id);
341 return $id;
342}
343function gameView(array $g,string $u): array {
344 $other=$g['a']===$u?$g['b']:$g['a'];$side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a';
345 $opponent=profile($other);
346 $s=$g['state']?json_decode($g['state'],true):null;
347 $color=$g['white']===$u?'w':'b';
348 $skins=gamePieceSkins($g);
349 $displayColor=$color==='w'?$skins['white']:$skins['black'];
350 $opponentDisplayColor=$color==='w'?$skins['black']:$skins['white'];
351 $cfg=$s?gameConfig():[];
352 $view=$s?SynhexMatch::clientView($s,$color,$cfg):null;
353 if ($view && in_array($g['status'],['ended','stopped'],true)) {
354 $view['units']=array_map(static fn($u)=>$u+['hologram'=>false,'known'=>true],$s['units']??[]);
355 $view['phase']='ended';
356 $view['timeline']=$s['timeline']??($s['history'][count($s['history']??[])-1]??null);
357 }
358 $yourTurn=$g['status']==='active' && $s && SynhexMatch::isYourTurn($s,$color);
359 $bar=$s?SynhexMatch::unitBar($s):['w'=>0,'b'=>0];
360 return ['id'=>(int)$g['id'],'turnOrder'=>(int)$g['turn_order'],'replayId'=>$g['status']==='ended'?(int)query('SELECT MAX(result_id) FROM replays JOIN results ON results.id=replays.result_id WHERE game_id=?',[$g['id']])->fetchColumn():null,'opponentId'=>$other,'rivalry'=>rivalry($u,$other),'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'],'opponentRating'=>(int)$opponent['rating'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color,'displayColor'=>$displayColor,'opponentDisplayColor'=>$opponentDisplayColor,'pieceSkinWhite'=>$skins['white'],'pieceSkinBlack'=>$skins['black'],
361 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
362 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
363 'state'=>$view,'yourTurn'=>$yourTurn,'legal'=>[],
364 'check'=>false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
365 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null,
366 'claimable'=>false,'strength'=>$bar,'version'=>(int)$g['version']];
367}