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