1 <?php
2 
3 /**
4  * Utilities for handling HTTP related tasks
5  *
6  * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7  * @author     Andreas Gohr <andi@splitbrain.org>
8  */
9 
10 define('HTTP_MULTIPART_BOUNDARY', 'D0KuW1K1B0uNDARY');
11 define('HTTP_HEADER_LF', "\r\n");
12 define('HTTP_CHUNK_SIZE', 16 * 1024);
13 
14 /**
15  * Checks and sets HTTP headers for conditional HTTP requests
16  *
17  * @param int $timestamp lastmodified time of the cache file
18  * @returns  void or exits with previously header() commands executed
19  * @link     http://simonwillison.net/2003/Apr/23/conditionalGet/
20  *
21  * @author   Simon Willison <swillison@gmail.com>
22  */
23 function http_conditionalRequest($timestamp)
24 {
25     global $INPUT;
26 
27     // A PHP implementation of conditional get, see
28     //   http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/
29     $last_modified = substr(gmdate('r', $timestamp), 0, -5) . 'GMT';
30     $etag = '"' . md5($last_modified) . '"';
31     // Send the headers
32     header("Last-Modified: $last_modified");
33     header("ETag: $etag");
34     // See if the client has provided the required headers
35     $if_modified_since = $INPUT->server->filter('stripslashes')->str('HTTP_IF_MODIFIED_SINCE', false);
36     $if_none_match = $INPUT->server->filter('stripslashes')->str('HTTP_IF_NONE_MATCH', false);
37 
38     if (!$if_modified_since && !$if_none_match) {
39         return;
40     }
41 
42     // At least one of the headers is there - check them
43     if ($if_none_match && $if_none_match != $etag) {
44         return; // etag is there but doesn't match
45     }
46 
47     if ($if_modified_since && $if_modified_since != $last_modified) {
48         return; // if-modified-since is there but doesn't match
49     }
50 
51     // Nothing has changed since their last request - serve a 304 and exit
52     header('HTTP/1.0 304 Not Modified');
53 
54     // don't produce output, even if compression is on
55     @ob_end_clean();
56     exit;
57 }
58 
59 /**
60  * Let the webserver send the given file via x-sendfile method
61  *
62  * @param string $file absolute path of file to send
63  * @returns  void or exits with previous header() commands executed
64  * @author Chris Smith <chris@jalakai.co.uk>
65  *
66  */
67 function http_sendfile($file)
68 {
69     global $conf;
70 
71     //use x-sendfile header to pass the delivery to compatible web servers
72     if ($conf['xsendfile'] == 1) {
73         header("X-LIGHTTPD-send-file: $file");
74         ob_end_clean();
75         exit;
76     } elseif ($conf['xsendfile'] == 2) {
77         header("X-Sendfile: $file");
78         ob_end_clean();
79         exit;
80     } elseif ($conf['xsendfile'] == 3) {
81         // FS#2388 nginx just needs the relative path.
82         $file = DOKU_REL . substr($file, strlen(fullpath(DOKU_INC)) + 1);
83         header("X-Accel-Redirect: $file");
84         ob_end_clean();
85         exit;
86     }
87 }
88 
89 /**
90  * Send file contents supporting rangeRequests
91  *
92  * This function exits the running script
93  *
94  * @param resource $fh - file handle for an already open file
95  * @param int $size - size of the whole file
96  * @param int $mime - MIME type of the file
97  *
98  * @author Andreas Gohr <andi@splitbrain.org>
99  */
100 function http_rangeRequest($fh, $size, $mime)
101 {
102     global $INPUT;
103 
104     $ranges = [];
105     $isrange = false;
106 
107     header('Accept-Ranges: bytes');
108 
109     if (!$INPUT->server->has('HTTP_RANGE')) {
110         // no range requested - send the whole file
111         $ranges[] = [0, $size, $size];
112     } else {
113         $t = explode('=', $INPUT->server->str('HTTP_RANGE'));
114         if (!$t[0] == 'bytes') {
115             // we only understand byte ranges - send the whole file
116             $ranges[] = [0, $size, $size];
117         } else {
118             $isrange = true;
119             // handle multiple ranges
120             $r = explode(',', $t[1]);
121             foreach ($r as $x) {
122                 $p = explode('-', $x);
123                 $start = (int)$p[0];
124                 $end = (int)$p[1];
125                 if (!$end) $end = $size - 1;
126                 if ($start > $end || $start > $size || $end > $size) {
127                     header('HTTP/1.1 416 Requested Range Not Satisfiable');
128                     echo 'Bad Range Request!';
129                     exit;
130                 }
131                 $len = $end - $start + 1;
132                 $ranges[] = [$start, $end, $len];
133             }
134         }
135     }
136     $parts = count($ranges);
137 
138     // now send the type and length headers
139     if (!$isrange) {
140         header("Content-Type: $mime", true);
141     } else {
142         header('HTTP/1.1 206 Partial Content');
143         if ($parts == 1) {
144             header("Content-Type: $mime", true);
145         } else {
146             header('Content-Type: multipart/byteranges; boundary=' . HTTP_MULTIPART_BOUNDARY, true);
147         }
148     }
149 
150     // send all ranges
151     for ($i = 0; $i < $parts; $i++) {
152         [$start, $end, $len] = $ranges[$i];
153 
154         // multipart or normal headers
155         if ($parts > 1) {
156             echo HTTP_HEADER_LF . '--' . HTTP_MULTIPART_BOUNDARY . HTTP_HEADER_LF;
157             echo "Content-Type: $mime" . HTTP_HEADER_LF;
158             echo "Content-Range: bytes $start-$end/$size" . HTTP_HEADER_LF;
159             echo HTTP_HEADER_LF;
160         } else {
161             header("Content-Length: $len");
162             if ($isrange) {
163                 header("Content-Range: bytes $start-$end/$size");
164             }
165         }
166 
167         // send file content
168         fseek($fh, $start); //seek to start of range
169         $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
170         while (!feof($fh) && $chunk > 0) {
171             @set_time_limit(30); // large files can take a lot of time
172             echo fread($fh, $chunk);
173             flush();
174             $len -= $chunk;
175             $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
176         }
177     }
178     if ($parts > 1) {
179         echo HTTP_HEADER_LF . '--' . HTTP_MULTIPART_BOUNDARY . '--' . HTTP_HEADER_LF;
180     }
181 
182     // everything should be done here, exit (or return if testing)
183     if (defined('SIMPLE_TEST')) return;
184     exit;
185 }
186 
187 /**
188  * Check for a gzipped version and create if necessary
189  *
190  * return true if there exists a gzip version of the uncompressed file
191  * (samepath/samefilename.sameext.gz) created after the uncompressed file
192  *
193  * @param string $uncompressed_file
194  * @return bool
195  * @author Chris Smith <chris.eureka@jalakai.co.uk>
196  *
197  */
198 function http_gzip_valid($uncompressed_file)
199 {
200     if (!DOKU_HAS_GZIP) return false;
201 
202     $gzip = $uncompressed_file . '.gz';
203     if (filemtime($gzip) < filemtime($uncompressed_file)) {    // filemtime returns false (0) if file doesn't exist
204         return copy($uncompressed_file, 'compress.zlib://' . $gzip);
205     }
206 
207     return true;
208 }
209 
210 /**
211  * Set HTTP headers and echo cachefile, if useable
212  *
213  * This function handles output of cacheable resource files. It ses the needed
214  * HTTP headers. If a useable cache is present, it is passed to the web server
215  * and the script is terminated.
216  *
217  * @param string $cache cache file name
218  * @param bool $cache_ok if cache can be used
219  */
220 function http_cached($cache, $cache_ok)
221 {
222     global $conf;
223 
224     // check cache age & handle conditional request
225     // since the resource files are timestamped, we can use a long max age: 1 year
226     header('Cache-Control: public, max-age=31536000');
227     header('Pragma: public');
228     if ($cache_ok) {
229         http_conditionalRequest(filemtime($cache));
230         if ($conf['allowdebug']) header("X-CacheUsed: $cache");
231 
232         // finally send output
233         if ($conf['gzip_output'] && http_gzip_valid($cache)) {
234             header('Vary: Accept-Encoding');
235             header('Content-Encoding: gzip');
236             readfile($cache . ".gz");
237         } else {
238             http_sendfile($cache);
239             readfile($cache);
240         }
241         exit;
242     }
243 
244     http_conditionalRequest(time());
245 }
246 
247 /**
248  * Cache content and print it
249  *
250  * @param string $file file name
251  * @param string $content
252  */
253 function http_cached_finish($file, $content)
254 {
255     global $conf;
256 
257     // save cache file
258     io_saveFile($file, $content);
259     if (DOKU_HAS_GZIP) io_saveFile("$file.gz", $content);
260 
261     // finally send output
262     if ($conf['gzip_output'] && DOKU_HAS_GZIP) {
263         header('Vary: Accept-Encoding');
264         header('Content-Encoding: gzip');
265         echo gzencode($content, 9, FORCE_GZIP);
266     } else {
267         echo $content;
268     }
269 }
270 
271 /**
272  * Fetches raw, unparsed POST data
273  *
274  * @return string
275  */
276 function http_get_raw_post_data()
277 {
278     static $postData = null;
279     if ($postData === null) {
280         $postData = file_get_contents('php://input');
281     }
282     return $postData;
283 }
284 
285 /**
286  * Set the HTTP response status and takes care of the used PHP SAPI
287  *
288  * Inspired by CodeIgniter's set_status_header function
289  *
290  * @param int $code
291  * @param string $text
292  */
293 function http_status($code = 200, $text = '')
294 {
295     global $INPUT;
296 
297     static $stati = [
298         200 => 'OK',
299         201 => 'Created',
300         202 => 'Accepted',
301         203 => 'Non-Authoritative Information',
302         204 => 'No Content',
303         205 => 'Reset Content',
304         206 => 'Partial Content',
305         300 => 'Multiple Choices',
306         301 => 'Moved Permanently',
307         302 => 'Found',
308         304 => 'Not Modified',
309         305 => 'Use Proxy',
310         307 => 'Temporary Redirect',
311         400 => 'Bad Request',
312         401 => 'Unauthorized',
313         403 => 'Forbidden',
314         404 => 'Not Found',
315         405 => 'Method Not Allowed',
316         406 => 'Not Acceptable',
317         407 => 'Proxy Authentication Required',
318         408 => 'Request Timeout',
319         409 => 'Conflict',
320         410 => 'Gone',
321         411 => 'Length Required',
322         412 => 'Precondition Failed',
323         413 => 'Request Entity Too Large',
324         414 => 'Request-URI Too Long',
325         415 => 'Unsupported Media Type',
326         416 => 'Requested Range Not Satisfiable',
327         417 => 'Expectation Failed',
328         500 => 'Internal Server Error',
329         501 => 'Not Implemented',
330         502 => 'Bad Gateway',
331         503 => 'Service Unavailable',
332         504 => 'Gateway Timeout',
333         505 => 'HTTP Version Not Supported'
334     ];
335 
336     if ($text == '' && isset($stati[$code])) {
337         $text = $stati[$code];
338     }
339 
340     $server_protocol = $INPUT->server->str('SERVER_PROTOCOL', false);
341 
342     if (str_starts_with(PHP_SAPI, 'cgi') || defined('SIMPLE_TEST')) {
343         header("Status: {$code} {$text}", true);
344     } elseif ($server_protocol == 'HTTP/1.1' || $server_protocol == 'HTTP/1.0') {
345         header($server_protocol . " {$code} {$text}", true, $code);
346     } else {
347         header("HTTP/1.1 {$code} {$text}", true, $code);
348     }
349 }
350