<?php
-$request = trim($_SERVER['PATH_INFO'], '/');
-if (!file_exists("$request.json")) {
- if (!is_numeric($request)) {
- die("unknown profile request $request");
+function error($message, $status = 500)
+{
+ http_response_code($status);
+ if ($page = @fopen('widget.html', 'r')) {
+ # copy static page contents until page body
+ while (!feof($page)) {
+ print $line = fgets($page);
+ if (preg_match('/<body\b/', $line)) break;
+ }
}
- system("./getsc2clan $request | sponge $request.json", $exitcode);
- if ($exitcode) {
- die("no results for profile id $request from Blizzard");
+ else {
+ print '<html><body>';
}
+ print "<p>$message</p>\n";
+ print "</body>\n</html>\n";
+ exit;
+}
+
+$request = trim($_GET['clan'] ?? $_SERVER['PATH_INFO'], '/');
+$target = "data/$request.json";
+$last = file_exists($target) ? lstat($target)['mtime'] : 0;
+
+if ($last < time() - 3600) {
+ $recipe = NULL;
+ if (is_numeric($request)) {
+ $recipe = $request;
+ }
+ elseif ($last) {
+ if ($data = json_decode(file_get_contents($target), true)) {
+ $profiles = array_column($data['members'], 'profileId');
+ #TODO: reduce profiles by checking ladder presence
+ $recipe = join(' ', array_merge([$request], $profiles));
+ }
+ }
+ else {
+ error("Unknown profile request <q>$request</q>", 400);
+ }
+
+ if ($recipe) {
+ system("./getsc2clan $recipe | sponge $target", $exitcode);
+ if ($exitcode and !$last) {
+ error("No results for profile $request from Blizzard", 503);
+ }
+ }
+}
+if (!filesize($target)) {
+ error("No clan data for <q>$request</q>", 404);
}
require('widget.html');