3 * Utilities for handling HTTP related tasks
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
9 define('HTTP_MULTIPART_BOUNDARY', 'D0KuW1K1B0uNDARY');
10 define('HTTP_HEADER_LF', "\r\n");
11 define('HTTP_CHUNK_SIZE', 16 * 1024);
14 * Checks and sets HTTP headers for conditional HTTP requests
16 * @param int $timestamp lastmodified time of the cache file
17 * @returns void or exits with previously header() commands executed
18 * @link http://simonwillison.net/2003/Apr/23/conditionalGet/
20 * @author Simon Willison <swillison@gmail.com>
22 function http_conditionalRequest($timestamp)
26 // A PHP implementation of conditional get, see
27 // http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/
28 $last_modified = substr(gmdate('r', $timestamp), 0, -5) . 'GMT';
29 $etag = '"' . md5($last_modified) . '"';
31 header("Last-Modified: $last_modified");
32 header("ETag: $etag");
33 // See if the client has provided the required headers
34 $if_modified_since = $INPUT->server
->filter('stripslashes')->str('HTTP_IF_MODIFIED_SINCE', false);
35 $if_none_match = $INPUT->server
->filter('stripslashes')->str('HTTP_IF_NONE_MATCH', false);
37 if (!$if_modified_since && !$if_none_match) {
41 // At least one of the headers is there - check them
42 if ($if_none_match && $if_none_match != $etag) {
43 return; // etag is there but doesn't match
46 if ($if_modified_since && $if_modified_since != $last_modified) {
47 return; // if-modified-since is there but doesn't match
50 // Nothing has changed since their last request - serve a 304 and exit
51 header('HTTP/1.0 304 Not Modified');
53 // don't produce output, even if compression is on
59 * Let the webserver send the given file via x-sendfile method
61 * @param string $file absolute path of file to send
62 * @returns void or exits with previous header() commands executed
63 * @author Chris Smith <chris@jalakai.co.uk>
66 function http_sendfile($file)
70 //use x-sendfile header to pass the delivery to compatible web servers
71 if ($conf['xsendfile'] == 1) {
72 header("X-LIGHTTPD-send-file: $file");
75 } elseif ($conf['xsendfile'] == 2) {
76 header("X-Sendfile: $file");
79 } elseif ($conf['xsendfile'] == 3) {
80 // FS#2388 nginx just needs the relative path.
81 $file = DOKU_REL
. substr($file, strlen(fullpath(DOKU_INC
)) +
1);
82 header("X-Accel-Redirect: $file");
89 * Send file contents supporting rangeRequests
91 * This function exits the running script
93 * @param resource $fh - file handle for an already open file
94 * @param int $size - size of the whole file
95 * @param int $mime - MIME type of the file
97 * @author Andreas Gohr <andi@splitbrain.org>
99 function http_rangeRequest($fh, $size, $mime)
106 header('Accept-Ranges: bytes');
108 if (!$INPUT->server
->has('HTTP_RANGE')) {
109 // no range requested - send the whole file
110 $ranges[] = [0, $size, $size];
112 $t = explode('=', $INPUT->server
->str('HTTP_RANGE'));
113 if (!$t[0] == 'bytes') {
114 // we only understand byte ranges - send the whole file
115 $ranges[] = [0, $size, $size];
118 // handle multiple ranges
119 $r = explode(',', $t[1]);
121 $p = explode('-', $x);
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 echo 'Bad Range Request!';
130 $len = $end - $start +
1;
131 $ranges[] = [$start, $end, $len];
135 $parts = count($ranges);
137 // now send the type and length headers
139 header("Content-Type: $mime", true);
141 header('HTTP/1.1 206 Partial Content');
143 header("Content-Type: $mime", true);
145 header('Content-Type: multipart/byteranges; boundary=' . HTTP_MULTIPART_BOUNDARY
, true);
150 for ($i = 0; $i < $parts; $i++
) {
151 [$start, $end, $len] = $ranges[$i];
153 // multipart or normal headers
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
;
160 header("Content-Length: $len");
162 header("Content-Range: bytes $start-$end/$size");
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 echo fread($fh, $chunk);
174 $chunk = ($len > HTTP_CHUNK_SIZE
) ? HTTP_CHUNK_SIZE
: $len;
178 echo HTTP_HEADER_LF
. '--' . HTTP_MULTIPART_BOUNDARY
. '--' . HTTP_HEADER_LF
;
181 // everything should be done here, exit (or return if testing)
182 if (defined('SIMPLE_TEST')) return;
187 * Check for a gzipped version and create if necessary
189 * return true if there exists a gzip version of the uncompressed file
190 * (samepath/samefilename.sameext.gz) created after the uncompressed file
192 * @param string $uncompressed_file
194 * @author Chris Smith <chris.eureka@jalakai.co.uk>
197 function http_gzip_valid($uncompressed_file)
199 if (!DOKU_HAS_GZIP
) return false;
201 $gzip = $uncompressed_file . '.gz';
202 if (filemtime($gzip) < filemtime($uncompressed_file)) { // filemtime returns false (0) if file doesn't exist
203 return copy($uncompressed_file, 'compress.zlib://' . $gzip);
210 * Set HTTP headers and echo cachefile, if useable
212 * This function handles output of cacheable resource files. It ses the needed
213 * HTTP headers. If a useable cache is present, it is passed to the web server
214 * and the script is terminated.
216 * @param string $cache cache file name
217 * @param bool $cache_ok if cache can be used
219 function http_cached($cache, $cache_ok)
223 // check cache age & handle conditional request
224 // since the resource files are timestamped, we can use a long max age: 1 year
225 header('Cache-Control: public, max-age=31536000');
226 header('Pragma: public');
228 http_conditionalRequest(filemtime($cache));
229 if ($conf['allowdebug']) header("X-CacheUsed: $cache");
231 // finally send output
232 if ($conf['gzip_output'] && http_gzip_valid($cache)) {
233 header('Vary: Accept-Encoding');
234 header('Content-Encoding: gzip');
235 readfile($cache . ".gz");
237 http_sendfile($cache);
243 http_conditionalRequest(time());
247 * Cache content and print it
249 * @param string $file file name
250 * @param string $content
252 function http_cached_finish($file, $content)
257 io_saveFile($file, $content);
258 if (DOKU_HAS_GZIP
) io_saveFile("$file.gz", $content);
260 // finally send output
261 if ($conf['gzip_output'] && DOKU_HAS_GZIP
) {
262 header('Vary: Accept-Encoding');
263 header('Content-Encoding: gzip');
264 echo gzencode($content, 9, FORCE_GZIP
);
271 * Fetches raw, unparsed POST data
275 function http_get_raw_post_data()
277 static $postData = null;
278 if ($postData === null) {
279 $postData = file_get_contents('php://input');
285 * Set the HTTP response status and takes care of the used PHP SAPI
287 * Inspired by CodeIgniter's set_status_header function
290 * @param string $text
292 function http_status($code = 200, $text = '')
300 203 => 'Non-Authoritative Information',
302 205 => 'Reset Content',
303 206 => 'Partial Content',
304 300 => 'Multiple Choices',
305 301 => 'Moved Permanently',
307 304 => 'Not Modified',
309 307 => 'Temporary Redirect',
310 400 => 'Bad Request',
311 401 => 'Unauthorized',
314 405 => 'Method Not Allowed',
315 406 => 'Not Acceptable',
316 407 => 'Proxy Authentication Required',
317 408 => 'Request Timeout',
320 411 => 'Length Required',
321 412 => 'Precondition Failed',
322 413 => 'Request Entity Too Large',
323 414 => 'Request-URI Too Long',
324 415 => 'Unsupported Media Type',
325 416 => 'Requested Range Not Satisfiable',
326 417 => 'Expectation Failed',
327 500 => 'Internal Server Error',
328 501 => 'Not Implemented',
329 502 => 'Bad Gateway',
330 503 => 'Service Unavailable',
331 504 => 'Gateway Timeout',
332 505 => 'HTTP Version Not Supported'
335 if ($text == '' && isset($stati[$code])) {
336 $text = $stati[$code];
339 $server_protocol = $INPUT->server
->str('SERVER_PROTOCOL', false);
341 if (substr(PHP_SAPI
, 0, 3) == 'cgi' ||
defined('SIMPLE_TEST')) {
342 header("Status: {$code} {$text}", true);
343 } elseif ($server_protocol == 'HTTP/1.1' ||
$server_protocol == 'HTTP/1.0') {
344 header($server_protocol . " {$code} {$text}", true, $code);
346 header("HTTP/1.1 {$code} {$text}", true, $code);