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    // A PHP implementation of conditional get, see
24    //   http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/
25    $last_modified = substr(gmdate('r', $timestamp), 0, -5).'GMT';
26    $etag = '"'.md5($last_modified).'"';
27    // Send the headers
28    header("Last-Modified: $last_modified");
29    header("ETag: $etag");
30    // See if the client has provided the required headers
31    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
32        $if_modified_since = stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']);
33    }else{
34        $if_modified_since = false;
35    }
36
37    if (isset($_SERVER['HTTP_IF_NONE_MATCH'])){
38        $if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
39    }else{
40        $if_none_match = false;
41    }
42
43    if (!$if_modified_since && !$if_none_match){
44        return;
45    }
46
47    // At least one of the headers is there - check them
48    if ($if_none_match && $if_none_match != $etag) {
49        return; // etag is there but doesn't match
50    }
51
52    if ($if_modified_since && $if_modified_since != $last_modified) {
53        return; // if-modified-since is there but doesn't match
54    }
55
56    // Nothing has changed since their last request - serve a 304 and exit
57    header('HTTP/1.0 304 Not Modified');
58
59    // don't produce output, even if compression is on
60    @ob_end_clean();
61    exit;
62}
63
64/**
65 * Let the webserver send the given file via x-sendfile method
66 *
67 * @author Chris Smith <chris@jalakai.co.uk>
68 *
69 * @param string $file absolute path of file to send
70 * @returns  void or exits with previous header() commands executed
71 */
72function http_sendfile($file) {
73    global $conf;
74
75    //use x-sendfile header to pass the delivery to compatible web servers
76    if($conf['xsendfile'] == 1){
77        header("X-LIGHTTPD-send-file: $file");
78        ob_end_clean();
79        exit;
80    }elseif($conf['xsendfile'] == 2){
81        header("X-Sendfile: $file");
82        ob_end_clean();
83        exit;
84    }elseif($conf['xsendfile'] == 3){
85        header("X-Accel-Redirect: $file");
86        ob_end_clean();
87        exit;
88    }
89}
90
91/**
92 * Send file contents supporting rangeRequests
93 *
94 * This function exits the running script
95 *
96 * @param resource $fh - file handle for an already open file
97 * @param int $size     - size of the whole file
98 * @param int $mime     - MIME type of the file
99 *
100 * @author Andreas Gohr <andi@splitbrain.org>
101 */
102function http_rangeRequest($fh,$size,$mime){
103    $ranges  = array();
104    $isrange = false;
105
106    header('Accept-Ranges: bytes');
107
108    if(!isset($_SERVER['HTTP_RANGE'])){
109        // no range requested - send the whole file
110        $ranges[] = array(0,$size,$size);
111    }else{
112        $t = explode('=', $_SERVER['HTTP_RANGE']);
113        if (!$t[0]=='bytes') {
114            // we only understand byte ranges - send the whole file
115            $ranges[] = array(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[] = array($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        list($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 * @author Chris Smith <chris.eureka@jalakai.co.uk>
193 *
194 * @param string $uncompressed_file
195 * @return bool
196 */
197function http_gzip_valid($uncompressed_file) {
198    if(!DOKU_HAS_GZIP) return false;
199
200    $gzip = $uncompressed_file.'.gz';
201    if (filemtime($gzip) < filemtime($uncompressed_file)) {    // filemtime returns false (0) if file doesn't exist
202        return copy($uncompressed_file, 'compress.zlib://'.$gzip);
203    }
204
205    return true;
206}
207
208/**
209 * Set HTTP headers and echo cachefile, if useable
210 *
211 * This function handles output of cacheable resource files. It ses the needed
212 * HTTP headers. If a useable cache is present, it is passed to the web server
213 * and the script is terminated.
214 *
215 * @param string $cache cache file name
216 * @param bool   $cache_ok    if cache can be used
217 */
218function http_cached($cache, $cache_ok) {
219    global $conf;
220
221    // check cache age & handle conditional request
222    // since the resource files are timestamped, we can use a long max age: 1 year
223    header('Cache-Control: public, max-age=31536000');
224    header('Pragma: public');
225    if($cache_ok){
226        http_conditionalRequest(filemtime($cache));
227        if($conf['allowdebug']) header("X-CacheUsed: $cache");
228
229        // finally send output
230        if ($conf['gzip_output'] && http_gzip_valid($cache)) {
231            header('Vary: Accept-Encoding');
232            header('Content-Encoding: gzip');
233            readfile($cache.".gz");
234        } else {
235            http_sendfile($cache);
236            readfile($cache);
237        }
238        exit;
239    }
240
241    http_conditionalRequest(time());
242}
243
244/**
245 * Cache content and print it
246 *
247 * @param string $file file name
248 * @param string $content
249 */
250function http_cached_finish($file, $content) {
251    global $conf;
252
253    // save cache file
254    io_saveFile($file, $content);
255    if(DOKU_HAS_GZIP) io_saveFile("$file.gz",$content);
256
257    // finally send output
258    if ($conf['gzip_output'] && DOKU_HAS_GZIP) {
259        header('Vary: Accept-Encoding');
260        header('Content-Encoding: gzip');
261        print gzencode($content,9,FORCE_GZIP);
262    } else {
263        print $content;
264    }
265}
266
267/**
268 * Fetches raw, unparsed POST data
269 *
270 * @return string
271 */
272function http_get_raw_post_data() {
273    static $postData = null;
274    if ($postData === null) {
275        $postData = file_get_contents('php://input');
276    }
277    return $postData;
278}
279
280/**
281 * Set the HTTP response status and takes care of the used PHP SAPI
282 *
283 * Inspired by CodeIgniter's set_status_header function
284 *
285 * @param int    $code
286 * @param string $text
287 */
288function http_status($code = 200, $text = '') {
289    static $stati = array(
290        200 => 'OK',
291        201 => 'Created',
292        202 => 'Accepted',
293        203 => 'Non-Authoritative Information',
294        204 => 'No Content',
295        205 => 'Reset Content',
296        206 => 'Partial Content',
297
298        300 => 'Multiple Choices',
299        301 => 'Moved Permanently',
300        302 => 'Found',
301        304 => 'Not Modified',
302        305 => 'Use Proxy',
303        307 => 'Temporary Redirect',
304
305        400 => 'Bad Request',
306        401 => 'Unauthorized',
307        403 => 'Forbidden',
308        404 => 'Not Found',
309        405 => 'Method Not Allowed',
310        406 => 'Not Acceptable',
311        407 => 'Proxy Authentication Required',
312        408 => 'Request Timeout',
313        409 => 'Conflict',
314        410 => 'Gone',
315        411 => 'Length Required',
316        412 => 'Precondition Failed',
317        413 => 'Request Entity Too Large',
318        414 => 'Request-URI Too Long',
319        415 => 'Unsupported Media Type',
320        416 => 'Requested Range Not Satisfiable',
321        417 => 'Expectation Failed',
322
323        500 => 'Internal Server Error',
324        501 => 'Not Implemented',
325        502 => 'Bad Gateway',
326        503 => 'Service Unavailable',
327        504 => 'Gateway Timeout',
328        505 => 'HTTP Version Not Supported'
329    );
330
331    if($text == '' && isset($stati[$code])) {
332        $text = $stati[$code];
333    }
334
335    $server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : false;
336
337    if(substr(php_sapi_name(), 0, 3) == 'cgi' || defined('SIMPLE_TEST')) {
338        header("Status: {$code} {$text}", true);
339    } elseif($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0') {
340        header($server_protocol." {$code} {$text}", true, $code);
341    } else {
342        header("HTTP/1.1 {$code} {$text}", true, $code);
343    }
344}
345