4 * Utilities for handling HTTP related tasks
6 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author Andreas Gohr <andi@splitbrain.org>
10 define('HTTP_MULTIPART_BOUNDARY', 'D0KuW1K1B0uNDARY');
11 define('HTTP_HEADER_LF', "\r\n");
12 define('HTTP_CHUNK_SIZE', 16 * 1024);
15 * Checks and sets HTTP headers for conditional HTTP requests
17 * @param int $timestamp lastmodified time of the cache file
18 * @returns void or exits with previously header() commands executed
19 * @link http://simonwillison.net/2003/Apr/23/conditionalGet/
21 * @author Simon Willison <swillison@gmail.com>
23 function http_conditionalRequest($timestamp)
27 // A PHP implementation of conditional get, see
28 // http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/
29 $last_modified = substr(gmdate('r', $timestamp), 0, -5) . 'GMT';
30 $etag = '"' . md5($last_modified) . '"';
32 header("Last-Modified: $last_modified");
33 header("ETag: $etag");
34 // See if the client has provided the required headers
35 $if_modified_since = $INPUT->server
->filter('stripslashes')->str('HTTP_IF_MODIFIED_SINCE', false);
36 $if_none_match = $INPUT->server
->filter('stripslashes')->str('HTTP_IF_NONE_MATCH', false);
38 if (!$if_modified_since && !$if_none_match) {
42 // At least one of the headers is there - check them
43 if ($if_none_match && $if_none_match != $etag) {
44 return; // etag is there but doesn't match
47 if ($if_modified_since && $if_modified_since != $last_modified) {
48 return; // if-modified-since is there but doesn't match
51 // Nothing has changed since their last request - serve a 304 and exit
52 header('HTTP/1.0 304 Not Modified');
54 // don't produce output, even if compression is on
60 * Let the webserver send the given file via x-sendfile method
62 * @param string $file absolute path of file to send
63 * @returns void or exits with previous header() commands executed
64 * @author Chris Smith <chris@jalakai.co.uk>
67 function http_sendfile($file)
71 //use x-sendfile header to pass the delivery to compatible web servers
72 if ($conf['xsendfile'] == 1) {
73 header("X-LIGHTTPD-send-file: $file");
76 } elseif ($conf['xsendfile'] == 2) {
77 header("X-Sendfile: $file");
80 } elseif ($conf['xsendfile'] == 3) {
81 // FS#2388 nginx just needs the relative path.
82 $file = DOKU_REL
. substr($file, strlen(fullpath(DOKU_INC
)) +
1);
83 header("X-Accel-Redirect: $file");
90 * Send file contents supporting rangeRequests
92 * This function exits the running script
94 * @param resource $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
98 * @author Andreas Gohr <andi@splitbrain.org>
100 function http_rangeRequest($fh, $size, $mime)
107 header('Accept-Ranges: bytes');
109 if (!$INPUT->server
->has('HTTP_RANGE')) {
110 // no range requested - send the whole file
111 $ranges[] = [0, $size, $size];
113 $t = explode('=', $INPUT->server
->str('HTTP_RANGE'));
114 if (!$t[0] == 'bytes') {
115 // we only understand byte ranges - send the whole file
116 $ranges[] = [0, $size, $size];
119 // handle multiple ranges
120 $r = explode(',', $t[1]);
122 $p = explode('-', $x);
125 if (!$end) $end = $size - 1;
126 if ($start > $end ||
$start > $size ||
$end > $size) {
127 header('HTTP/1.1 416 Requested Range Not Satisfiable');
128 echo 'Bad Range Request!';
131 $len = $end - $start +
1;
132 $ranges[] = [$start, $end, $len];
136 $parts = count($ranges);
138 // now send the type and length headers
140 header("Content-Type: $mime", true);
142 header('HTTP/1.1 206 Partial Content');
144 header("Content-Type: $mime", true);
146 header('Content-Type: multipart/byteranges; boundary=' . HTTP_MULTIPART_BOUNDARY
, true);
151 for ($i = 0; $i < $parts; $i++
) {
152 [$start, $end, $len] = $ranges[$i];
154 // multipart or normal headers
156 echo HTTP_HEADER_LF
. '--' . HTTP_MULTIPART_BOUNDARY
. HTTP_HEADER_LF
;
157 echo "Content-Type: $mime" . HTTP_HEADER_LF
;
158 echo "Content-Range: bytes $start-$end/$size" . HTTP_HEADER_LF
;
161 header("Content-Length: $len");
163 header("Content-Range: bytes $start-$end/$size");
168 fseek($fh, $start); //seek to start of range
169 $chunk = ($len > HTTP_CHUNK_SIZE
) ? HTTP_CHUNK_SIZE
: $len;
170 while (!feof($fh) && $chunk > 0) {
171 @set_time_limit
(30); // large files can take a lot of time
172 echo fread($fh, $chunk);
175 $chunk = ($len > HTTP_CHUNK_SIZE
) ? HTTP_CHUNK_SIZE
: $len;
179 echo HTTP_HEADER_LF
. '--' . HTTP_MULTIPART_BOUNDARY
. '--' . HTTP_HEADER_LF
;
182 // everything should be done here, exit (or return if testing)
183 if (defined('SIMPLE_TEST')) return;
188 * Check for a gzipped version and create if necessary
190 * return true if there exists a gzip version of the uncompressed file
191 * (samepath/samefilename.sameext.gz) created after the uncompressed file
193 * @param string $uncompressed_file
195 * @author Chris Smith <chris.eureka@jalakai.co.uk>
198 function http_gzip_valid($uncompressed_file)
200 if (!DOKU_HAS_GZIP
) return false;
202 $gzip = $uncompressed_file . '.gz';
203 if (filemtime($gzip) < filemtime($uncompressed_file)) { // filemtime returns false (0) if file doesn't exist
204 return copy($uncompressed_file, 'compress.zlib://' . $gzip);
211 * Set HTTP headers and echo cachefile, if useable
213 * This function handles output of cacheable resource files. It ses the needed
214 * HTTP headers. If a useable cache is present, it is passed to the web server
215 * and the script is terminated.
217 * @param string $cache cache file name
218 * @param bool $cache_ok if cache can be used
220 function http_cached($cache, $cache_ok)
224 // check cache age & handle conditional request
225 // since the resource files are timestamped, we can use a long max age: 1 year
226 header('Cache-Control: public, max-age=31536000');
227 header('Pragma: public');
229 http_conditionalRequest(filemtime($cache));
230 if ($conf['allowdebug']) header("X-CacheUsed: $cache");
232 // finally send output
233 if ($conf['gzip_output'] && http_gzip_valid($cache)) {
234 header('Vary: Accept-Encoding');
235 header('Content-Encoding: gzip');
236 readfile($cache . ".gz");
238 http_sendfile($cache);
244 http_conditionalRequest(time());
248 * Cache content and print it
250 * @param string $file file name
251 * @param string $content
253 function http_cached_finish($file, $content)
258 io_saveFile($file, $content);
259 if (DOKU_HAS_GZIP
) io_saveFile("$file.gz", $content);
261 // finally send output
262 if ($conf['gzip_output'] && DOKU_HAS_GZIP
) {
263 header('Vary: Accept-Encoding');
264 header('Content-Encoding: gzip');
265 echo gzencode($content, 9, FORCE_GZIP
);
272 * Fetches raw, unparsed POST data
276 function http_get_raw_post_data()
278 static $postData = null;
279 if ($postData === null) {
280 $postData = file_get_contents('php://input');
286 * Set the HTTP response status and takes care of the used PHP SAPI
288 * Inspired by CodeIgniter's set_status_header function
291 * @param string $text
293 function http_status($code = 200, $text = '')
301 203 => 'Non-Authoritative Information',
303 205 => 'Reset Content',
304 206 => 'Partial Content',
305 300 => 'Multiple Choices',
306 301 => 'Moved Permanently',
308 304 => 'Not Modified',
310 307 => 'Temporary Redirect',
311 400 => 'Bad Request',
312 401 => 'Unauthorized',
315 405 => 'Method Not Allowed',
316 406 => 'Not Acceptable',
317 407 => 'Proxy Authentication Required',
318 408 => 'Request Timeout',
321 411 => 'Length Required',
322 412 => 'Precondition Failed',
323 413 => 'Request Entity Too Large',
324 414 => 'Request-URI Too Long',
325 415 => 'Unsupported Media Type',
326 416 => 'Requested Range Not Satisfiable',
327 417 => 'Expectation Failed',
328 500 => 'Internal Server Error',
329 501 => 'Not Implemented',
330 502 => 'Bad Gateway',
331 503 => 'Service Unavailable',
332 504 => 'Gateway Timeout',
333 505 => 'HTTP Version Not Supported'
336 if ($text == '' && isset($stati[$code])) {
337 $text = $stati[$code];
340 $server_protocol = $INPUT->server
->str('SERVER_PROTOCOL', false);
342 if (str_starts_with(PHP_SAPI
, 'cgi') ||
defined('SIMPLE_TEST')) {
343 header("Status: {$code} {$text}", true);
344 } elseif ($server_protocol == 'HTTP/1.1' ||
$server_protocol == 'HTTP/1.0') {
345 header($server_protocol . " {$code} {$text}", true, $code);
347 header("HTTP/1.1 {$code} {$text}", true, $code);