summaryrefslogtreecommitdiff
path: root/inc/httputils.php
blob: 0ad97a9a18169261b4dc745c2f9768308837505a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<?php
/**
 * Utilities for handling HTTP related tasks
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Andreas Gohr <andi@splitbrain.org>
 */

define('HTTP_MULTIPART_BOUNDARY','D0KuW1K1B0uNDARY');
define('HTTP_HEADER_LF',"\r\n");
define('HTTP_CHUNK_SIZE',16*1024);

/**
 * Checks and sets HTTP headers for conditional HTTP requests
 *
 * @author   Simon Willison <swillison@gmail.com>
 * @link     http://simonwillison.net/2003/Apr/23/conditionalGet/
 * @param    timestamp $timestamp lastmodified time of the cache file
 * @returns  void or exits with previously header() commands executed
 */
function http_conditionalRequest($timestamp){
    // A PHP implementation of conditional get, see
    //   http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/
    $last_modified = substr(gmdate('r', $timestamp), 0, -5).'GMT';
    $etag = '"'.md5($last_modified).'"';
    // Send the headers
    header("Last-Modified: $last_modified");
    header("ETag: $etag");
    // See if the client has provided the required headers
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
        $if_modified_since = stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']);
    }else{
        $if_modified_since = false;
    }

    if (isset($_SERVER['HTTP_IF_NONE_MATCH'])){
        $if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
    }else{
        $if_none_match = false;
    }

    if (!$if_modified_since && !$if_none_match){
        return;
    }

    // At least one of the headers is there - check them
    if ($if_none_match && $if_none_match != $etag) {
        return; // etag is there but doesn't match
    }

    if ($if_modified_since && $if_modified_since != $last_modified) {
        return; // if-modified-since is there but doesn't match
    }

    // Nothing has changed since their last request - serve a 304 and exit
    header('HTTP/1.0 304 Not Modified');

    // don't produce output, even if compression is on
    @ob_end_clean();
    exit;
}

/**
 * Let the webserver send the given file vi x-sendfile method
 *
 * @author Chris Smith <chris.eureka@jalakai.co.uk>
 * @returns  void or exits with previously header() commands executed
 */
function http_sendfile($file) {
    global $conf;

    //use x-sendfile header to pass the delivery to compatible webservers
    if($conf['xsendfile'] == 1){
        header("X-LIGHTTPD-send-file: $file");
        ob_end_clean();
        exit;
    }elseif($conf['xsendfile'] == 2){
        header("X-Sendfile: $file");
        ob_end_clean();
        exit;
    }elseif($conf['xsendfile'] == 3){
        header("X-Accel-Redirect: $file");
        ob_end_clean();
        exit;
    }

    return false;
}

/**
 * Send file contents supporting rangeRequests
 *
 * This function exits the running script
 *
 * @param ressource $fh - file handle for an already open file
 * @param int $size     - size of the whole file
 * @param int $mime     - MIME type of the file
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function http_rangeRequest($fh,$size,$mime){
    $ranges  = array();
    $isrange = false;

    header('Accept-Ranges: bytes');

    if(!isset($_SERVER['HTTP_RANGE'])){
        // no range requested - send the whole file
        $ranges[] = array(0,$size,$size);
    }else{
        $t = explode('=', $_SERVER['HTTP_RANGE']);
        if (!$t[0]=='bytes') {
            // we only understand byte ranges - send the whole file
            $ranges[] = array(0,$size,$size);
        }else{
            $isrange = true;
            // handle multiple ranges
            $r = explode(',',$t[1]);
            foreach($r as $x){
                $p = explode('-', $x);
                $start = (int)$p[0];
                $end   = (int)$p[1];
                if (!$end) $end = $size - 1;
                if ($start > $end || $start > $size || $end > $size){
                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
                    print 'Bad Range Request!';
                    exit;
                }
                $len = $end - $start + 1;
                $ranges[] = array($start,$end,$len);
            }
        }
    }
    $parts = count($ranges);

    // now send the type and length headers
    if(!$isrange){
        header("Content-Type: $mime",true);
    }else{
        header('HTTP/1.1 206 Partial Content');
        if($parts == 1){
            header("Content-Type: $mime",true);
        }else{
            header('Content-Type: multipart/byteranges; boundary='.HTTP_MULTIPART_BOUNDARY,true);
        }
    }

    // send all ranges
    for($i=0; $i<$parts; $i++){
        list($start,$end,$len) = $ranges[$i];

        // multipart or normal headers
        if($parts > 1){
            echo HTTP_HEADER_LF.'--'.HTTP_MULTIPART_BOUNDARY.HTTP_HEADER_LF;
            echo "Content-Type: $mime".HTTP_HEADER_LF;
            echo "Content-Range: bytes $start-$end/$size".HTTP_HEADER_LF;
            echo HTTP_HEADER_LF;
        }else{
            header("Content-Length: $len");
            if($isrange){
                header("Content-Range: bytes $start-$end/$size");
            }
        }

        // send file content
        fseek($fh,$start); //seek to start of range
        $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
        while (!feof($fh) && $chunk > 0) {
            @set_time_limit(30); // large files can take a lot of time
            print fread($fh, $chunk);
            flush();
            $len -= $chunk;
            $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len;
        }
    }
    if($parts > 1){
        echo HTTP_HEADER_LF.'--'.HTTP_MULTIPART_BOUNDARY.'--'.HTTP_HEADER_LF;
    }

    // everything should be done here, exit
    exit;
}

/**
 * Check for a gzipped version and create if necessary
 *
 * return true if there exists a gzip version of the uncompressed file
 * (samepath/samefilename.sameext.gz) created after the uncompressed file
 *
 * @author Chris Smith <chris.eureka@jalakai.co.uk>
 */
function http_gzip_valid($uncompressed_file) {
    $gzip = $uncompressed_file.'.gz';
    if (filemtime($gzip) < filemtime($uncompressed_file)) {    // filemtime returns false (0) if file doesn't exist
        return copy($uncompressed_file, 'compress.zlib://'.$gzip);
    }

    return true;
}

/**
 * Set HTTP headers and echo cachefile, if useable
 *
 * This function handles output of cacheable resource files. It ses the needed
 * HTTP headers. If a useable cache is present, it is passed to the web server
 * and the scrpt is terminated.
 */
function http_cached($cache, $cache_ok) {
    global $conf;

    // check cache age & handle conditional request
    // since the resource files are timestamped, we can use a long max age: 1 year
    header('Cache-Control: public, max-age=31536000');
    header('Pragma: public');
    if($cache_ok){
        http_conditionalRequest(filemtime($cache));
        if($conf['allowdebug']) header("X-CacheUsed: $cache");

        // finally send output
        if ($conf['gzip_output'] && http_gzip_valid($cache)) {
            header('Vary: Accept-Encoding');
            header('Content-Encoding: gzip');
            readfile($cache.".gz");
        } else {
            if (!http_sendfile($cache)) readfile($cache);
        }
        exit;
    }

    http_conditionalRequest(time());
}

/**
 * Cache content and print it
 */
function http_cached_finish($file, $content) {
    global $conf;

    // save cache file
    io_saveFile($file, $content);
    if(function_exists('gzopen')) io_saveFile("$file.gz",$content);

    // finally send output
    if ($conf['gzip_output']) {
        header('Vary: Accept-Encoding');
        header('Content-Encoding: gzip');
        print gzencode($content,9,FORCE_GZIP);
    } else {
        print $content;
    }
}