BinaryFileResponse.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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
  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($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. * @param \SplFileInfo|string $file The file to stream
  52. * @param int $status The response status code
  53. * @param array $headers An array of response headers
  54. * @param bool $public Files are public by default
  55. * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
  56. * @param bool $autoEtag Whether the ETag header should be automatically set
  57. * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
  58. *
  59. * @return static
  60. *
  61. * @deprecated since Symfony 5.2, use __construct() instead.
  62. */
  63. public static function create($file = null, int $status = 200, array $headers = [], bool $public = true, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
  64. {
  65. trigger_deprecation('symfony/http-foundation', '5.2', 'The "%s()" method is deprecated, use "new %s()" instead.', __METHOD__, static::class);
  66. return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
  67. }
  68. /**
  69. * Sets the file to stream.
  70. *
  71. * @param \SplFileInfo|string $file The file to stream
  72. *
  73. * @return $this
  74. *
  75. * @throws FileException
  76. */
  77. public function setFile($file, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
  78. {
  79. if (!$file instanceof File) {
  80. if ($file instanceof \SplFileInfo) {
  81. $file = new File($file->getPathname());
  82. } else {
  83. $file = new File((string) $file);
  84. }
  85. }
  86. if (!$file->isReadable()) {
  87. throw new FileException('File must be readable.');
  88. }
  89. $this->file = $file;
  90. if ($autoEtag) {
  91. $this->setAutoEtag();
  92. }
  93. if ($autoLastModified) {
  94. $this->setAutoLastModified();
  95. }
  96. if ($contentDisposition) {
  97. $this->setContentDisposition($contentDisposition);
  98. }
  99. return $this;
  100. }
  101. /**
  102. * Gets the file.
  103. *
  104. * @return File
  105. */
  106. public function getFile()
  107. {
  108. return $this->file;
  109. }
  110. /**
  111. * Sets the response stream chunk size.
  112. *
  113. * @return $this
  114. */
  115. public function setChunkSize(int $chunkSize): self
  116. {
  117. if ($chunkSize < 1 || $chunkSize > \PHP_INT_MAX) {
  118. throw new \LogicException('The chunk size of a BinaryFileResponse cannot be less than 1 or greater than PHP_INT_MAX.');
  119. }
  120. $this->chunkSize = $chunkSize;
  121. return $this;
  122. }
  123. /**
  124. * Automatically sets the Last-Modified header according the file modification date.
  125. *
  126. * @return $this
  127. */
  128. public function setAutoLastModified()
  129. {
  130. $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
  131. return $this;
  132. }
  133. /**
  134. * Automatically sets the ETag header according to the checksum of the file.
  135. *
  136. * @return $this
  137. */
  138. public function setAutoEtag()
  139. {
  140. $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));
  141. return $this;
  142. }
  143. /**
  144. * Sets the Content-Disposition header with the given filename.
  145. *
  146. * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
  147. * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file
  148. * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
  149. *
  150. * @return $this
  151. */
  152. public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = '')
  153. {
  154. if ('' === $filename) {
  155. $filename = $this->file->getFilename();
  156. }
  157. if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) {
  158. $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
  159. for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
  160. $char = mb_substr($filename, $i, 1, $encoding);
  161. if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
  162. $filenameFallback .= '_';
  163. } else {
  164. $filenameFallback .= $char;
  165. }
  166. }
  167. }
  168. $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
  169. $this->headers->set('Content-Disposition', $dispositionHeader);
  170. return $this;
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function prepare(Request $request)
  176. {
  177. if ($this->isInformational() || $this->isEmpty()) {
  178. parent::prepare($request);
  179. $this->maxlen = 0;
  180. return $this;
  181. }
  182. if (!$this->headers->has('Content-Type')) {
  183. $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
  184. }
  185. parent::prepare($request);
  186. $this->offset = 0;
  187. $this->maxlen = -1;
  188. if (false === $fileSize = $this->file->getSize()) {
  189. return $this;
  190. }
  191. $this->headers->remove('Transfer-Encoding');
  192. $this->headers->set('Content-Length', $fileSize);
  193. if (!$this->headers->has('Accept-Ranges')) {
  194. // Only accept ranges on safe HTTP methods
  195. $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
  196. }
  197. if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
  198. // Use X-Sendfile, do not send any content.
  199. $type = $request->headers->get('X-Sendfile-Type');
  200. $path = $this->file->getRealPath();
  201. // Fall back to scheme://path for stream wrapped locations.
  202. if (false === $path) {
  203. $path = $this->file->getPathname();
  204. }
  205. if ('x-accel-redirect' === strtolower($type)) {
  206. // Do X-Accel-Mapping substitutions.
  207. // @link https://github.com/rack/rack/blob/main/lib/rack/sendfile.rb
  208. // @link https://mattbrictson.com/blog/accelerated-rails-downloads
  209. if (!$request->headers->has('X-Accel-Mapping')) {
  210. throw new \LogicException('The "X-Accel-Mapping" header must be set when "X-Sendfile-Type" is set to "X-Accel-Redirect".');
  211. }
  212. $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping'), ',=');
  213. foreach ($parts as $part) {
  214. [$pathPrefix, $location] = $part;
  215. if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
  216. $path = $location.substr($path, \strlen($pathPrefix));
  217. // Only set X-Accel-Redirect header if a valid URI can be produced
  218. // as nginx does not serve arbitrary file paths.
  219. $this->headers->set($type, $path);
  220. $this->maxlen = 0;
  221. break;
  222. }
  223. }
  224. } else {
  225. $this->headers->set($type, $path);
  226. $this->maxlen = 0;
  227. }
  228. } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
  229. // Process the range headers.
  230. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
  231. $range = $request->headers->get('Range');
  232. if (str_starts_with($range, 'bytes=')) {
  233. [$start, $end] = explode('-', substr($range, 6), 2) + [1 => 0];
  234. $end = ('' === $end) ? $fileSize - 1 : (int) $end;
  235. if ('' === $start) {
  236. $start = $fileSize - $end;
  237. $end = $fileSize - 1;
  238. } else {
  239. $start = (int) $start;
  240. }
  241. if ($start <= $end) {
  242. $end = min($end, $fileSize - 1);
  243. if ($start < 0 || $start > $end) {
  244. $this->setStatusCode(416);
  245. $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
  246. } elseif ($end - $start < $fileSize - 1) {
  247. $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
  248. $this->offset = $start;
  249. $this->setStatusCode(206);
  250. $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
  251. $this->headers->set('Content-Length', $end - $start + 1);
  252. }
  253. }
  254. }
  255. }
  256. }
  257. if ($request->isMethod('HEAD')) {
  258. $this->maxlen = 0;
  259. }
  260. return $this;
  261. }
  262. private function hasValidIfRangeHeader(?string $header): bool
  263. {
  264. if ($this->getEtag() === $header) {
  265. return true;
  266. }
  267. if (null === $lastModified = $this->getLastModified()) {
  268. return false;
  269. }
  270. return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
  271. }
  272. /**
  273. * {@inheritdoc}
  274. */
  275. public function sendContent()
  276. {
  277. try {
  278. if (!$this->isSuccessful()) {
  279. return parent::sendContent();
  280. }
  281. if (0 === $this->maxlen) {
  282. return $this;
  283. }
  284. $out = fopen('php://output', 'w');
  285. $file = fopen($this->file->getPathname(), 'r');
  286. ignore_user_abort(true);
  287. if (0 !== $this->offset) {
  288. fseek($file, $this->offset);
  289. }
  290. $length = $this->maxlen;
  291. while ($length && !feof($file)) {
  292. $read = $length > $this->chunkSize || 0 > $length ? $this->chunkSize : $length;
  293. if (false === $data = fread($file, $read)) {
  294. break;
  295. }
  296. while ('' !== $data) {
  297. $read = fwrite($out, $data);
  298. if (false === $read || connection_aborted()) {
  299. break 2;
  300. }
  301. if (0 < $length) {
  302. $length -= $read;
  303. }
  304. $data = substr($data, $read);
  305. }
  306. }
  307. fclose($out);
  308. fclose($file);
  309. } finally {
  310. if ($this->deleteFileAfterSend && is_file($this->file->getPathname())) {
  311. unlink($this->file->getPathname());
  312. }
  313. }
  314. return $this;
  315. }
  316. /**
  317. * {@inheritdoc}
  318. *
  319. * @throws \LogicException when the content is not null
  320. */
  321. public function setContent(?string $content)
  322. {
  323. if (null !== $content) {
  324. throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
  325. }
  326. return $this;
  327. }
  328. /**
  329. * {@inheritdoc}
  330. */
  331. public function getContent()
  332. {
  333. return false;
  334. }
  335. /**
  336. * Trust X-Sendfile-Type header.
  337. */
  338. public static function trustXSendfileTypeHeader()
  339. {
  340. self::$trustXSendfileTypeHeader = true;
  341. }
  342. /**
  343. * If this is set to true, the file will be unlinked after the request is sent
  344. * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
  345. *
  346. * @return $this
  347. */
  348. public function deleteFileAfterSend(bool $shouldDelete = true)
  349. {
  350. $this->deleteFileAfterSend = $shouldDelete;
  351. return $this;
  352. }
  353. }