httputils.php 10 KB

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