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 * @param int $timestamp lastmodified time of the cache file 19 * @returns void or exits with previously header() commands executed 20 */ 21function http_conditionalRequest($timestamp){ 22 // A PHP implementation of conditional get, see 23 // http://fishbowl.pastiche.org/2002/10/21/http_conditional_get_for_rss_hackers/ 24 $last_modified = substr(gmdate('r', $timestamp), 0, -5).'GMT'; 25 $etag = '"'.md5($last_modified).'"'; 26 // Send the headers 27 header("Last-Modified: $last_modified"); 28 header("ETag: $etag"); 29 // See if the client has provided the required headers 30 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){ 31 $if_modified_since = stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']); 32 }else{ 33 $if_modified_since = false; 34 } 35 36 if (isset($_SERVER['HTTP_IF_NONE_MATCH'])){ 37 $if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']); 38 }else{ 39 $if_none_match = false; 40 } 41 42 if (!$if_modified_since && !$if_none_match){ 43 return; 44 } 45 46 // At least one of the headers is there - check them 47 if ($if_none_match && $if_none_match != $etag) { 48 return; // etag is there but doesn't match 49 } 50 51 if ($if_modified_since && $if_modified_since != $last_modified) { 52 return; // if-modified-since is there but doesn't match 53 } 54 55 // Nothing has changed since their last request - serve a 304 and exit 56 header('HTTP/1.0 304 Not Modified'); 57 58 // don't produce output, even if compression is on 59 @ob_end_clean(); 60 exit; 61} 62 63/** 64 * Let the webserver send the given file vi x-sendfile method 65 * 66 * @author Chris Smith <chris.eureka@jalakai.co.uk> 67 * @returns void or exits with previously header() commands executed 68 */ 69function http_sendfile($file) { 70 global $conf; 71 72 //use x-sendfile header to pass the delivery to compatible webservers 73 if($conf['xsendfile'] == 1){ 74 header("X-LIGHTTPD-send-file: $file"); 75 ob_end_clean(); 76 exit; 77 }elseif($conf['xsendfile'] == 2){ 78 header("X-Sendfile: $file"); 79 ob_end_clean(); 80 exit; 81 }elseif($conf['xsendfile'] == 3){ 82 header("X-Accel-Redirect: $file"); 83 ob_end_clean(); 84 exit; 85 } 86 87 return false; 88} 89 90/** 91 * Send file contents supporting rangeRequests 92 * 93 * This function exits the running script 94 * 95 * @param ressource $fh - file handle for an already open file 96 * @param int $size - size of the whole file 97 * @param int $mime - MIME type of the file 98 * 99 * @author Andreas Gohr <andi@splitbrain.org> 100 */ 101function http_rangeRequest($fh,$size,$mime){ 102 $ranges = array(); 103 $isrange = false; 104 105 header('Accept-Ranges: bytes'); 106 107 if(!isset($_SERVER['HTTP_RANGE'])){ 108 // no range requested - send the whole file 109 $ranges[] = array(0,$size,$size); 110 }else{ 111 $t = explode('=', $_SERVER['HTTP_RANGE']); 112 if (!$t[0]=='bytes') { 113 // we only understand byte ranges - send the whole file 114 $ranges[] = array(0,$size,$size); 115 }else{ 116 $isrange = true; 117 // handle multiple ranges 118 $r = explode(',',$t[1]); 119 foreach($r as $x){ 120 $p = explode('-', $x); 121 $start = (int)$p[0]; 122 $end = (int)$p[1]; 123 if (!$end) $end = $size - 1; 124 if ($start > $end || $start > $size || $end > $size){ 125 header('HTTP/1.1 416 Requested Range Not Satisfiable'); 126 print 'Bad Range Request!'; 127 exit; 128 } 129 $len = $end - $start + 1; 130 $ranges[] = array($start,$end,$len); 131 } 132 } 133 } 134 $parts = count($ranges); 135 136 // now send the type and length headers 137 if(!$isrange){ 138 header("Content-Type: $mime",true); 139 }else{ 140 header('HTTP/1.1 206 Partial Content'); 141 if($parts == 1){ 142 header("Content-Type: $mime",true); 143 }else{ 144 header('Content-Type: multipart/byteranges; boundary='.HTTP_MULTIPART_BOUNDARY,true); 145 } 146 } 147 148 // send all ranges 149 for($i=0; $i<$parts; $i++){ 150 list($start,$end,$len) = $ranges[$i]; 151 152 // multipart or normal headers 153 if($parts > 1){ 154 echo HTTP_HEADER_LF.'--'.HTTP_MULTIPART_BOUNDARY.HTTP_HEADER_LF; 155 echo "Content-Type: $mime".HTTP_HEADER_LF; 156 echo "Content-Range: bytes $start-$end/$size".HTTP_HEADER_LF; 157 echo HTTP_HEADER_LF; 158 }else{ 159 header("Content-Length: $len"); 160 if($isrange){ 161 header("Content-Range: bytes $start-$end/$size"); 162 } 163 } 164 165 // send file content 166 fseek($fh,$start); //seek to start of range 167 $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len; 168 while (!feof($fh) && $chunk > 0) { 169 @set_time_limit(30); // large files can take a lot of time 170 print fread($fh, $chunk); 171 flush(); 172 $len -= $chunk; 173 $chunk = ($len > HTTP_CHUNK_SIZE) ? HTTP_CHUNK_SIZE : $len; 174 } 175 } 176 if($parts > 1){ 177 echo HTTP_HEADER_LF.'--'.HTTP_MULTIPART_BOUNDARY.'--'.HTTP_HEADER_LF; 178 } 179 180 // everything should be done here, exit 181 exit; 182} 183 184/** 185 * Check for a gzipped version and create if necessary 186 * 187 * return true if there exists a gzip version of the uncompressed file 188 * (samepath/samefilename.sameext.gz) created after the uncompressed file 189 * 190 * @author Chris Smith <chris.eureka@jalakai.co.uk> 191 */ 192function http_gzip_valid($uncompressed_file) { 193 $gzip = $uncompressed_file.'.gz'; 194 if (filemtime($gzip) < filemtime($uncompressed_file)) { // filemtime returns false (0) if file doesn't exist 195 return copy($uncompressed_file, 'compress.zlib://'.$gzip); 196 } 197 198 return true; 199} 200 201/** 202 * Set HTTP headers and echo cachefile, if useable 203 * 204 * This function handles output of cacheable resource files. It ses the needed 205 * HTTP headers. If a useable cache is present, it is passed to the web server 206 * and the scrpt is terminated. 207 */ 208function http_cached($cache, $cache_ok) { 209 global $conf; 210 211 // check cache age & handle conditional request 212 // since the resource files are timestamped, we can use a long max age: 1 year 213 header('Cache-Control: public, max-age=31536000'); 214 header('Pragma: public'); 215 if($cache_ok){ 216 http_conditionalRequest(filemtime($cache)); 217 if($conf['allowdebug']) header("X-CacheUsed: $cache"); 218 219 // finally send output 220 if ($conf['gzip_output'] && http_gzip_valid($cache)) { 221 header('Vary: Accept-Encoding'); 222 header('Content-Encoding: gzip'); 223 readfile($cache.".gz"); 224 } else { 225 if (!http_sendfile($cache)) readfile($cache); 226 } 227 exit; 228 } 229 230 http_conditionalRequest(time()); 231} 232 233/** 234 * Cache content and print it 235 */ 236function http_cached_finish($file, $content) { 237 global $conf; 238 239 // save cache file 240 io_saveFile($file, $content); 241 if(function_exists('gzopen')) io_saveFile("$file.gz",$content); 242 243 // finally send output 244 if ($conf['gzip_output']) { 245 header('Vary: Accept-Encoding'); 246 header('Content-Encoding: gzip'); 247 print gzencode($content,9,FORCE_GZIP); 248 } else { 249 print $content; 250 } 251} 252 253/** 254 * Fetches raw, unparsed POST data 255 * 256 * @return string 257 */ 258function http_get_raw_post_data() { 259 static $postData = null; 260 if ($postData === null) { 261 $postData = file_get_contents('php://input'); 262 } 263 return $postData; 264} 265 266/** 267 * Set the HTTP response status and takes care of the used PHP SAPI 268 * 269 * Inspired by CodeIgniter's set_status_header function 270 * 271 * @param int $code 272 * @param string $text 273 */ 274function http_status($code = 200, $text = '') { 275 static $stati = array( 276 200 => 'OK', 277 201 => 'Created', 278 202 => 'Accepted', 279 203 => 'Non-Authoritative Information', 280 204 => 'No Content', 281 205 => 'Reset Content', 282 206 => 'Partial Content', 283 284 300 => 'Multiple Choices', 285 301 => 'Moved Permanently', 286 302 => 'Found', 287 304 => 'Not Modified', 288 305 => 'Use Proxy', 289 307 => 'Temporary Redirect', 290 291 400 => 'Bad Request', 292 401 => 'Unauthorized', 293 403 => 'Forbidden', 294 404 => 'Not Found', 295 405 => 'Method Not Allowed', 296 406 => 'Not Acceptable', 297 407 => 'Proxy Authentication Required', 298 408 => 'Request Timeout', 299 409 => 'Conflict', 300 410 => 'Gone', 301 411 => 'Length Required', 302 412 => 'Precondition Failed', 303 413 => 'Request Entity Too Large', 304 414 => 'Request-URI Too Long', 305 415 => 'Unsupported Media Type', 306 416 => 'Requested Range Not Satisfiable', 307 417 => 'Expectation Failed', 308 309 500 => 'Internal Server Error', 310 501 => 'Not Implemented', 311 502 => 'Bad Gateway', 312 503 => 'Service Unavailable', 313 504 => 'Gateway Timeout', 314 505 => 'HTTP Version Not Supported' 315 ); 316 317 if($text == '' && isset($stati[$code])) { 318 $text = $stati[$code]; 319 } 320 321 $server_protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : false; 322 323 if(substr(php_sapi_name(), 0, 3) == 'cgi') { 324 header("Status: {$code} {$text}", true); 325 } elseif($server_protocol == 'HTTP/1.1' OR $server_protocol == 'HTTP/1.0') { 326 header($server_protocol." {$code} {$text}", true, $code); 327 } else { 328 header("HTTP/1.1 {$code} {$text}", true, $code); 329 } 330} 331