xref: /dokuwiki/inc/httputils.php (revision 96946cc94d3ecb3832e2a1ce35c49743e25329e1)
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 *
16758447cfSAndreas Gohr * @author   Simon Willison <swillison@gmail.com>
1723a96c41SElan Ruusamäe * @link     http://simonwillison.net/2003/Apr/23/conditionalGet/
18758447cfSAndreas Gohr * @param    timestamp $timestamp lastmodified time of the cache file
19758447cfSAndreas Gohr * @returns  void or exits with previously header() commands executed
20758447cfSAndreas Gohr */
21758447cfSAndreas Gohrfunction http_conditionalRequest($timestamp){
22758447cfSAndreas Gohr    // A PHP implementation of conditional get, see
2323a96c41SElan Ruusamäe    //   http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/
24758447cfSAndreas Gohr    $last_modified = substr(gmdate('r', $timestamp), 0, -5).'GMT';
25758447cfSAndreas Gohr    $etag = '"'.md5($last_modified).'"';
26758447cfSAndreas Gohr    // Send the headers
27758447cfSAndreas Gohr    header("Last-Modified: $last_modified");
28758447cfSAndreas Gohr    header("ETag: $etag");
29758447cfSAndreas Gohr    // See if the client has provided the required headers
30758447cfSAndreas Gohr    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
31758447cfSAndreas Gohr        $if_modified_since = stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']);
32758447cfSAndreas Gohr    }else{
33758447cfSAndreas Gohr        $if_modified_since = false;
34758447cfSAndreas Gohr    }
35758447cfSAndreas Gohr
36758447cfSAndreas Gohr    if (isset($_SERVER['HTTP_IF_NONE_MATCH'])){
37758447cfSAndreas Gohr        $if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
38758447cfSAndreas Gohr    }else{
39758447cfSAndreas Gohr        $if_none_match = false;
40758447cfSAndreas Gohr    }
41758447cfSAndreas Gohr
42758447cfSAndreas Gohr    if (!$if_modified_since && !$if_none_match){
43758447cfSAndreas Gohr        return;
44758447cfSAndreas Gohr    }
45758447cfSAndreas Gohr
46758447cfSAndreas Gohr    // At least one of the headers is there - check them
47758447cfSAndreas Gohr    if ($if_none_match && $if_none_match != $etag) {
48758447cfSAndreas Gohr        return; // etag is there but doesn't match
49758447cfSAndreas Gohr    }
50758447cfSAndreas Gohr
51758447cfSAndreas Gohr    if ($if_modified_since && $if_modified_since != $last_modified) {
52758447cfSAndreas Gohr        return; // if-modified-since is there but doesn't match
53758447cfSAndreas Gohr    }
54758447cfSAndreas Gohr
55758447cfSAndreas Gohr    // Nothing has changed since their last request - serve a 304 and exit
56758447cfSAndreas Gohr    header('HTTP/1.0 304 Not Modified');
57758447cfSAndreas Gohr
58758447cfSAndreas Gohr    // don't produce output, even if compression is on
59c66972f2SAdrian Lang    @ob_end_clean();
60758447cfSAndreas Gohr    exit;
61758447cfSAndreas Gohr}
62758447cfSAndreas Gohr
63758447cfSAndreas Gohr/**
64758447cfSAndreas Gohr * Let the webserver send the given file vi x-sendfile method
65758447cfSAndreas Gohr *
66758447cfSAndreas Gohr * @author Chris Smith <chris.eureka@jalakai.co.uk>
67758447cfSAndreas Gohr * @returns  void or exits with previously header() commands executed
68758447cfSAndreas Gohr */
69758447cfSAndreas Gohrfunction http_sendfile($file) {
70758447cfSAndreas Gohr    global $conf;
71758447cfSAndreas Gohr
72758447cfSAndreas Gohr    //use x-sendfile header to pass the delivery to compatible webservers
73758447cfSAndreas Gohr    if($conf['xsendfile'] == 1){
74758447cfSAndreas Gohr        header("X-LIGHTTPD-send-file: $file");
75758447cfSAndreas Gohr        ob_end_clean();
76758447cfSAndreas Gohr        exit;
77758447cfSAndreas Gohr    }elseif($conf['xsendfile'] == 2){
78758447cfSAndreas Gohr        header("X-Sendfile: $file");
79758447cfSAndreas Gohr        ob_end_clean();
80758447cfSAndreas Gohr        exit;
81758447cfSAndreas Gohr    }elseif($conf['xsendfile'] == 3){
82758447cfSAndreas Gohr        header("X-Accel-Redirect: $file");
83758447cfSAndreas Gohr        ob_end_clean();
84758447cfSAndreas Gohr        exit;
85758447cfSAndreas Gohr    }
86758447cfSAndreas Gohr
87758447cfSAndreas Gohr    return false;
88758447cfSAndreas Gohr}
89758447cfSAndreas Gohr
90758447cfSAndreas Gohr/**
91758447cfSAndreas Gohr * Send file contents supporting rangeRequests
92758447cfSAndreas Gohr *
93758447cfSAndreas Gohr * This function exits the running script
94758447cfSAndreas Gohr *
95758447cfSAndreas Gohr * @param ressource $fh - file handle for an already open file
96758447cfSAndreas Gohr * @param int $size     - size of the whole file
97758447cfSAndreas Gohr * @param int $mime     - MIME type of the file
98758447cfSAndreas Gohr *
99758447cfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
100758447cfSAndreas Gohr */
101758447cfSAndreas Gohrfunction http_rangeRequest($fh,$size,$mime){
102758447cfSAndreas Gohr    $ranges  = array();
103758447cfSAndreas Gohr    $isrange = false;
104758447cfSAndreas Gohr
105758447cfSAndreas Gohr    header('Accept-Ranges: bytes');
106758447cfSAndreas Gohr
107758447cfSAndreas Gohr    if(!isset($_SERVER['HTTP_RANGE'])){
108758447cfSAndreas Gohr        // no range requested - send the whole file
109758447cfSAndreas Gohr        $ranges[] = array(0,$size,$size);
110758447cfSAndreas Gohr    }else{
111758447cfSAndreas Gohr        $t = explode('=', $_SERVER['HTTP_RANGE']);
112758447cfSAndreas Gohr        if (!$t[0]=='bytes') {
113758447cfSAndreas Gohr            // we only understand byte ranges - send the whole file
114758447cfSAndreas Gohr            $ranges[] = array(0,$size,$size);
115758447cfSAndreas Gohr        }else{
116758447cfSAndreas Gohr            $isrange = true;
117758447cfSAndreas Gohr            // handle multiple ranges
118758447cfSAndreas Gohr            $r = explode(',',$t[1]);
119758447cfSAndreas Gohr            foreach($r as $x){
120758447cfSAndreas Gohr                $p = explode('-', $x);
121758447cfSAndreas Gohr                $start = (int)$p[0];
122758447cfSAndreas Gohr                $end   = (int)$p[1];
123758447cfSAndreas Gohr                if (!$end) $end = $size - 1;
124758447cfSAndreas Gohr                if ($start > $end || $start > $size || $end > $size){
125758447cfSAndreas Gohr                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
126758447cfSAndreas Gohr                    print 'Bad Range Request!';
127758447cfSAndreas Gohr                    exit;
128758447cfSAndreas Gohr                }
129758447cfSAndreas Gohr                $len = $end - $start + 1;
130758447cfSAndreas Gohr                $ranges[] = array($start,$end,$len);
131758447cfSAndreas Gohr            }
132758447cfSAndreas Gohr        }
133758447cfSAndreas Gohr    }
134758447cfSAndreas Gohr    $parts = count($ranges);
135758447cfSAndreas Gohr
136758447cfSAndreas Gohr    // now send the type and length headers
137758447cfSAndreas Gohr    if(!$isrange){
138758447cfSAndreas Gohr        header("Content-Type: $mime",true);
139758447cfSAndreas Gohr    }else{
140758447cfSAndreas Gohr        header('HTTP/1.1 206 Partial Content');
141758447cfSAndreas Gohr        if($parts == 1){
142758447cfSAndreas Gohr            header("Content-Type: $mime",true);
143758447cfSAndreas Gohr        }else{
144758447cfSAndreas Gohr            header('Content-Type: multipart/byteranges; boundary='.HTTP_MULTIPART_BOUNDARY,true);
145758447cfSAndreas Gohr        }
146758447cfSAndreas Gohr    }
147758447cfSAndreas Gohr
148758447cfSAndreas Gohr    // send all ranges
149758447cfSAndreas Gohr    for($i=0; $i<$parts; $i++){
150758447cfSAndreas Gohr        list($start,$end,$len) = $ranges[$i];
151758447cfSAndreas Gohr
152758447cfSAndreas Gohr        // multipart or normal headers
153758447cfSAndreas Gohr        if($parts > 1){
154758447cfSAndreas Gohr            echo HTTP_HEADER_LF.'--'.HTTP_MULTIPART_BOUNDARY.HTTP_HEADER_LF;
155758447cfSAndreas Gohr            echo "Content-Type: $mime".HTTP_HEADER_LF;
156758447cfSAndreas Gohr            echo "Content-Range: bytes $start-$end/$size".HTTP_HEADER_LF;
157b8b5563eSAndreas Gohr            echo HTTP_HEADER_LF;
158758447cfSAndreas Gohr        }else{
159758447cfSAndreas Gohr            header("Content-Length: $len");
160758447cfSAndreas Gohr            if($isrange){
161758447cfSAndreas Gohr                header("Content-Range: bytes $start-$end/$size");
162758447cfSAndreas Gohr            }
163758447cfSAndreas Gohr        }
164758447cfSAndreas Gohr
165758447cfSAndreas Gohr        // send file content
166758447cfSAndreas Gohr        fseek($fh,$start); //seek to start of range
167758447cfSAndreas Gohr        $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
168758447cfSAndreas Gohr        while (!feof($fh) && $chunk > 0) {
169758447cfSAndreas Gohr            @set_time_limit(30); // large files can take a lot of time
170758447cfSAndreas Gohr            print fread($fh, $chunk);
171758447cfSAndreas Gohr            flush();
172758447cfSAndreas Gohr            $len -= $chunk;
173758447cfSAndreas Gohr            $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
174758447cfSAndreas Gohr        }
175758447cfSAndreas Gohr    }
176758447cfSAndreas Gohr    if($parts > 1){
177758447cfSAndreas Gohr        echo HTTP_HEADER_LF.'--'.HTTP_MULTIPART_BOUNDARY.'--'.HTTP_HEADER_LF;
178758447cfSAndreas Gohr    }
179758447cfSAndreas Gohr
180758447cfSAndreas Gohr    // everything should be done here, exit
181758447cfSAndreas Gohr    exit;
182758447cfSAndreas Gohr}
183758447cfSAndreas Gohr
184758447cfSAndreas Gohr/**
185758447cfSAndreas Gohr * Check for a gzipped version and create if necessary
186758447cfSAndreas Gohr *
187758447cfSAndreas Gohr * return true if there exists a gzip version of the uncompressed file
188758447cfSAndreas Gohr * (samepath/samefilename.sameext.gz) created after the uncompressed file
189758447cfSAndreas Gohr *
190758447cfSAndreas Gohr * @author Chris Smith <chris.eureka@jalakai.co.uk>
191758447cfSAndreas Gohr */
192758447cfSAndreas Gohrfunction http_gzip_valid($uncompressed_file) {
193758447cfSAndreas Gohr    $gzip = $uncompressed_file.'.gz';
194758447cfSAndreas Gohr    if (filemtime($gzip) < filemtime($uncompressed_file)) {    // filemtime returns false (0) if file doesn't exist
195758447cfSAndreas Gohr        return copy($uncompressed_file, 'compress.zlib://'.$gzip);
196758447cfSAndreas Gohr    }
197758447cfSAndreas Gohr
198758447cfSAndreas Gohr    return true;
199758447cfSAndreas Gohr}
2006619f42eSAdrian Lang
2016619f42eSAdrian Lang/**
2026619f42eSAdrian Lang * Set HTTP headers and echo cachefile, if useable
2036619f42eSAdrian Lang *
2046619f42eSAdrian Lang * This function handles output of cacheable resource files. It ses the needed
2056619f42eSAdrian Lang * HTTP headers. If a useable cache is present, it is passed to the web server
2066619f42eSAdrian Lang * and the scrpt is terminated.
2076619f42eSAdrian Lang */
2086619f42eSAdrian Langfunction http_cached($cache, $cache_ok) {
2096619f42eSAdrian Lang    global $conf;
2106619f42eSAdrian Lang
2116619f42eSAdrian Lang    // check cache age & handle conditional request
2126619f42eSAdrian Lang    // since the resource files are timestamped, we can use a long max age: 1 year
2136619f42eSAdrian Lang    header('Cache-Control: public, max-age=31536000');
2146619f42eSAdrian Lang    header('Pragma: public');
2156619f42eSAdrian Lang    if($cache_ok){
2166619f42eSAdrian Lang        http_conditionalRequest(filemtime($cache));
2176619f42eSAdrian Lang        if($conf['allowdebug']) header("X-CacheUsed: $cache");
2186619f42eSAdrian Lang
2196619f42eSAdrian Lang        // finally send output
2206619f42eSAdrian Lang        if ($conf['gzip_output'] && http_gzip_valid($cache)) {
2216619f42eSAdrian Lang            header('Vary: Accept-Encoding');
2226619f42eSAdrian Lang            header('Content-Encoding: gzip');
2236619f42eSAdrian Lang            readfile($cache.".gz");
2246619f42eSAdrian Lang        } else {
2256619f42eSAdrian Lang            if (!http_sendfile($cache)) readfile($cache);
2266619f42eSAdrian Lang        }
2276619f42eSAdrian Lang        exit;
2286619f42eSAdrian Lang    }
2296619f42eSAdrian Lang
2306619f42eSAdrian Lang    http_conditionalRequest(time());
2316619f42eSAdrian Lang}
2326619f42eSAdrian Lang
2336619f42eSAdrian Lang/**
2346619f42eSAdrian Lang * Cache content and print it
2356619f42eSAdrian Lang */
2366619f42eSAdrian Langfunction http_cached_finish($file, $content) {
2376619f42eSAdrian Lang    global $conf;
2386619f42eSAdrian Lang
2396619f42eSAdrian Lang    // save cache file
2406619f42eSAdrian Lang    io_saveFile($file, $content);
2416619f42eSAdrian Lang    if(function_exists('gzopen')) io_saveFile("$file.gz",$content);
2426619f42eSAdrian Lang
2436619f42eSAdrian Lang    // finally send output
2446619f42eSAdrian Lang    if ($conf['gzip_output']) {
2456619f42eSAdrian Lang        header('Vary: Accept-Encoding');
2466619f42eSAdrian Lang        header('Content-Encoding: gzip');
2476619f42eSAdrian Lang        print gzencode($content,9,FORCE_GZIP);
2486619f42eSAdrian Lang    } else {
2496619f42eSAdrian Lang        print $content;
2506619f42eSAdrian Lang    }
2516619f42eSAdrian Lang}
252*96946cc9SDominik Eckelmann
253*96946cc9SDominik Eckelmannfunction http_get_raw_post_data() {
254*96946cc9SDominik Eckelmann    static $postData = null;
255*96946cc9SDominik Eckelmann    if ($postData === null) {
256*96946cc9SDominik Eckelmann        $postData = file_get_contents('php://input');
257*96946cc9SDominik Eckelmann    }
258*96946cc9SDominik Eckelmann    return $postData;
259*96946cc9SDominik Eckelmann}
260