keep json includes in data/ subdir
[sc2-widget] / widget.php
1 <?php
2 function error($message, $status = 500)
3 {
4         http_response_code($status);
5         if ($page = @fopen('widget.html', 'r')) {
6                 # copy static page contents until page body
7                 while (!feof($page)) {
8                         print $line = fgets($page);
9                         if (preg_match('/<body\b/', $line)) break;
10                 }
11         }
12         else {
13                 print '<html><body>';
14         }
15         print "<p>$message</p>\n";
16         print "</body>\n</html>\n";
17         exit;
18 }
19
20 $request = trim($_SERVER['PATH_INFO'], '/');
21 $target = "data/$request.json";
22 $last = file_exists($target) ? filemtime($target) : 0;
23
24 if ($last < time() - 3600) {
25         $recipe = NULL;
26         if (is_numeric($request)) {
27                 $recipe = $request;
28         }
29         elseif (!$last) {
30                 error("Unknown profile request <q>$request</q>", 400);
31         }
32
33         if ($recipe) {
34                 system("./getsc2clan $recipe | sponge $target", $exitcode);
35                 if ($exitcode and !$last) {
36                         error("No results for profile $request from Blizzard", 503);
37                 }
38         }
39 }
40 if (!filesize($target)) {
41         error("No clan data for <q>$request</q>", 404);
42 }
43 require('widget.html');