server.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. <?php
  2. /**
  3. * Statum frontend demo backend.
  4. *
  5. * Run from this directory with PHP's built-in server:
  6. *
  7. * php -S localhost:8000 server.php
  8. *
  9. * Then open http://localhost:8000/ in your browser.
  10. *
  11. * This is a DEMO only: there is no real signing or encryption. Snapshots are
  12. * wrapped in trivial frames, and per-item action context is carried in the
  13. * action's `private` blob as plain base64. State lives in the PHP session so
  14. * that actions are stateful across requests.
  15. */
  16. session_start();
  17. // Static product catalog used by the demo.
  18. $CATALOG = [
  19. ['id' => 1, 'name' => 'Widget', 'price' => 9.99, 'featured' => true, 'inStock' => true],
  20. ['id' => 2, 'name' => 'Gadget', 'price' => 19.99, 'featured' => false, 'inStock' => true],
  21. ['id' => 3, 'name' => 'Sprocket', 'price' => 4.50, 'featured' => false, 'inStock' => false],
  22. ['id' => 4, 'name' => 'Gizmo', 'price' => 29.99, 'featured' => true, 'inStock' => true],
  23. ];
  24. $TYPES = ['counter', 'products', 'cart', 'user', 'notice'];
  25. // ---------------------------------------------------------------------------
  26. // Helpers
  27. // ---------------------------------------------------------------------------
  28. /** Send a JSON array of Statum directives and stop. */
  29. function statum_respond(array $directives): void
  30. {
  31. header('Content-Type: application/vnd.statum+json');
  32. header('Cache-Control: no-store');
  33. echo json_encode($directives, JSON_PRETTY_PRINT);
  34. exit;
  35. }
  36. /** Wrap a snapshot in a trivial (unsigned) frame. */
  37. function frame(array $snapshot): array
  38. {
  39. return ['content' => json_encode($snapshot), 'signer' => 'demo', 'signature' => ''];
  40. }
  41. /** Stable per-type slot key, kept in the session. */
  42. function key_for(string $type): string
  43. {
  44. if (!isset($_SESSION['keys'][$type])) {
  45. $_SESSION['keys'][$type] = 'k_' . $type;
  46. }
  47. return $_SESSION['keys'][$type];
  48. }
  49. /**
  50. * Build a snapshot for a type. `always` makes transmit_after == as_at so the
  51. * client sends the base64 frame on every request (demonstrating that path).
  52. */
  53. function make_snapshot(string $type, string $scope, array $public, array $opts = []): array
  54. {
  55. $now = gmdate('Y-m-d\TH:i:s\Z');
  56. return [
  57. 'as_at' => $now,
  58. 'slot' => ['key' => key_for($type), 'scope' => $scope, 'type' => $type],
  59. 'transmit_after' => !empty($opts['always']) ? $now : gmdate('Y-m-d\TH:i:s\Z', time() + 60),
  60. 'invalid_after' => gmdate('Y-m-d\TH:i:s\Z', time() + 600),
  61. 'private' => $opts['private'] ?? '',
  62. 'public' => $public,
  63. ];
  64. }
  65. function set_dir(array $snapshot): array
  66. {
  67. return ['type' => 'set', 'snapshot_frame' => frame($snapshot)];
  68. }
  69. function clear_dir(string $key): array
  70. {
  71. return ['type' => 'clear', 'key' => $key];
  72. }
  73. function product_by_id($id): ?array
  74. {
  75. global $CATALOG;
  76. foreach ($CATALOG as $p) {
  77. if ((string)$p['id'] === (string)$id) return $p;
  78. }
  79. return null;
  80. }
  81. // ---------------------------------------------------------------------------
  82. // Public-data builders
  83. // ---------------------------------------------------------------------------
  84. function build_counter(): array
  85. {
  86. $v = $_SESSION['counter'] ?? 0;
  87. return [
  88. 'value' => $v,
  89. 'high' => $v > 5,
  90. 'increment' => ['uri' => '/api/counter/inc', 'method' => 'POST'],
  91. 'decrement' => ['uri' => '/api/counter/dec', 'method' => 'POST'],
  92. 'reset' => ['uri' => '/api/counter/reset', 'method' => 'POST'],
  93. 'add' => ['uri' => '/api/counter/add', 'method' => 'POST'],
  94. ];
  95. }
  96. function build_products(): array
  97. {
  98. global $CATALOG;
  99. $items = [];
  100. foreach ($CATALOG as $p) {
  101. $pid = (string)$p['id'];
  102. $items[] = [
  103. 'id' => $pid,
  104. 'name' => $p['name'],
  105. 'price' => $p['price'],
  106. 'featured' => $p['featured'],
  107. 'inStock' => $p['inStock'],
  108. // Per-item context rides in `private`; the client echoes it back
  109. // via the X-Statum-Private header (no stm-data expression needed).
  110. 'addToCartAction' => [
  111. 'uri' => '/api/cart/add',
  112. 'method' => 'POST',
  113. 'private' => base64_encode('id=' . $pid),
  114. ],
  115. ];
  116. }
  117. return ['items' => $items];
  118. }
  119. function build_cart(): array
  120. {
  121. $cart = $_SESSION['cart'] ?? [];
  122. $count = 0;
  123. $total = 0.0;
  124. $lines = [];
  125. foreach ($cart as $id => $qty) {
  126. $p = product_by_id($id);
  127. if (!$p) continue;
  128. $count += $qty;
  129. $total += $p['price'] * $qty;
  130. $lines[] = ['id' => (string)$id, 'name' => $p['name'], 'qty' => $qty, 'price' => $p['price']];
  131. }
  132. return [
  133. 'count' => $count,
  134. 'total' => round($total, 2),
  135. 'empty' => $count === 0,
  136. 'items' => $lines,
  137. 'checkoutAction' => ['uri' => '/api/cart/checkout', 'method' => 'POST'],
  138. 'clearAction' => ['uri' => '/api/cart/clear', 'method' => 'POST'],
  139. ];
  140. }
  141. function build_user(): array
  142. {
  143. $role = $_SESSION['role'] ?? 'guest';
  144. $names = ['guest' => 'Guest', 'member' => 'Member Mike', 'admin' => 'Admin Alice'];
  145. return [
  146. 'role' => $role,
  147. 'name' => $names[$role] ?? 'Guest',
  148. 'toggleAction' => ['uri' => '/api/user/toggle', 'method' => 'POST'],
  149. 'resetAllAction' => ['uri' => '/api/reset-all', 'method' => 'POST'],
  150. ];
  151. }
  152. function build_notice(): array
  153. {
  154. return [
  155. 'html' => $_SESSION['notice'] ?? '<em>No notice set.</em>',
  156. 'setAction' => ['uri' => '/api/notice/set', 'method' => 'POST'],
  157. 'failAction' => ['uri' => '/api/notice/fail', 'method' => 'POST'],
  158. ];
  159. }
  160. /** Build the snapshot for a type with its demo scope/options. */
  161. function snap(string $type): ?array
  162. {
  163. switch ($type) {
  164. case 'counter': return make_snapshot('counter', 'session', build_counter());
  165. case 'products': return make_snapshot('products', 'session', build_products());
  166. case 'cart': return make_snapshot('cart', 'session', build_cart(), ['always' => true]);
  167. case 'user': return make_snapshot('user', 'session', build_user());
  168. case 'notice': return make_snapshot('notice', 'flow', build_notice());
  169. }
  170. return null;
  171. }
  172. function all_directives(): array
  173. {
  174. global $TYPES;
  175. $dirs = [];
  176. foreach ($TYPES as $t) {
  177. $s = snap($t);
  178. if ($s) $dirs[] = set_dir($s);
  179. }
  180. return $dirs;
  181. }
  182. // ---------------------------------------------------------------------------
  183. // Router
  184. // ---------------------------------------------------------------------------
  185. $method = $_SERVER['REQUEST_METHOD'];
  186. $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  187. // Static assets.
  188. if ($path === '/statum.js') {
  189. header('Content-Type: application/javascript');
  190. readfile(__DIR__ . '/../js/statum.js');
  191. exit;
  192. }
  193. // The page itself.
  194. if ($path === '/' || $path === '/index.html') {
  195. header('Content-Type: text/html; charset=utf-8');
  196. readfile(__DIR__ . '/index.html');
  197. exit;
  198. }
  199. // Landing page after a (post) checkout navigation.
  200. if ($path === '/api/checkout-done') {
  201. header('Content-Type: text/html; charset=utf-8');
  202. $order = htmlspecialchars($_GET['order'] ?? 'UNKNOWN');
  203. echo "<!doctype html><meta charset=utf-8><title>Checkout</title>" .
  204. "<body style='font-family:sans-serif;padding:2rem'>" .
  205. "<h1>Order $order placed</h1><p>This page was reached via a statum <code>post</code> directive.</p>" .
  206. "<p><a href='/'>Back to the demo</a></p>";
  207. exit;
  208. }
  209. // --- Statum endpoints -------------------------------------------------------
  210. if ($path === '/_statum/entrypoint') {
  211. statum_respond(all_directives());
  212. }
  213. if ($path === '/_statum/slots') {
  214. // Pre-flight target: refresh each type whose frame the client sent back.
  215. $body = json_decode(file_get_contents('php://input'), true);
  216. $dirs = [];
  217. if (is_array($body)) {
  218. foreach ($body as $fr) {
  219. $snap = json_decode($fr['content'] ?? 'null', true);
  220. $type = $snap['slot']['type'] ?? null;
  221. if ($type) {
  222. $s = snap($type);
  223. if ($s) $dirs[] = set_dir($s);
  224. }
  225. }
  226. }
  227. statum_respond($dirs);
  228. }
  229. // --- Actions ----------------------------------------------------------------
  230. if ($path === '/api/counter/inc' && $method === 'POST') {
  231. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) + 1;
  232. statum_respond([set_dir(snap('counter'))]);
  233. }
  234. if ($path === '/api/counter/dec' && $method === 'POST') {
  235. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) - 1;
  236. statum_respond([set_dir(snap('counter'))]);
  237. }
  238. if ($path === '/api/counter/reset' && $method === 'POST') {
  239. $_SESSION['counter'] = 0;
  240. statum_respond([set_dir(snap('counter'))]);
  241. }
  242. if ($path === '/api/counter/add' && $method === 'POST') {
  243. $amount = intval($_POST['amount'] ?? 1);
  244. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) + $amount;
  245. statum_respond([set_dir(snap('counter'))]);
  246. }
  247. if ($path === '/api/cart/add' && $method === 'POST') {
  248. $priv = $_SERVER['HTTP_X_STATUM_PRIVATE'] ?? '';
  249. $raw = base64_decode($priv, true) ?: '';
  250. if (preg_match('/id=([0-9]+)/', $raw, $m)) {
  251. $id = $m[1];
  252. $_SESSION['cart'][$id] = ($_SESSION['cart'][$id] ?? 0) + 1;
  253. }
  254. statum_respond([set_dir(snap('cart'))]);
  255. }
  256. if ($path === '/api/cart/clear' && $method === 'POST') {
  257. $_SESSION['cart'] = [];
  258. statum_respond([set_dir(snap('cart'))]);
  259. }
  260. if ($path === '/api/cart/checkout' && $method === 'POST') {
  261. // A `post` directive performs a full-page navigating form POST last.
  262. statum_respond([['type' => 'post', 'uri' => '/api/checkout-done', 'data' => ['order' => 'ORD-' . strtoupper(bin2hex(random_bytes(3)))]]]);
  263. }
  264. if ($path === '/api/user/toggle' && $method === 'POST') {
  265. $order = ['guest', 'member', 'admin'];
  266. $cur = array_search($_SESSION['role'] ?? 'guest', $order);
  267. $_SESSION['role'] = $order[($cur + 1) % count($order)];
  268. statum_respond([set_dir(snap('user'))]);
  269. }
  270. if ($path === '/api/notice/set' && $method === 'POST') {
  271. $_SESSION['notice'] = '<div class="ok"><strong>Notice:</strong> updated at ' . date('H:i:s') . '</div>';
  272. statum_respond([set_dir(snap('notice'))]);
  273. }
  274. if ($path === '/api/notice/fail' && $method === 'POST') {
  275. statum_respond([['type' => 'error', 'message' => 'Intentional failure.', 'code' => 'DEMO_FAIL', 'data' => ['at' => date('c')]]]);
  276. }
  277. if ($path === '/api/reset-all' && $method === 'POST') {
  278. $dirs = [];
  279. foreach ($TYPES as $t) {
  280. if (isset($_SESSION['keys'][$t])) $dirs[] = clear_dir($_SESSION['keys'][$t]);
  281. }
  282. session_unset();
  283. $dirs[] = ['type' => 'navigate', 'uri' => '/'];
  284. statum_respond($dirs);
  285. }
  286. // Fallback 404.
  287. http_response_code(404);
  288. header('Content-Type: text/plain');
  289. echo "404 Not Found: $path";