BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / bootstrap.php

bootstrap.php

bootstrap.php 15.3 KiB Download Raw
1<?php
2declare(strict_types=1);
3require_once __DIR__.'/Chess.php';
4require_once __DIR__.'/MoveFeedback.php';
5ini_set('display_errors','0');
6ini_set('log_errors','1');
7ini_set('error_log',dirname(__DIR__).'/data/php-errors.log');
8header('X-Content-Type-Options: nosniff');
9header('Referrer-Policy: same-origin');
10header("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'");
11header('Cache-Control: no-store');
12
13function db(): PDO {
14 static $db;
15 if ($db) return $db;
16 $db=new PDO('sqlite:'.dirname(__DIR__).'/data/microchess.sqlite',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
17 $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
18 $db->exec('CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL);
19 CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL);
20 CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL);
21 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));
22 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));
23 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);
24 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);
25 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);
26 CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);');
27 $columns=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1);
28 if (!in_array('activity_at',$columns,true)) {
29 $db->exec('BEGIN IMMEDIATE');
30 try {
31 if (!in_array('activity_at',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) {
32 $db->exec('ALTER TABLE games ADD COLUMN activity_at INTEGER');
33 $db->exec("UPDATE games SET activity_at=CAST(strftime('%s','now') AS INTEGER) WHERE activity_at IS NULL");
34 }
35 $db->exec('COMMIT');
36 } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; }
37 }
38 // Replace legacy triggers once, including databases already migrated on newer SQLite.
39 $legacy=$db->query("SELECT sql FROM sqlite_master WHERE type='trigger' AND name IN ('games_activity_insert','games_activity_update')")->fetchAll(PDO::FETCH_COLUMN);
40 if (array_filter($legacy,static fn(string $sql): bool => stripos($sql,'unixepoch(')!==false)) {
41 $db->exec('BEGIN IMMEDIATE');
42 try {
43 $db->exec('DROP TRIGGER IF EXISTS games_activity_insert; DROP TRIGGER IF EXISTS games_activity_update;');
44 activityTriggers($db);
45 $db->exec('COMMIT');
46 } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; }
47 } else {
48 activityTriggers($db);
49 }
50 // Assign existing accounts once as well as newly created accounts.
51 foreach ($db->query('SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM user_avatars)')->fetchAll(PDO::FETCH_COLUMN) as $id) {
52 $avatars=avatarCatalog();
53 $q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)');
54 $q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
55 }
56 $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);
57 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);
58 CREATE TABLE IF NOT EXISTS matchmaking (user_id TEXT PRIMARY KEY REFERENCES users(id), joined INTEGER NOT NULL);
59 CREATE TABLE IF NOT EXISTS matchmaking_clock (id INTEGER PRIMARY KEY CHECK(id=1), checked INTEGER NOT NULL);
60 INSERT OR IGNORE INTO matchmaking_clock VALUES(1,0);');
61 return $db;
62}
63function activityTriggers(PDO $db): void {
64 $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;
65 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;");
66}
67function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; }
68function profile(string $id): array {
69 return query('SELECT u.*,a.avatar,COALESCE(r.rating,1200) AS rating,COALESCE(r.played,0) AS ratedGames FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id LEFT JOIN ratings r ON r.user_id=u.id WHERE u.id=?',[$id])->fetch();
70}
71function avatarCatalog(): array {
72 static $avatars;
73 return $avatars ??= json_decode(file_get_contents(dirname(__DIR__).'/assets/avatars/catalog.json'),true,512,JSON_THROW_ON_ERROR);
74}
75final class DatabaseSessions implements SessionHandlerInterface {
76 public function open(string $path,string $name): bool {return true;}
77 public function close(): bool {return true;}
78 public function read(string $id): string|false {return query('SELECT payload FROM sessions WHERE id=? AND expires>?',[$id,time()])->fetchColumn()?:'';}
79 public function write(string $id,string $data): bool {query('INSERT OR REPLACE INTO sessions VALUES(?,?,?)',[$id,$data,time()+3600]);return true;}
80 public function destroy(string $id): bool {query('DELETE FROM sessions WHERE id=?',[$id]);return true;}
81 public function gc(int $max_lifetime): int|false {return query('DELETE FROM sessions WHERE expires<?',[time()])->rowCount();}
82}
83function localDev(): bool {
84 $host=parse_url('http://'.($_SERVER['HTTP_HOST']??''),PHP_URL_HOST);
85 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);
86}
87function config(): array {
88 static $c;
89 if ($c !== null) return $c;
90 $path=dirname(__DIR__).'/data/config.php';
91 $lock=fopen(dirname(__DIR__).'/data/config.lock','c');
92 if ($lock===false) throw new RuntimeException('The data directory must be writable to initialize configuration.');
93 try {
94 if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock configuration.');
95 if (!file_exists($path)) {
96 $template="<?php\n// Fill in these values on this server. Empty fields use environment variables.\nreturn [\n 'base_url' => '',\n 'client_id' => '',\n 'client_secret' => '',\n];\n";
97 if (file_put_contents($path,$template)!==strlen($template)) throw new RuntimeException('Unable to create data/config.php.');
98 }
99 $values=require $path;
100 if (!is_array($values)) throw new RuntimeException('data/config.php must return an array.');
101 } finally {
102 flock($lock,LOCK_UN);
103 fclose($lock);
104 }
105 foreach (['base_url'=>'MICROCHESS_BASE_URL','client_id'=>'MICROCHESS_CLIENT_ID','client_secret'=>'MICROCHESS_CLIENT_SECRET'] as $key=>$env) {
106 if (($values[$key]??'')==='') $values[$key]=getenv($env)?:'';
107 }
108 return $c=$values;
109}
110function baseUrl(): string {
111 if (localDev()) return 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/');
112 $base=rtrim(config()['base_url'],'/');
113 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 MICROCHESS_BASE_URL. The data directory is excluded from deployment; update this file on the production server separately.");
114 return $base;
115}
116function authRequest(string $path,?array $form=null,?string $token=null): array {
117 $ch=curl_init('https://auth.timfalken.com'.$path);
118 $headers=['Accept: application/json','User-Agent: Microchess/1.0'];
119 if ($token) $headers[]='Authorization: Bearer '.$token;
120 curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>$headers]);
121 if ($form!==null) curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($form)]);
122 $body=curl_exec($ch); $status=curl_getinfo($ch,CURLINFO_RESPONSE_CODE);
123 $data=is_string($body)?json_decode($body,true):null;
124 if ($status!==200 || !is_array($data)) throw new RuntimeException('Authentication service unavailable or session expired. Please sign in again.');
125 return $data;
126}
127function loginUser(string $id,string $name): void {
128 query('INSERT INTO users VALUES(?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name',[$id,$name]);
129 $avatars=avatarCatalog();
130 query('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)',[$id,$avatars[random_int(0,count($avatars)-1)]['id']]);
131 session_regenerate_id(true); $_SESSION['user']=$id; $_SESSION['csrf']=bin2hex(random_bytes(24));
132}
133// Generate the editable configuration on the first page request, including localhost.
134config();
135session_name('microchess_session');
136ini_set('session.use_strict_mode','1');
137session_set_cookie_params(['lifetime'=>0,'path'=>rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/', 'secure'=>!localDev(),'httponly'=>true,'samesite'=>'Lax']);
138session_set_save_handler(new DatabaseSessions(),true);
139session_start();
140if (localDev() && !in_array($_SESSION['user']??'', ['local:test_user_1','local:test_user_2'],true)) {
141 unset($_SESSION['token'],$_SESSION['expires'],$_SESSION['validated']);
142 loginUser('local:test_user_1','test_user_1');
143}
144function user(): string {
145 if (!isset($_SESSION['user'])) fail('Please sign in.',401);
146 if (!localDev() && (($_SESSION['expires']??0)<time())) {unset($_SESSION['user']);fail('Your session expired. Please sign in again.',401);}
147 return $_SESSION['user'];
148}
149function fail(string $message,int $status=400): never {http_response_code($status);header('Content-Type: application/json');echo json_encode(['error'=>$message]);exit;}
150function jsonOut(mixed $data): never {header('Content-Type: application/json');echo json_encode($data,JSON_THROW_ON_ERROR);exit;}
151function pair(string $a,string $b): array { $p=[$a,$b];sort($p,SORT_STRING);return $p; }
152function rivalry(string $u,string $other): array {
153 $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();
154 return ['wins'=>(int)$r['wins'],'losses'=>(int)$r['total']-(int)$r['wins']-(int)$r['ties'],'ties'=>(int)$r['ties']];
155}
156function befriend(string $a,string $b): void {
157 $p=pair($a,$b);
158 query('INSERT OR IGNORE INTO friends VALUES(?,?)',$p);
159 query('DELETE FROM friend_requests WHERE a=? AND b=?',$p);
160}
161function finishGame(array $g,?string $winner,string $reason,array $s): void {
162 $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($s),$g['id'],$g['version']]);
163 if ($finished->rowCount()!==1) throw new DomainException('The game has changed. Please try again.');
164 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()]);
165 $result=(int)db()->lastInsertId();
166 $a=(int)profile($g['a'])['rating'];$b=(int)profile($g['b'])['rating'];
167 $score=$winner===null?0.5:($winner===$g['a']?1:0);
168 $delta=(int)round(32*($score-1/(1+10**(($b-$a)/400))));
169 query('INSERT INTO rating_changes VALUES(?,?,?,?)',[$result,$a,$b,$delta]);
170 foreach ([[$g['a'],$a+$delta],[$g['b'],$b-$delta]] as [$id,$rating]) {
171 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]);
172 }
173}
174// Called inside BEGIN IMMEDIATE: selecting pairs and consuming entries is atomic.
175function matchPlayers(bool $force=false): void {
176 $now=time();
177 if (!$force && (int)query('SELECT checked FROM matchmaking_clock WHERE id=1')->fetchColumn()>$now-60) return;
178 query('UPDATE matchmaking_clock SET checked=? WHERE id=1',[$now]);
179 $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();
180 $used=[];
181 foreach ($pool as $a) {
182 if (isset($used[$a['user_id']])) continue;
183 $best=null;$distance=PHP_INT_MAX;
184 foreach ($pool as $b) {
185 if ($a['user_id']===$b['user_id'] || isset($used[$b['user_id']])) continue;
186 $gap=abs($a['rating']-$b['rating']);
187 $limit=min(500,100+50*intdiv(max(0,$now-$a['joined']),60),100+50*intdiv(max(0,$now-$b['joined']),60));
188 if ($gap<=$limit && $gap<$distance) {$best=$b;$distance=$gap;}
189 }
190 if ($best===null) continue;
191 startGame($a['user_id'],$best['user_id']);
192 query('DELETE FROM matchmaking WHERE user_id IN (?,?)',[$a['user_id'],$best['user_id']]);
193 $used[$a['user_id']]=$used[$best['user_id']]=true;
194 }
195}
196function startGame(string $a,string $b): int {
197 query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,random_int(0,1)?$a:$b,json_encode(Chess::initial()),time()]);
198 return (int)db()->lastInsertId();
199}
200function gameView(array $g,string $u): array {
201 $other=$g['a']===$u?$g['b']:$g['a'];$side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a';
202 $opponent=profile($other);
203 $s=$g['state']?json_decode($g['state'],true):null;
204 $color=$g['white']===$u?'w':'b';
205 return ['id'=>(int)$g['id'],'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,
206 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)),
207 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'),
208 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[],
209 'check'=>$s?Chess::check($s):false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'],
210 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null,
211 'claimable'=>$s?Chess::claimable($s):false,'version'=>(int)$g['version']];
212}