PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]); $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;'); $db->exec('CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL); CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL); 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(aquery('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1); if (!in_array('activity_at',$columns,true)) { $db->exec('BEGIN IMMEDIATE'); try { if (!in_array('activity_at',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) { $db->exec('ALTER TABLE games ADD COLUMN activity_at INTEGER'); $db->exec("UPDATE games SET activity_at=CAST(strftime('%s','now') AS INTEGER) WHERE activity_at IS NULL"); } $db->exec('COMMIT'); } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; } } // Replace legacy triggers once, including databases already migrated on newer SQLite. $legacy=$db->query("SELECT sql FROM sqlite_master WHERE type='trigger' AND name IN ('games_activity_insert','games_activity_update')")->fetchAll(PDO::FETCH_COLUMN); if (array_filter($legacy,static fn(string $sql): bool => stripos($sql,'unixepoch(')!==false)) { $db->exec('BEGIN IMMEDIATE'); try { $db->exec('DROP TRIGGER IF EXISTS games_activity_insert; DROP TRIGGER IF EXISTS games_activity_update;'); activityTriggers($db); $db->exec('COMMIT'); } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; } } else { activityTriggers($db); } // Assign existing accounts once as well as newly created accounts. foreach ($db->query('SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM user_avatars)')->fetchAll(PDO::FETCH_COLUMN) as $id) { $avatars=avatarCatalog(); $q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)'); $q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]); } return $db; } function activityTriggers(PDO $db): void { $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; 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;"); } function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; } function profile(string $id): array { return query('SELECT u.*,a.avatar FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id WHERE u.id=?',[$id])->fetch(); } function avatarCatalog(): array { static $avatars; return $avatars ??= json_decode(file_get_contents(dirname(__DIR__).'/assets/avatars/catalog.json'),true,512,JSON_THROW_ON_ERROR); } final class DatabaseSessions implements SessionHandlerInterface { public function open(string $path,string $name): bool {return true;} public function close(): bool {return true;} public function read(string $id): string|false {return query('SELECT payload FROM sessions WHERE id=? AND expires>?',[$id,time()])->fetchColumn()?:'';} public function write(string $id,string $data): bool {query('INSERT OR REPLACE INTO sessions VALUES(?,?,?)',[$id,$data,time()+3600]);return true;} public function destroy(string $id): bool {query('DELETE FROM sessions WHERE id=?',[$id]);return true;} public function gc(int $max_lifetime): int|false {return query('DELETE FROM sessions WHERE expiresrowCount();} } function localDev(): bool { $host=parse_url('http://'.($_SERVER['HTTP_HOST']??''),PHP_URL_HOST); 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); } function config(): array { static $c; if ($c !== null) return $c; $path=dirname(__DIR__).'/data/config.php'; $lock=fopen(dirname(__DIR__).'/data/config.lock','c'); if ($lock===false) throw new RuntimeException('The data directory must be writable to initialize configuration.'); try { if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock configuration.'); if (!file_exists($path)) { $template=" '',\n 'client_id' => '',\n 'client_secret' => '',\n];\n"; if (file_put_contents($path,$template)!==strlen($template)) throw new RuntimeException('Unable to create data/config.php.'); } $values=require $path; if (!is_array($values)) throw new RuntimeException('data/config.php must return an array.'); } finally { flock($lock,LOCK_UN); fclose($lock); } foreach (['base_url'=>'MICROCHESS_BASE_URL','client_id'=>'MICROCHESS_CLIENT_ID','client_secret'=>'MICROCHESS_CLIENT_SECRET'] as $key=>$env) { if (($values[$key]??'')==='') $values[$key]=getenv($env)?:''; } return $c=$values; } function baseUrl(): string { if (localDev()) return 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/'); $base=rtrim(config()['base_url'],'/'); 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."); return $base; } function authRequest(string $path,?array $form=null,?string $token=null): array { $ch=curl_init('https://auth.timfalken.com'.$path); $headers=['Accept: application/json','User-Agent: Microchess/1.0']; if ($token) $headers[]='Authorization: Bearer '.$token; curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>$headers]); if ($form!==null) curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($form)]); $body=curl_exec($ch); $status=curl_getinfo($ch,CURLINFO_RESPONSE_CODE); $data=is_string($body)?json_decode($body,true):null; if ($status!==200 || !is_array($data)) throw new RuntimeException('Authentication service unavailable or session expired. Please sign in again.'); return $data; } function loginUser(string $id,string $name): void { query('INSERT INTO users VALUES(?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name',[$id,$name]); $avatars=avatarCatalog(); query('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)',[$id,$avatars[random_int(0,count($avatars)-1)]['id']]); session_regenerate_id(true); $_SESSION['user']=$id; $_SESSION['csrf']=bin2hex(random_bytes(24)); } // Generate the editable configuration on the first page request, including localhost. config(); session_name('microchess_session'); ini_set('session.use_strict_mode','1'); session_set_cookie_params(['lifetime'=>0,'path'=>rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/', 'secure'=>!localDev(),'httponly'=>true,'samesite'=>'Lax']); session_set_save_handler(new DatabaseSessions(),true); session_start(); if (localDev() && !in_array($_SESSION['user']??'', ['local:test_user_1','local:test_user_2'],true)) { unset($_SESSION['token'],$_SESSION['expires'],$_SESSION['validated']); loginUser('local:test_user_1','test_user_1'); } function user(): string { if (!isset($_SESSION['user'])) fail('Please sign in.',401); if (!localDev() && (($_SESSION['expires']??0)$message]);exit;} function jsonOut(mixed $data): never {header('Content-Type: application/json');echo json_encode($data,JSON_THROW_ON_ERROR);exit;} function pair(string $a,string $b): array { $p=[$a,$b];sort($p,SORT_STRING);return $p; } function finishGame(array $g,?string $winner,string $reason,array $s): void { query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=?",[$winner,$reason,json_encode($s),$g['id']]); 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()]); } function startGame(string $a,string $b): int { 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()]); return (int)db()->lastInsertId(); } function gameView(array $g,string $u): array { $other=$g['a']===$u?$g['b']:$g['a'];$side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a'; $opponent=profile($other); $s=$g['state']?json_decode($g['state'],true):null; $color=$g['white']===$u?'w':'b'; return ['id'=>(int)$g['id'],'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color, 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)), 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'), 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[], 'check'=>$s?Chess::check($s):false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'], 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null, 'claimable'=>$s?Chess::claimable($s):false,'version'=>(int)$g['version']]; }