OSDN Git Service

8c02ad6cf57ea9baed588740c78f0e7f470fae60
[hengband/web.git] / dump_file.inc
1 <?php
2 class DumpFile
3 {
4     public function __construct($score_id) {
5         $this->score_id = $score_id;
6     }
7
8     public function show($dir, $ext, $content_type)
9     {
10         $dirname = sprintf("%s/%d", $dir, floor($this->score_id / 1000) * 1000);
11         $filename = sprintf("%s/%d.%s.gz", $dirname, $this->score_id, $ext);
12
13         if (!file_exists($filename)) {
14             http_response_code(404);
15             return;
16         }
17
18         $contents = file_get_contents($filename);
19         $etag = md5($contents);
20
21         if ($etag === filter_input(INPUT_SERVER, 'HTTP_IF_NONE_MATCH')) {
22             http_response_code(304);
23             return;
24         }
25
26         $content_encoding = self::get_content_encoding();
27         header("Etag: ".$etag);
28         header("Content-Type: ".$content_type);
29
30         if ($content_encoding !== FALSE) {
31             header("Content-Encoding: ".$content_encoding);
32             echo $contents;
33         } else {
34             echo gzdecode($contents);
35         }
36     }
37
38     private static function browser_accept_encodings()
39     {
40         if (!isset($_SERVER["HTTP_ACCEPT_ENCODING"])) return [];
41
42         return array_map('trim', explode(",", $_SERVER["HTTP_ACCEPT_ENCODING"]));
43     }
44
45
46     private static function get_content_encoding()
47     {
48         $supported_gzip_encodings = array_intersect(
49             self::browser_accept_encodings(),
50             ['gzip', 'x-gzip']);
51
52         return count($supported_gzip_encodings) > 0 ?
53             $supported_gzip_encodings[0] : FALSE;
54     }
55
56 }