xref: /dokuwiki/inc/httputils.php (revision 12ead38a3265c876ad16de2b1607d07abd11f90b)
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
10define('HTTP_MULTIPART_BOUNDARY', 'D0KuW1K1B0uNDARY');
11define('HTTP_HEADER_LF', "\r\n");
12define('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 */
23function 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 */
67function 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, #2895 nginx needs an internal redirect URL, not a file path.
82        header("X-Accel-Redirect: " . http_xaccel_url($file));
83        ob_end_clean();
84        exit;
85    }
86}
87
88/**
89 * Build the internal redirect URL for nginx's X-Accel-Redirect header
90 *
91 * Construct a request path from a given file path that nginx can resolve to the file through an `internal` location.
92 * A. Files inside the DokuWiki installation are returned as relative paths.
93 * B. Standard data directory paths are returned as /data/* paths regardless of their actual location (reconfigured
94 *    savedir or mediadir).
95 * C. Paths outside the DokuWiki installation are returned with a /_x_accel_redirect/ prefix
96 *
97 * Nginx admins need to configure appropriate internal location mappings.
98 *
99 * @param string $file absolute path of the file to send
100 * @return string the relative URL for the X-Accel-Redirect header
101 */
102function http_xaccel_url($file)
103{
104    global $conf;
105
106    $file = fullpath($file);
107    // DOKU_INC and savedir may carry uncanonicalized segments (the lib/exe entry points define
108    // DOKU_INC as __DIR__.'/../../', savedir defaults to the relative './data'); canonicalize both
109    // sides so the prefix comparisons against the canonicalized $file actually match
110    $dokuinc = fullpath(DOKU_INC) . '/';
111
112    if (str_starts_with($file, $dokuinc)) {
113        // A. files inside the DokuWiki directory: keep their path relative to the root
114        $path = substr($file, strlen($dokuinc));
115    } else {
116        // C. files outside DokuWiki and its data dirs: add prefix (overridden below if a root matches)
117        $path = '_x_accel_redirect/' . ltrim($file, '/');
118
119        // B. files in a relocated data directory: map back to their default URL below data/
120        $roots = [
121            fullpath($conf['mediadir'])    => 'data/media/',
122            fullpath($conf['mediaolddir']) => 'data/media_attic/',
123            fullpath($conf['cachedir'])    => 'data/cache/',
124            fullpath($conf['savedir'])     => 'data/',
125        ];
126        // match the most specific (longest) root first so nested directories win
127        uksort($roots, fn($a, $b) => strlen($b) - strlen($a));
128
129        foreach ($roots as $root => $logical) {
130            if (str_starts_with($file, $root . '/')) {
131                $path = $logical . substr($file, strlen($root) + 1);
132                break;
133            }
134        }
135    }
136
137    // URL-encode each segment (nginx URL-decodes the redirect target before resolving it)
138    return DOKU_REL . implode('/', array_map(rawurlencode(...), explode('/', $path)));
139}
140
141/**
142 * Send file contents supporting rangeRequests
143 *
144 * This function exits the running script
145 *
146 * @param resource $fh - file handle for an already open file
147 * @param int $size - size of the whole file
148 * @param int $mime - MIME type of the file
149 *
150 * @author Andreas Gohr <andi@splitbrain.org>
151 */
152function http_rangeRequest($fh, $size, $mime)
153{
154    global $INPUT;
155
156    $ranges = [];
157    $isrange = false;
158
159    header('Accept-Ranges: bytes');
160
161    if (!$INPUT->server->has('HTTP_RANGE')) {
162        // no range requested - send the whole file
163        $ranges[] = [0, $size, $size];
164    } else {
165        $t = explode('=', $INPUT->server->str('HTTP_RANGE'));
166        if (!$t[0] == 'bytes') {
167            // we only understand byte ranges - send the whole file
168            $ranges[] = [0, $size, $size];
169        } else {
170            $isrange = true;
171            // handle multiple ranges
172            $r = explode(',', $t[1]);
173            foreach ($r as $x) {
174                $p = explode('-', $x);
175                $start = (int)$p[0];
176                $end = (int)$p[1];
177                if (!$end) $end = $size - 1;
178                if ($start > $end || $start > $size || $end > $size) {
179                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
180                    echo 'Bad Range Request!';
181                    exit;
182                }
183                $len = $end - $start + 1;
184                $ranges[] = [$start, $end, $len];
185            }
186        }
187    }
188    $parts = count($ranges);
189
190    // now send the type and length headers
191    if (!$isrange) {
192        header("Content-Type: $mime", true);
193    } else {
194        header('HTTP/1.1 206 Partial Content');
195        if ($parts == 1) {
196            header("Content-Type: $mime", true);
197        } else {
198            header('Content-Type: multipart/byteranges; boundary=' . HTTP_MULTIPART_BOUNDARY, true);
199        }
200    }
201
202    // send all ranges
203    for ($i = 0; $i < $parts; $i++) {
204        [$start, $end, $len] = $ranges[$i];
205
206        // multipart or normal headers
207        if ($parts > 1) {
208            echo HTTP_HEADER_LF . '--' . HTTP_MULTIPART_BOUNDARY . HTTP_HEADER_LF;
209            echo "Content-Type: $mime" . HTTP_HEADER_LF;
210            echo "Content-Range: bytes $start-$end/$size" . HTTP_HEADER_LF;
211            echo HTTP_HEADER_LF;
212        } else {
213            header("Content-Length: $len");
214            if ($isrange) {
215                header("Content-Range: bytes $start-$end/$size");
216            }
217        }
218
219        // send file content
220        fseek($fh, $start); //seek to start of range
221        $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
222        while (!feof($fh) && $chunk > 0) {
223            @set_time_limit(30); // large files can take a lot of time
224            echo fread($fh, $chunk);
225            flush();
226            $len -= $chunk;
227            $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
228        }
229    }
230    if ($parts > 1) {
231        echo HTTP_HEADER_LF . '--' . HTTP_MULTIPART_BOUNDARY . '--' . HTTP_HEADER_LF;
232    }
233
234    // everything should be done here, exit (or return if testing)
235    if (defined('SIMPLE_TEST')) return;
236    exit;
237}
238
239/**
240 * Check for a gzipped version and create if necessary
241 *
242 * return true if there exists a gzip version of the uncompressed file
243 * (samepath/samefilename.sameext.gz) created after the uncompressed file
244 *
245 * @param string $uncompressed_file
246 * @return bool
247 * @author Chris Smith <chris.eureka@jalakai.co.uk>
248 *
249 */
250function http_gzip_valid($uncompressed_file)
251{
252    if (!DOKU_HAS_GZIP) return false;
253
254    $gzip = $uncompressed_file . '.gz';
255    if (filemtime($gzip) < filemtime($uncompressed_file)) {    // filemtime returns false (0) if file doesn't exist
256        return copy($uncompressed_file, 'compress.zlib://' . $gzip);
257    }
258
259    return true;
260}
261
262/**
263 * Set HTTP headers and echo cachefile, if useable
264 *
265 * This function handles output of cacheable resource files. It ses the needed
266 * HTTP headers. If a useable cache is present, it is passed to the web server
267 * and the script is terminated.
268 *
269 * @param string $cache cache file name
270 * @param bool $cache_ok if cache can be used
271 */
272function http_cached($cache, $cache_ok)
273{
274    global $conf;
275
276    // check cache age & handle conditional request
277    // since the resource files are timestamped, we can use a long max age: 1 year
278    header('Cache-Control: public, max-age=31536000');
279    header('Pragma: public');
280    if ($cache_ok) {
281        http_conditionalRequest(filemtime($cache));
282        if ($conf['allowdebug']) header("X-CacheUsed: $cache");
283
284        // finally send output
285        if ($conf['gzip_output'] && http_gzip_valid($cache)) {
286            header('Vary: Accept-Encoding');
287            header('Content-Encoding: gzip');
288            readfile($cache . ".gz");
289        } else {
290            http_sendfile($cache);
291            readfile($cache);
292        }
293        exit;
294    }
295
296    http_conditionalRequest(time());
297}
298
299/**
300 * Cache content and print it
301 *
302 * @param string $file file name
303 * @param string $content
304 */
305function http_cached_finish($file, $content)
306{
307    global $conf;
308
309    // save cache file
310    io_saveFile($file, $content);
311    if (DOKU_HAS_GZIP) io_saveFile("$file.gz", $content);
312
313    // finally send output
314    if ($conf['gzip_output'] && DOKU_HAS_GZIP) {
315        header('Vary: Accept-Encoding');
316        header('Content-Encoding: gzip');
317        echo gzencode($content, 9, FORCE_GZIP);
318    } else {
319        echo $content;
320    }
321}
322
323/**
324 * Fetches raw, unparsed POST data
325 *
326 * @return string
327 */
328function http_get_raw_post_data()
329{
330    static $postData = null;
331    if ($postData === null) {
332        $postData = file_get_contents('php://input');
333    }
334    return $postData;
335}
336
337/**
338 * Set the HTTP response status and takes care of the used PHP SAPI
339 *
340 * Inspired by CodeIgniter's set_status_header function
341 *
342 * @param int $code
343 * @param string $text
344 */
345function http_status($code = 200, $text = '')
346{
347    global $INPUT;
348
349    static $stati = [
350        200 => 'OK',
351        201 => 'Created',
352        202 => 'Accepted',
353        203 => 'Non-Authoritative Information',
354        204 => 'No Content',
355        205 => 'Reset Content',
356        206 => 'Partial Content',
357        300 => 'Multiple Choices',
358        301 => 'Moved Permanently',
359        302 => 'Found',
360        304 => 'Not Modified',
361        305 => 'Use Proxy',
362        307 => 'Temporary Redirect',
363        400 => 'Bad Request',
364        401 => 'Unauthorized',
365        403 => 'Forbidden',
366        404 => 'Not Found',
367        405 => 'Method Not Allowed',
368        406 => 'Not Acceptable',
369        407 => 'Proxy Authentication Required',
370        408 => 'Request Timeout',
371        409 => 'Conflict',
372        410 => 'Gone',
373        411 => 'Length Required',
374        412 => 'Precondition Failed',
375        413 => 'Request Entity Too Large',
376        414 => 'Request-URI Too Long',
377        415 => 'Unsupported Media Type',
378        416 => 'Requested Range Not Satisfiable',
379        417 => 'Expectation Failed',
380        500 => 'Internal Server Error',
381        501 => 'Not Implemented',
382        502 => 'Bad Gateway',
383        503 => 'Service Unavailable',
384        504 => 'Gateway Timeout',
385        505 => 'HTTP Version Not Supported'
386    ];
387
388    if ($text == '' && isset($stati[$code])) {
389        $text = $stati[$code];
390    }
391
392    $server_protocol = $INPUT->server->str('SERVER_PROTOCOL', false);
393
394    if (str_starts_with(PHP_SAPI, 'cgi') || defined('SIMPLE_TEST')) {
395        header("Status: {$code} {$text}", true);
396    } elseif ($server_protocol == 'HTTP/1.1' || $server_protocol == 'HTTP/1.0') {
397        header($server_protocol . " {$code} {$text}", true, $code);
398    } else {
399        header("HTTP/1.1 {$code} {$text}", true, $code);
400    }
401}
402