BinaryFileResponse.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  12. use Symfony\Component\HttpFoundation\File\File;
  13. /**
  14. * BinaryFileResponse represents an HTTP response delivering a file.
  15. *
  16. * @author Niklas Fiekas <niklas.fiekas@tu-clausthal.de>
  17. * @author stealth35 <stealth35-php@live.fr>
  18. * @author Igor Wiedler <igor@wiedler.ch>
  19. * @author Jordan Alliot <jordan.alliot@gmail.com>
  20. * @author Sergey Linnik <linniksa@gmail.com>
  21. */
  22. class BinaryFileResponse extends Response
  23. {
  24. protected static $trustXSendfileTypeHeader = false;
  25. /**
  26. * @var File
  27. */
  28. protected $file;
  29. protected $offset = 0;
  30. protected $maxlen = -1;
  31. protected $deleteFileAfterSend = false;
  32. protected $chunkSize = 16 * 1024;
  33. /**
  34. * @param \SplFileInfo|string $file The file to stream
  35. * @param int $status The response status code (200 "OK" by default)
  36. * @param array $headers An array of response headers
  37. * @param bool $public Files are public by default
  38. * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
  39. * @param bool $autoEtag Whether the ETag header should be automatically set
  40. * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
  41. */
  42. public function __construct(\SplFileInfo|string $file, int $status = 200, array $headers = [], bool $public = true, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
  43. {
  44. parent::__construct(null, $status, $headers);
  45. $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
  46. if ($public) {
  47. $this->setPublic();
  48. }
  49. }
  50. /**
  51. * Sets the file to stream.
  52. *
  53. * @return $this
  54. *
  55. * @throws FileException
  56. */
  57. public function setFile(\SplFileInfo|string $file, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true): static
  58. {
  59. if (!$file instanceof File) {
  60. if ($file instanceof \SplFileInfo) {
  61. $file = new File($file->getPathname());
  62. } else {
  63. $file = new File((string) $file);
  64. }
  65. }
  66. if (!$file->isReadable()) {
  67. throw new FileException('File must be readable.');
  68. }
  69. $this->file = $file;
  70. if ($autoEtag) {
  71. $this->setAutoEtag();
  72. }
  73. if ($autoLastModified) {
  74. $this->setAutoLastModified();
  75. }
  76. if ($contentDisposition) {
  77. $this->setContentDisposition($contentDisposition);
  78. }
  79. return $this;
  80. }
  81. /**
  82. * Gets the file.
  83. */
  84. public function getFile(): File
  85. {
  86. return $this->file;
  87. }
  88. /**
  89. * Sets the response stream chunk size.
  90. *
  91. * @return $this
  92. */
  93. public function setChunkSize(int $chunkSize): static
  94. {
  95. if ($chunkSize < 1 || $chunkSize > \PHP_INT_MAX) {
  96. throw new \LogicException('The chunk size of a BinaryFileResponse cannot be less than 1 or greater than PHP_INT_MAX.');
  97. }
  98. $this->chunkSize = $chunkSize;
  99. return $this;
  100. }
  101. /**
  102. * Automatically sets the Last-Modified header according the file modification date.
  103. *
  104. * @return $this
  105. */
  106. public function setAutoLastModified(): static
  107. {
  108. $this->setLastModified(\DateTimeImmutable::createFromFormat('U', $this->file->getMTime()));
  109. return $this;
  110. }
  111. /**
  112. * Automatically sets the ETag header according to the checksum of the file.
  113. *
  114. * @return $this
  115. */
  116. public function setAutoEtag(): static
  117. {
  118. $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));
  119. return $this;
  120. }
  121. /**
  122. * Sets the Content-Disposition header with the given filename.
  123. *
  124. * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
  125. * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file
  126. * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
  127. *
  128. * @return $this
  129. */
  130. public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = ''): static
  131. {
  132. if ('' === $filename) {
  133. $filename = $this->file->getFilename();
  134. }
  135. if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) {
  136. $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
  137. for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
  138. $char = mb_substr($filename, $i, 1, $encoding);
  139. if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
  140. $filenameFallback .= '_';
  141. } else {
  142. $filenameFallback .= $char;
  143. }
  144. }
  145. }
  146. $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
  147. $this->headers->set('Content-Disposition', $dispositionHeader);
  148. return $this;
  149. }
  150. public function prepare(Request $request): static
  151. {
  152. if ($this->isInformational() || $this->isEmpty()) {
  153. parent::prepare($request);
  154. $this->maxlen = 0;
  155. return $this;
  156. }
  157. if (!$this->headers->has('Content-Type')) {
  158. $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
  159. }
  160. parent::prepare($request);
  161. $this->offset = 0;
  162. $this->maxlen = -1;
  163. if (false === $fileSize = $this->file->getSize()) {
  164. return $this;
  165. }
  166. $this->headers->remove('Transfer-Encoding');
  167. $this->headers->set('Content-Length', $fileSize);
  168. if (!$this->headers->has('Accept-Ranges')) {
  169. // Only accept ranges on safe HTTP methods
  170. $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
  171. }
  172. if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
  173. // Use X-Sendfile, do not send any content.
  174. $type = $request->headers->get('X-Sendfile-Type');
  175. $path = $this->file->getRealPath();
  176. // Fall back to scheme://path for stream wrapped locations.
  177. if (false === $path) {
  178. $path = $this->file->getPathname();
  179. }
  180. if ('x-accel-redirect' === strtolower($type)) {
  181. // Do X-Accel-Mapping substitutions.
  182. // @link https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-redirect
  183. $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
  184. foreach ($parts as $part) {
  185. [$pathPrefix, $location] = $part;
  186. if (str_starts_with($path, $pathPrefix)) {
  187. $path = $location.substr($path, \strlen($pathPrefix));
  188. // Only set X-Accel-Redirect header if a valid URI can be produced
  189. // as nginx does not serve arbitrary file paths.
  190. $this->headers->set($type, $path);
  191. $this->maxlen = 0;
  192. break;
  193. }
  194. }
  195. } else {
  196. $this->headers->set($type, $path);
  197. $this->maxlen = 0;
  198. }
  199. } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
  200. // Process the range headers.
  201. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
  202. $range = $request->headers->get('Range');
  203. if (str_starts_with($range, 'bytes=')) {
  204. [$start, $end] = explode('-', substr($range, 6), 2) + [1 => 0];
  205. $end = ('' === $end) ? $fileSize - 1 : (int) $end;
  206. if ('' === $start) {
  207. $start = $fileSize - $end;
  208. $end = $fileSize - 1;
  209. } else {
  210. $start = (int) $start;
  211. }
  212. if ($start <= $end) {
  213. $end = min($end, $fileSize - 1);
  214. if ($start < 0 || $start > $end) {
  215. $this->setStatusCode(416);
  216. $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
  217. } elseif ($end - $start < $fileSize - 1) {
  218. $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
  219. $this->offset = $start;
  220. $this->setStatusCode(206);
  221. $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
  222. $this->headers->set('Content-Length', $end - $start + 1);
  223. }
  224. }
  225. }
  226. }
  227. }
  228. if ($request->isMethod('HEAD')) {
  229. $this->maxlen = 0;
  230. }
  231. return $this;
  232. }
  233. private function hasValidIfRangeHeader(?string $header): bool
  234. {
  235. if ($this->getEtag() === $header) {
  236. return true;
  237. }
  238. if (null === $lastModified = $this->getLastModified()) {
  239. return false;
  240. }
  241. return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
  242. }
  243. public function sendContent(): static
  244. {
  245. try {
  246. if (!$this->isSuccessful()) {
  247. return $this;
  248. }
  249. if (0 === $this->maxlen) {
  250. return $this;
  251. }
  252. $out = fopen('php://output', 'w');
  253. $file = fopen($this->file->getPathname(), 'r');
  254. ignore_user_abort(true);
  255. if (0 !== $this->offset) {
  256. fseek($file, $this->offset);
  257. }
  258. $length = $this->maxlen;
  259. while ($length && !feof($file)) {
  260. $read = $length > $this->chunkSize || 0 > $length ? $this->chunkSize : $length;
  261. if (false === $data = fread($file, $read)) {
  262. break;
  263. }
  264. while ('' !== $data) {
  265. $read = fwrite($out, $data);
  266. if (false === $read || connection_aborted()) {
  267. break 2;
  268. }
  269. if (0 < $length) {
  270. $length -= $read;
  271. }
  272. $data = substr($data, $read);
  273. }
  274. }
  275. fclose($out);
  276. fclose($file);
  277. } finally {
  278. if ($this->deleteFileAfterSend && is_file($this->file->getPathname())) {
  279. unlink($this->file->getPathname());
  280. }
  281. }
  282. return $this;
  283. }
  284. /**
  285. * @throws \LogicException when the content is not null
  286. */
  287. public function setContent(?string $content): static
  288. {
  289. if (null !== $content) {
  290. throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
  291. }
  292. return $this;
  293. }
  294. public function getContent(): string|false
  295. {
  296. return false;
  297. }
  298. /**
  299. * Trust X-Sendfile-Type header.
  300. *
  301. * @return void
  302. */
  303. public static function trustXSendfileTypeHeader()
  304. {
  305. self::$trustXSendfileTypeHeader = true;
  306. }
  307. /**
  308. * If this is set to true, the file will be unlinked after the request is sent
  309. * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
  310. *
  311. * @return $this
  312. */
  313. public function deleteFileAfterSend(bool $shouldDelete = true): static
  314. {
  315. $this->deleteFileAfterSend = $shouldDelete;
  316. return $this;
  317. }
  318. }