1<?php
2
3/*
4 *  pgn4web javascript chessboard
5 *  copyright (C) 2009-2013 Paolo Casaschi
6 *  see README file and http://pgn4web.casaschi.net
7 *  for credits, license and more details
8 */
9
10error_reporting(E_ALL | E_STRICT);
11
12function get_param($param, $shortParam, $default) {
13  if (isset($_REQUEST[$param])) { return $_REQUEST[$param]; }
14  if (isset($_REQUEST[$shortParam])) { return $_REQUEST[$shortParam]; }
15  return $default;
16}
17
18$pgnData = get_param("pgnData", "pd", "gotd.pgn");
19
20
21function get_pgnText($pgnUrl) {
22  if (strpos($pgnUrl, ":") || (strpos($pgnUrl, "%3A"))) { return "[Event \"error: invalid pgnData=$pgnUrl\"]\n"; }
23  $fileLimitBytes = 10000000; // 10Mb
24  $pgnText = file_get_contents($pgnUrl, NULL, NULL, 0, $fileLimitBytes + 1);
25  if (!$pgnText) { return "[Event \"error: failed to get pgnData=$pgnUrl\"]\n"; }
26  $pgnText = str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), $pgnText);
27  return $pgnText;
28}
29
30$pgnText = get_pgnText($pgnData);
31
32$numGames = preg_match_all("/(\s*\[\s*(\w+)\s*\"([^\"]*)\"\s*\]\s*)+[^\[]*/", $pgnText, $games );
33
34
35$gameNum = get_param("gameNum", "gn", "");
36
37$expiresDate = "";
38if ($gameNum == "random") { $gameNum = rand(1, $numGames); }
39else if (!preg_match("/^\d+$/", $gameNum)) {
40  $timeNow = time();
41  $expiresDate = gmdate("D, d M Y H:i:s", (floor($timeNow / (60 * 60 * 24)) + 1) * (60 * 60 * 24)) . " GMT";
42  if (!preg_match("/^[ +-]\d+$/", $gameNum)) { $gameNum = 0; } // space is needed since + is urldecoded as space
43  $gameNum = floor(($gameNum + ($timeNow / (60 * 60 * 24))) % $numGames) + 1;
44}
45else if ($gameNum < 1) { $gameNum = 1; }
46else if ($gameNum > $numGames) { $gameNum = $numGames; }
47$gameNum -= 1;
48
49header("content-type: application/x-chess-pgn");
50header("content-disposition: inline; filename=game.pgn");
51if ($expiresDate) {
52  header("expires: " . $expiresDate);
53}
54print $games[0][$gameNum];
55
56?>
57