BinaryFileResponse.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 bool $trustXSendfileTypeHeader = false;
  25. protected File $file;
  26. protected ?\SplTempFileObject $tempFileObject = null;
  27. protected int $offset = 0;
  28. protected int $maxlen = -1;
  29. protected bool $deleteFileAfterSend = false;
  30. protected int $chunkSize = 16 * 1024;
  31. /**
  32. * @param \SplFileInfo|string $file The file to stream
  33. * @param int $status The response status code (200 "OK" by default)
  34. * @param array $headers An array of response headers
  35. * @param bool $public Files are public by default
  36. * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
  37. * @param bool $autoEtag Whether the ETag header should be automatically set
  38. * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
  39. */
  40. public function __construct(\SplFileInfo|string $file, int $status = 200, array $headers = [], bool $public = true, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
  41. {
  42. parent::__construct(null, $status, $headers);
  43. $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
  44. if ($public) {
  45. $this->setPublic();
  46. }
  47. }
  48. /**
  49. * Sets the file to stream.
  50. *
  51. * @return $this
  52. *
  53. * @throws FileException
  54. */
  55. public function setFile(\SplFileInfo|string $file, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true): static
  56. {
  57. $isTemporaryFile = $file instanceof \SplTempFileObject;
  58. $this->tempFileObject = $isTemporaryFile ? $file : null;
  59. if (!$file instanceof File) {
  60. if ($file instanceof \SplFileInfo) {
  61. $file = new File($file->getPathname(), !$isTemporaryFile);
  62. } else {
  63. $file = new File($file);
  64. }
  65. }
  66. if (!$file->isReadable() && !$isTemporaryFile) {
  67. throw new FileException('File must be readable.');
  68. }
  69. $this->file = $file;
  70. if ($autoEtag) {
  71. $this->setAutoEtag();
  72. }
  73. if ($autoLastModified && !$isTemporaryFile) {
  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) {
  96. throw new \InvalidArgumentException('The chunk size of a BinaryFileResponse cannot be less than 1.');
  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->tempFileObject ? time() : $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('xxh128', $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. $mimeType = null;
  159. if (!$this->tempFileObject) {
  160. $mimeType = $this->file->getMimeType();
  161. }
  162. $this->headers->set('Content-Type', $mimeType ?: 'application/octet-stream');
  163. }
  164. parent::prepare($request);
  165. $this->offset = 0;
  166. $this->maxlen = -1;
  167. if ($this->tempFileObject) {
  168. $fileSize = $this->tempFileObject->fstat()['size'];
  169. } elseif (false === $fileSize = $this->file->getSize()) {
  170. return $this;
  171. }
  172. $this->headers->remove('Transfer-Encoding');
  173. $this->headers->set('Content-Length', $fileSize);
  174. if (!$this->headers->has('Accept-Ranges')) {
  175. // Only accept ranges on safe HTTP methods
  176. $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
  177. }
  178. if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
  179. // Use X-Sendfile, do not send any content.
  180. $type = $request->headers->get('X-Sendfile-Type');
  181. $path = $this->file->getRealPath();
  182. // Fall back to scheme://path for stream wrapped locations.
  183. if (false === $path) {
  184. $path = $this->file->getPathname();
  185. }
  186. if ('x-accel-redirect' === strtolower($type)) {
  187. // Do X-Accel-Mapping substitutions.
  188. // @link https://github.com/rack/rack/blob/main/lib/rack/sendfile.rb
  189. // @link https://mattbrictson.com/blog/accelerated-rails-downloads
  190. if (!$request->headers->has('X-Accel-Mapping')) {
  191. throw new \LogicException('The "X-Accel-Mapping" header must be set when "X-Sendfile-Type" is set to "X-Accel-Redirect".');
  192. }
  193. $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping'), ',=');
  194. foreach ($parts as $part) {
  195. [$pathPrefix, $location] = $part;
  196. if (str_starts_with($path, $pathPrefix)) {
  197. $path = $location.substr($path, \strlen($pathPrefix));
  198. // Only set X-Accel-Redirect header if a valid URI can be produced
  199. // as nginx does not serve arbitrary file paths.
  200. $this->headers->set($type, $path);
  201. $this->maxlen = 0;
  202. break;
  203. }
  204. }
  205. } else {
  206. $this->headers->set($type, $path);
  207. $this->maxlen = 0;
  208. }
  209. } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
  210. // Process the range headers.
  211. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
  212. $range = $request->headers->get('Range');
  213. if (str_starts_with($range, 'bytes=')) {
  214. [$start, $end] = explode('-', substr($range, 6), 2) + [1 => 0];
  215. $end = ('' === $end) ? $fileSize - 1 : (int) $end;
  216. if ('' === $start) {
  217. $start = $fileSize - $end;
  218. $end = $fileSize - 1;
  219. } else {
  220. $start = (int) $start;
  221. }
  222. if ($start <= $end) {
  223. $end = min($end, $fileSize - 1);
  224. if ($start < 0 || $start > $end) {
  225. $this->setStatusCode(416);
  226. $this->headers->set('Content-Range', \sprintf('bytes */%s', $fileSize));
  227. } elseif ($end - $start < $fileSize - 1) {
  228. $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
  229. $this->offset = $start;
  230. $this->setStatusCode(206);
  231. $this->headers->set('Content-Range', \sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
  232. $this->headers->set('Content-Length', $end - $start + 1);
  233. }
  234. }
  235. }
  236. }
  237. }
  238. if ($request->isMethod('HEAD')) {
  239. $this->maxlen = 0;
  240. }
  241. return $this;
  242. }
  243. private function hasValidIfRangeHeader(?string $header): bool
  244. {
  245. if ($this->getEtag() === $header) {
  246. return true;
  247. }
  248. if (null === $lastModified = $this->getLastModified()) {
  249. return false;
  250. }
  251. return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
  252. }
  253. public function sendContent(): static
  254. {
  255. try {
  256. if (!$this->isSuccessful()) {
  257. return $this;
  258. }
  259. if (0 === $this->maxlen) {
  260. return $this;
  261. }
  262. $out = fopen('php://output', 'w');
  263. if ($this->tempFileObject) {
  264. $file = $this->tempFileObject;
  265. $file->rewind();
  266. } else {
  267. $file = new \SplFileObject($this->file->getPathname(), 'r');
  268. }
  269. ignore_user_abort(true);
  270. if (0 !== $this->offset) {
  271. $file->fseek($this->offset);
  272. }
  273. $length = $this->maxlen;
  274. while ($length && !$file->eof()) {
  275. $read = $length > $this->chunkSize || 0 > $length ? $this->chunkSize : $length;
  276. if (false === $data = $file->fread($read)) {
  277. break;
  278. }
  279. while ('' !== $data) {
  280. $read = fwrite($out, $data);
  281. if (false === $read || connection_aborted()) {
  282. break 2;
  283. }
  284. if (0 < $length) {
  285. $length -= $read;
  286. }
  287. $data = substr($data, $read);
  288. }
  289. }
  290. fclose($out);
  291. } finally {
  292. if (null === $this->tempFileObject && $this->deleteFileAfterSend && is_file($this->file->getPathname())) {
  293. unlink($this->file->getPathname());
  294. }
  295. }
  296. return $this;
  297. }
  298. /**
  299. * @throws \LogicException when the content is not null
  300. */
  301. public function setContent(?string $content): static
  302. {
  303. if (null !== $content) {
  304. throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
  305. }
  306. return $this;
  307. }
  308. public function getContent(): string|false
  309. {
  310. return false;
  311. }
  312. /**
  313. * Trust X-Sendfile-Type header.
  314. */
  315. public static function trustXSendfileTypeHeader(): void
  316. {
  317. self::$trustXSendfileTypeHeader = true;
  318. }
  319. /**
  320. * If this is set to true, the file will be unlinked after the request is sent
  321. * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
  322. *
  323. * @return $this
  324. */
  325. public function deleteFileAfterSend(bool $shouldDelete = true): static
  326. {
  327. $this->deleteFileAfterSend = $shouldDelete;
  328. return $this;
  329. }
  330. }