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