prefer get parameter for apache redirects
[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($_GET['clan'] ?? $_SERVER['PATH_INFO'], '/');
21 $target = "data/$request.json";
22 $last = file_exists($target) ? lstat($target)['mtime'] : 0;
23
24 if ($last < time() - 3600) {
25         $recipe = NULL;
26         if (is_numeric($request)) {
27                 $recipe = $request;
28         }
29         elseif ($last) {
30                 if ($data = json_decode(file_get_contents($target), true)) {
31                         $profiles = array_column($data['members'], 'profileId');
32                         #TODO: reduce profiles by checking ladder presence
33                         $recipe = join(' ', array_merge([$request], $profiles));
34                 }
35         }
36         else {
37                 error("Unknown profile request <q>$request</q>", 400);
38         }
39
40         if ($recipe) {
41                 system("./getsc2clan $recipe | sponge $target", $exitcode);
42                 if ($exitcode and !$last) {
43                         error("No results for profile $request from Blizzard", 503);
44                 }
45         }
46 }
47 if (!filesize($target)) {
48         error("No clan data for <q>$request</q>", 404);
49 }
50 require('widget.html');