You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

350 lines
10 KiB

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