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