xref: /dokuwiki/inc/httputils.php (revision 24870174d2ee45460ba6bcfe5f5a0ae94715efd7)
1758447cfSAndreas Gohr<?php
2758447cfSAndreas Gohr/**
3758447cfSAndreas Gohr * Utilities for handling HTTP related tasks
4758447cfSAndreas Gohr *
5758447cfSAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6758447cfSAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
7758447cfSAndreas Gohr */
8758447cfSAndreas Gohr
9758447cfSAndreas Gohrdefine('HTTP_MULTIPART_BOUNDARY', 'D0KuW1K1B0uNDARY');
10758447cfSAndreas Gohrdefine('HTTP_HEADER_LF', "\r\n");
11758447cfSAndreas Gohrdefine('HTTP_CHUNK_SIZE', 16 * 1024);
12758447cfSAndreas Gohr
13758447cfSAndreas Gohr/**
14758447cfSAndreas Gohr * Checks and sets HTTP headers for conditional HTTP requests
15758447cfSAndreas Gohr *
1693b2e677SMichael Hamann * @param int $timestamp lastmodified time of the cache file
17758447cfSAndreas Gohr * @returns  void or exits with previously header() commands executed
18*24870174SAndreas Gohr * @link     http://simonwillison.net/2003/Apr/23/conditionalGet/
19*24870174SAndreas Gohr *
20*24870174SAndreas Gohr * @author   Simon Willison <swillison@gmail.com>
21758447cfSAndreas Gohr */
22*24870174SAndreas Gohrfunction http_conditionalRequest($timestamp)
23*24870174SAndreas Gohr{
242b9be456SAndreas Gohr    global $INPUT;
252b9be456SAndreas Gohr
26758447cfSAndreas Gohr    // A PHP implementation of conditional get, see
2723a96c41SElan Ruusamäe    //   http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/
28758447cfSAndreas Gohr    $last_modified = substr(gmdate('r', $timestamp), 0, -5) . 'GMT';
29758447cfSAndreas Gohr    $etag = '"' . md5($last_modified) . '"';
30758447cfSAndreas Gohr    // Send the headers
31758447cfSAndreas Gohr    header("Last-Modified: $last_modified");
32758447cfSAndreas Gohr    header("ETag: $etag");
33758447cfSAndreas Gohr    // See if the client has provided the required headers
342b9be456SAndreas Gohr    $if_modified_since = $INPUT->server->filter('stripslashes')->str('HTTP_IF_MODIFIED_SINCE', false);
352b9be456SAndreas Gohr    $if_none_match = $INPUT->server->filter('stripslashes')->str('HTTP_IF_NONE_MATCH', false);
36758447cfSAndreas Gohr
37758447cfSAndreas Gohr    if (!$if_modified_since && !$if_none_match) {
38758447cfSAndreas Gohr        return;
39758447cfSAndreas Gohr    }
40758447cfSAndreas Gohr
41758447cfSAndreas Gohr    // At least one of the headers is there - check them
42758447cfSAndreas Gohr    if ($if_none_match && $if_none_match != $etag) {
43758447cfSAndreas Gohr        return; // etag is there but doesn't match
44758447cfSAndreas Gohr    }
45758447cfSAndreas Gohr
46758447cfSAndreas Gohr    if ($if_modified_since && $if_modified_since != $last_modified) {
47758447cfSAndreas Gohr        return; // if-modified-since is there but doesn't match
48758447cfSAndreas Gohr    }
49758447cfSAndreas Gohr
50758447cfSAndreas Gohr    // Nothing has changed since their last request - serve a 304 and exit
51758447cfSAndreas Gohr    header('HTTP/1.0 304 Not Modified');
52758447cfSAndreas Gohr
53758447cfSAndreas Gohr    // don't produce output, even if compression is on
54c66972f2SAdrian Lang    @ob_end_clean();
55758447cfSAndreas Gohr    exit;
56758447cfSAndreas Gohr}
57758447cfSAndreas Gohr
58758447cfSAndreas Gohr/**
59b051e974SChristopher Smith * Let the webserver send the given file via x-sendfile method
60758447cfSAndreas Gohr *
6140e0b444SDominik Eckelmann * @param string $file absolute path of file to send
62f327a5f0SChristopher Smith * @returns  void or exits with previous header() commands executed
63*24870174SAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
64*24870174SAndreas Gohr *
65758447cfSAndreas Gohr */
66*24870174SAndreas Gohrfunction http_sendfile($file)
67*24870174SAndreas Gohr{
68758447cfSAndreas Gohr    global $conf;
69758447cfSAndreas Gohr
70758447cfSAndreas Gohr    //use x-sendfile header to pass the delivery to compatible web servers
71758447cfSAndreas Gohr    if ($conf['xsendfile'] == 1) {
72758447cfSAndreas Gohr        header("X-LIGHTTPD-send-file: $file");
73758447cfSAndreas Gohr        ob_end_clean();
74758447cfSAndreas Gohr        exit;
75758447cfSAndreas Gohr    } elseif ($conf['xsendfile'] == 2) {
76758447cfSAndreas Gohr        header("X-Sendfile: $file");
77758447cfSAndreas Gohr        ob_end_clean();
78758447cfSAndreas Gohr        exit;
79758447cfSAndreas Gohr    } elseif ($conf['xsendfile'] == 3) {
80446b5b59SDominik Eckelmann        // FS#2388 nginx just needs the relative path.
81446b5b59SDominik Eckelmann        $file = DOKU_REL . substr($file, strlen(fullpath(DOKU_INC)) + 1);
82758447cfSAndreas Gohr        header("X-Accel-Redirect: $file");
83758447cfSAndreas Gohr        ob_end_clean();
84758447cfSAndreas Gohr        exit;
85758447cfSAndreas Gohr    }
86758447cfSAndreas Gohr}
87758447cfSAndreas Gohr
88758447cfSAndreas Gohr/**
89758447cfSAndreas Gohr * Send file contents supporting rangeRequests
90758447cfSAndreas Gohr *
91758447cfSAndreas Gohr * This function exits the running script
92758447cfSAndreas Gohr *
9390124802SGerrit Uitslag * @param resource $fh - file handle for an already open file
94758447cfSAndreas Gohr * @param int $size - size of the whole file
95758447cfSAndreas Gohr * @param int $mime - MIME type of the file
96758447cfSAndreas Gohr *
97758447cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
98758447cfSAndreas Gohr */
99*24870174SAndreas Gohrfunction http_rangeRequest($fh, $size, $mime)
100*24870174SAndreas Gohr{
1012b9be456SAndreas Gohr    global $INPUT;
1022b9be456SAndreas Gohr
103*24870174SAndreas Gohr    $ranges = [];
104758447cfSAndreas Gohr    $isrange = false;
105758447cfSAndreas Gohr
106758447cfSAndreas Gohr    header('Accept-Ranges: bytes');
107758447cfSAndreas Gohr
1082b9be456SAndreas Gohr    if (!$INPUT->server->has('HTTP_RANGE')) {
109758447cfSAndreas Gohr        // no range requested - send the whole file
110*24870174SAndreas Gohr        $ranges[] = [0, $size, $size];
111758447cfSAndreas Gohr    } else {
1122b9be456SAndreas Gohr        $t = explode('=', $INPUT->server->str('HTTP_RANGE'));
113758447cfSAndreas Gohr        if (!$t[0] == 'bytes') {
114758447cfSAndreas Gohr            // we only understand byte ranges - send the whole file
115*24870174SAndreas Gohr            $ranges[] = [0, $size, $size];
116758447cfSAndreas Gohr        } else {
117758447cfSAndreas Gohr            $isrange = true;
118758447cfSAndreas Gohr            // handle multiple ranges
119758447cfSAndreas Gohr            $r = explode(',', $t[1]);
120758447cfSAndreas Gohr            foreach ($r as $x) {
121758447cfSAndreas Gohr                $p = explode('-', $x);
122758447cfSAndreas Gohr                $start = (int)$p[0];
123758447cfSAndreas Gohr                $end = (int)$p[1];
124758447cfSAndreas Gohr                if (!$end) $end = $size - 1;
125758447cfSAndreas Gohr                if ($start > $end || $start > $size || $end > $size) {
126758447cfSAndreas Gohr                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
127758447cfSAndreas Gohr                    print 'Bad Range Request!';
128758447cfSAndreas Gohr                    exit;
129758447cfSAndreas Gohr                }
130758447cfSAndreas Gohr                $len = $end - $start + 1;
131*24870174SAndreas Gohr                $ranges[] = [$start, $end, $len];
132758447cfSAndreas Gohr            }
133758447cfSAndreas Gohr        }
134758447cfSAndreas Gohr    }
135758447cfSAndreas Gohr    $parts = count($ranges);
136758447cfSAndreas Gohr
137758447cfSAndreas Gohr    // now send the type and length headers
138758447cfSAndreas Gohr    if (!$isrange) {
139758447cfSAndreas Gohr        header("Content-Type: $mime", true);
140758447cfSAndreas Gohr    } else {
141758447cfSAndreas Gohr        header('HTTP/1.1 206 Partial Content');
142758447cfSAndreas Gohr        if ($parts == 1) {
143758447cfSAndreas Gohr            header("Content-Type: $mime", true);
144758447cfSAndreas Gohr        } else {
145758447cfSAndreas Gohr            header('Content-Type: multipart/byteranges; boundary=' . HTTP_MULTIPART_BOUNDARY, true);
146758447cfSAndreas Gohr        }
147758447cfSAndreas Gohr    }
148758447cfSAndreas Gohr
149758447cfSAndreas Gohr    // send all ranges
150758447cfSAndreas Gohr    for ($i = 0; $i < $parts; $i++) {
151*24870174SAndreas Gohr        [$start, $end, $len] = $ranges[$i];
152758447cfSAndreas Gohr
153758447cfSAndreas Gohr        // multipart or normal headers
154758447cfSAndreas Gohr        if ($parts > 1) {
155758447cfSAndreas Gohr            echo HTTP_HEADER_LF . '--' . HTTP_MULTIPART_BOUNDARY . HTTP_HEADER_LF;
156758447cfSAndreas Gohr            echo "Content-Type: $mime" . HTTP_HEADER_LF;
157758447cfSAndreas Gohr            echo "Content-Range: bytes $start-$end/$size" . HTTP_HEADER_LF;
158b8b5563eSAndreas Gohr            echo HTTP_HEADER_LF;
159758447cfSAndreas Gohr        } else {
160758447cfSAndreas Gohr            header("Content-Length: $len");
161758447cfSAndreas Gohr            if ($isrange) {
162758447cfSAndreas Gohr                header("Content-Range: bytes $start-$end/$size");
163758447cfSAndreas Gohr            }
164758447cfSAndreas Gohr        }
165758447cfSAndreas Gohr
166758447cfSAndreas Gohr        // send file content
167758447cfSAndreas Gohr        fseek($fh, $start); //seek to start of range
168758447cfSAndreas Gohr        $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
169758447cfSAndreas Gohr        while (!feof($fh) && $chunk > 0) {
170758447cfSAndreas Gohr            @set_time_limit(30); // large files can take a lot of time
171758447cfSAndreas Gohr            print fread($fh, $chunk);
172758447cfSAndreas Gohr            flush();
173758447cfSAndreas Gohr            $len -= $chunk;
174758447cfSAndreas Gohr            $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
175758447cfSAndreas Gohr        }
176758447cfSAndreas Gohr    }
177758447cfSAndreas Gohr    if ($parts > 1) {
178758447cfSAndreas Gohr        echo HTTP_HEADER_LF . '--' . HTTP_MULTIPART_BOUNDARY . '--' . HTTP_HEADER_LF;
179758447cfSAndreas Gohr    }
180758447cfSAndreas Gohr
181b051e974SChristopher Smith    // everything should be done here, exit (or return if testing)
182b051e974SChristopher Smith    if (defined('SIMPLE_TEST')) return;
183758447cfSAndreas Gohr    exit;
184758447cfSAndreas Gohr}
185758447cfSAndreas Gohr
186758447cfSAndreas Gohr/**
187758447cfSAndreas Gohr * Check for a gzipped version and create if necessary
188758447cfSAndreas Gohr *
189758447cfSAndreas Gohr * return true if there exists a gzip version of the uncompressed file
190758447cfSAndreas Gohr * (samepath/samefilename.sameext.gz) created after the uncompressed file
191758447cfSAndreas Gohr *
19242ea7f44SGerrit Uitslag * @param string $uncompressed_file
19342ea7f44SGerrit Uitslag * @return bool
194*24870174SAndreas Gohr * @author Chris Smith <chris.eureka@jalakai.co.uk>
195*24870174SAndreas Gohr *
196758447cfSAndreas Gohr */
197*24870174SAndreas Gohrfunction http_gzip_valid($uncompressed_file)
198*24870174SAndreas Gohr{
19913c37900SAndreas Gohr    if (!DOKU_HAS_GZIP) return false;
20013c37900SAndreas Gohr
201758447cfSAndreas Gohr    $gzip = $uncompressed_file . '.gz';
202758447cfSAndreas Gohr    if (filemtime($gzip) < filemtime($uncompressed_file)) {    // filemtime returns false (0) if file doesn't exist
203758447cfSAndreas Gohr        return copy($uncompressed_file, 'compress.zlib://' . $gzip);
204758447cfSAndreas Gohr    }
205758447cfSAndreas Gohr
206758447cfSAndreas Gohr    return true;
207758447cfSAndreas Gohr}
2086619f42eSAdrian Lang
2096619f42eSAdrian Lang/**
2106619f42eSAdrian Lang * Set HTTP headers and echo cachefile, if useable
2116619f42eSAdrian Lang *
2126619f42eSAdrian Lang * This function handles output of cacheable resource files. It ses the needed
2136619f42eSAdrian Lang * HTTP headers. If a useable cache is present, it is passed to the web server
21490124802SGerrit Uitslag * and the script is terminated.
21542ea7f44SGerrit Uitslag *
21642ea7f44SGerrit Uitslag * @param string $cache cache file name
21742ea7f44SGerrit Uitslag * @param bool $cache_ok if cache can be used
2186619f42eSAdrian Lang */
219*24870174SAndreas Gohrfunction http_cached($cache, $cache_ok)
220*24870174SAndreas Gohr{
2216619f42eSAdrian Lang    global $conf;
2226619f42eSAdrian Lang
2236619f42eSAdrian Lang    // check cache age & handle conditional request
2246619f42eSAdrian Lang    // since the resource files are timestamped, we can use a long max age: 1 year
2256619f42eSAdrian Lang    header('Cache-Control: public, max-age=31536000');
2266619f42eSAdrian Lang    header('Pragma: public');
2276619f42eSAdrian Lang    if ($cache_ok) {
2286619f42eSAdrian Lang        http_conditionalRequest(filemtime($cache));
2296619f42eSAdrian Lang        if ($conf['allowdebug']) header("X-CacheUsed: $cache");
2306619f42eSAdrian Lang
2316619f42eSAdrian Lang        // finally send output
2326619f42eSAdrian Lang        if ($conf['gzip_output'] && http_gzip_valid($cache)) {
2336619f42eSAdrian Lang            header('Vary: Accept-Encoding');
2346619f42eSAdrian Lang            header('Content-Encoding: gzip');
2356619f42eSAdrian Lang            readfile($cache . ".gz");
2366619f42eSAdrian Lang        } else {
23740e0b444SDominik Eckelmann            http_sendfile($cache);
23840e0b444SDominik Eckelmann            readfile($cache);
2396619f42eSAdrian Lang        }
2406619f42eSAdrian Lang        exit;
2416619f42eSAdrian Lang    }
2426619f42eSAdrian Lang
2436619f42eSAdrian Lang    http_conditionalRequest(time());
2446619f42eSAdrian Lang}
2456619f42eSAdrian Lang
2466619f42eSAdrian Lang/**
2476619f42eSAdrian Lang * Cache content and print it
24842ea7f44SGerrit Uitslag *
24942ea7f44SGerrit Uitslag * @param string $file file name
25042ea7f44SGerrit Uitslag * @param string $content
2516619f42eSAdrian Lang */
252*24870174SAndreas Gohrfunction http_cached_finish($file, $content)
253*24870174SAndreas Gohr{
2546619f42eSAdrian Lang    global $conf;
2556619f42eSAdrian Lang
2566619f42eSAdrian Lang    // save cache file
2576619f42eSAdrian Lang    io_saveFile($file, $content);
25813c37900SAndreas Gohr    if (DOKU_HAS_GZIP) io_saveFile("$file.gz", $content);
2596619f42eSAdrian Lang
2606619f42eSAdrian Lang    // finally send output
26113c37900SAndreas Gohr    if ($conf['gzip_output'] && DOKU_HAS_GZIP) {
2626619f42eSAdrian Lang        header('Vary: Accept-Encoding');
2636619f42eSAdrian Lang        header('Content-Encoding: gzip');
2646619f42eSAdrian Lang        print gzencode($content, 9, FORCE_GZIP);
2656619f42eSAdrian Lang    } else {
2666619f42eSAdrian Lang        print $content;
2676619f42eSAdrian Lang    }
2686619f42eSAdrian Lang}
26996946cc9SDominik Eckelmann
2709d2e1be6SAndreas Gohr/**
2719d2e1be6SAndreas Gohr * Fetches raw, unparsed POST data
2729d2e1be6SAndreas Gohr *
2739d2e1be6SAndreas Gohr * @return string
2749d2e1be6SAndreas Gohr */
275*24870174SAndreas Gohrfunction http_get_raw_post_data()
276*24870174SAndreas Gohr{
27796946cc9SDominik Eckelmann    static $postData = null;
27896946cc9SDominik Eckelmann    if ($postData === null) {
27996946cc9SDominik Eckelmann        $postData = file_get_contents('php://input');
28096946cc9SDominik Eckelmann    }
28196946cc9SDominik Eckelmann    return $postData;
28296946cc9SDominik Eckelmann}
2839d2e1be6SAndreas Gohr
2849d2e1be6SAndreas Gohr/**
2859d2e1be6SAndreas Gohr * Set the HTTP response status and takes care of the used PHP SAPI
2869d2e1be6SAndreas Gohr *
2879d2e1be6SAndreas Gohr * Inspired by CodeIgniter's set_status_header function
2889d2e1be6SAndreas Gohr *
2899d2e1be6SAndreas Gohr * @param int $code
2909d2e1be6SAndreas Gohr * @param string $text
2919d2e1be6SAndreas Gohr */
292*24870174SAndreas Gohrfunction http_status($code = 200, $text = '')
293*24870174SAndreas Gohr{
2942b9be456SAndreas Gohr    global $INPUT;
2952b9be456SAndreas Gohr
296*24870174SAndreas Gohr    static $stati = [
2979d2e1be6SAndreas Gohr        200 => 'OK',
2989d2e1be6SAndreas Gohr        201 => 'Created',
2999d2e1be6SAndreas Gohr        202 => 'Accepted',
3009d2e1be6SAndreas Gohr        203 => 'Non-Authoritative Information',
3019d2e1be6SAndreas Gohr        204 => 'No Content',
3029d2e1be6SAndreas Gohr        205 => 'Reset Content',
3039d2e1be6SAndreas Gohr        206 => 'Partial Content',
3049d2e1be6SAndreas Gohr        300 => 'Multiple Choices',
3059d2e1be6SAndreas Gohr        301 => 'Moved Permanently',
3069d2e1be6SAndreas Gohr        302 => 'Found',
3079d2e1be6SAndreas Gohr        304 => 'Not Modified',
3089d2e1be6SAndreas Gohr        305 => 'Use Proxy',
3099d2e1be6SAndreas Gohr        307 => 'Temporary Redirect',
3109d2e1be6SAndreas Gohr        400 => 'Bad Request',
3119d2e1be6SAndreas Gohr        401 => 'Unauthorized',
3129d2e1be6SAndreas Gohr        403 => 'Forbidden',
3139d2e1be6SAndreas Gohr        404 => 'Not Found',
3149d2e1be6SAndreas Gohr        405 => 'Method Not Allowed',
3159d2e1be6SAndreas Gohr        406 => 'Not Acceptable',
3169d2e1be6SAndreas Gohr        407 => 'Proxy Authentication Required',
3179d2e1be6SAndreas Gohr        408 => 'Request Timeout',
3189d2e1be6SAndreas Gohr        409 => 'Conflict',
3199d2e1be6SAndreas Gohr        410 => 'Gone',
3209d2e1be6SAndreas Gohr        411 => 'Length Required',
3219d2e1be6SAndreas Gohr        412 => 'Precondition Failed',
3229d2e1be6SAndreas Gohr        413 => 'Request Entity Too Large',
3239d2e1be6SAndreas Gohr        414 => 'Request-URI Too Long',
3249d2e1be6SAndreas Gohr        415 => 'Unsupported Media Type',
3259d2e1be6SAndreas Gohr        416 => 'Requested Range Not Satisfiable',
3269d2e1be6SAndreas Gohr        417 => 'Expectation Failed',
3279d2e1be6SAndreas Gohr        500 => 'Internal Server Error',
3289d2e1be6SAndreas Gohr        501 => 'Not Implemented',
3299d2e1be6SAndreas Gohr        502 => 'Bad Gateway',
3309d2e1be6SAndreas Gohr        503 => 'Service Unavailable',
3319d2e1be6SAndreas Gohr        504 => 'Gateway Timeout',
3329d2e1be6SAndreas Gohr        505 => 'HTTP Version Not Supported'
333*24870174SAndreas Gohr    ];
3349d2e1be6SAndreas Gohr
3359d2e1be6SAndreas Gohr    if ($text == '' && isset($stati[$code])) {
3369d2e1be6SAndreas Gohr        $text = $stati[$code];
3379d2e1be6SAndreas Gohr    }
3389d2e1be6SAndreas Gohr
3392b9be456SAndreas Gohr    $server_protocol = $INPUT->server->str('SERVER_PROTOCOL', false);
3409d2e1be6SAndreas Gohr
341*24870174SAndreas Gohr    if (substr(PHP_SAPI, 0, 3) == 'cgi' || defined('SIMPLE_TEST')) {
3429d2e1be6SAndreas Gohr        header("Status: {$code} {$text}", true);
343*24870174SAndreas Gohr    } elseif ($server_protocol == 'HTTP/1.1' || $server_protocol == 'HTTP/1.0') {
3449d2e1be6SAndreas Gohr        header($server_protocol . " {$code} {$text}", true, $code);
3459d2e1be6SAndreas Gohr    } else {
3469d2e1be6SAndreas Gohr        header("HTTP/1.1 {$code} {$text}", true, $code);
3479d2e1be6SAndreas Gohr    }
3489d2e1be6SAndreas Gohr}
349