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