BinaryFileResponse.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 = 8 * 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. public static function create($file = null, $status = 200, $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
  62. {
  63. return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
  64. }
  65. /**
  66. * Sets the file to stream.
  67. *
  68. * @param \SplFileInfo|string $file The file to stream
  69. * @param string $contentDisposition
  70. * @param bool $autoEtag
  71. * @param bool $autoLastModified
  72. *
  73. * @return $this
  74. *
  75. * @throws FileException
  76. */
  77. public function setFile($file, $contentDisposition = null, $autoEtag = false, $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 The file to stream
  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. public function setAutoLastModified()
  127. {
  128. $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
  129. return $this;
  130. }
  131. /**
  132. * Automatically sets the ETag header according to the checksum of the file.
  133. */
  134. public function setAutoEtag()
  135. {
  136. $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));
  137. return $this;
  138. }
  139. /**
  140. * Sets the Content-Disposition header with the given filename.
  141. *
  142. * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
  143. * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file
  144. * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
  145. *
  146. * @return $this
  147. */
  148. public function setContentDisposition($disposition, $filename = '', $filenameFallback = '')
  149. {
  150. if ('' === $filename) {
  151. $filename = $this->file->getFilename();
  152. }
  153. if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) {
  154. $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
  155. for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
  156. $char = mb_substr($filename, $i, 1, $encoding);
  157. if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
  158. $filenameFallback .= '_';
  159. } else {
  160. $filenameFallback .= $char;
  161. }
  162. }
  163. }
  164. $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
  165. $this->headers->set('Content-Disposition', $dispositionHeader);
  166. return $this;
  167. }
  168. /**
  169. * {@inheritdoc}
  170. */
  171. public function prepare(Request $request)
  172. {
  173. if ($this->isInformational() || $this->isEmpty()) {
  174. parent::prepare($request);
  175. $this->maxlen = 0;
  176. return $this;
  177. }
  178. if (!$this->headers->has('Content-Type')) {
  179. $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
  180. }
  181. parent::prepare($request);
  182. $this->offset = 0;
  183. $this->maxlen = -1;
  184. if (false === $fileSize = $this->file->getSize()) {
  185. return $this;
  186. }
  187. $this->headers->remove('Transfer-Encoding');
  188. $this->headers->set('Content-Length', $fileSize);
  189. if (!$this->headers->has('Accept-Ranges')) {
  190. // Only accept ranges on safe HTTP methods
  191. $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
  192. }
  193. if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
  194. // Use X-Sendfile, do not send any content.
  195. $type = $request->headers->get('X-Sendfile-Type');
  196. $path = $this->file->getRealPath();
  197. // Fall back to scheme://path for stream wrapped locations.
  198. if (false === $path) {
  199. $path = $this->file->getPathname();
  200. }
  201. if ('x-accel-redirect' === strtolower($type)) {
  202. // Do X-Accel-Mapping substitutions.
  203. // @link https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-redirect
  204. $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
  205. foreach ($parts as $part) {
  206. [$pathPrefix, $location] = $part;
  207. if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
  208. $path = $location.substr($path, \strlen($pathPrefix));
  209. // Only set X-Accel-Redirect header if a valid URI can be produced
  210. // as nginx does not serve arbitrary file paths.
  211. $this->headers->set($type, $path);
  212. $this->maxlen = 0;
  213. break;
  214. }
  215. }
  216. } else {
  217. $this->headers->set($type, $path);
  218. $this->maxlen = 0;
  219. }
  220. } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
  221. // Process the range headers.
  222. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
  223. $range = $request->headers->get('Range');
  224. if (str_starts_with($range, 'bytes=')) {
  225. [$start, $end] = explode('-', substr($range, 6), 2) + [0];
  226. $end = ('' === $end) ? $fileSize - 1 : (int) $end;
  227. if ('' === $start) {
  228. $start = $fileSize - $end;
  229. $end = $fileSize - 1;
  230. } else {
  231. $start = (int) $start;
  232. }
  233. if ($start <= $end) {
  234. $end = min($end, $fileSize - 1);
  235. if ($start < 0 || $start > $end) {
  236. $this->setStatusCode(416);
  237. $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
  238. } elseif ($end - $start < $fileSize - 1) {
  239. $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
  240. $this->offset = $start;
  241. $this->setStatusCode(206);
  242. $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
  243. $this->headers->set('Content-Length', $end - $start + 1);
  244. }
  245. }
  246. }
  247. }
  248. }
  249. if ($request->isMethod('HEAD')) {
  250. $this->maxlen = 0;
  251. }
  252. return $this;
  253. }
  254. private function hasValidIfRangeHeader(?string $header): bool
  255. {
  256. if ($this->getEtag() === $header) {
  257. return true;
  258. }
  259. if (null === $lastModified = $this->getLastModified()) {
  260. return false;
  261. }
  262. return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
  263. }
  264. /**
  265. * Sends the file.
  266. *
  267. * {@inheritdoc}
  268. */
  269. public function sendContent()
  270. {
  271. try {
  272. if (!$this->isSuccessful()) {
  273. return parent::sendContent();
  274. }
  275. if (0 === $this->maxlen) {
  276. return $this;
  277. }
  278. $out = fopen('php://output', 'w');
  279. $file = fopen($this->file->getPathname(), 'r');
  280. ignore_user_abort(true);
  281. if (0 !== $this->offset) {
  282. fseek($file, $this->offset);
  283. }
  284. $length = $this->maxlen;
  285. while ($length && !feof($file)) {
  286. $read = ($length > $this->chunkSize) ? $this->chunkSize : $length;
  287. $length -= $read;
  288. stream_copy_to_stream($file, $out, $read);
  289. if (connection_aborted()) {
  290. break;
  291. }
  292. }
  293. fclose($out);
  294. fclose($file);
  295. } finally {
  296. if ($this->deleteFileAfterSend && file_exists($this->file->getPathname())) {
  297. unlink($this->file->getPathname());
  298. }
  299. }
  300. return $this;
  301. }
  302. /**
  303. * {@inheritdoc}
  304. *
  305. * @throws \LogicException when the content is not null
  306. */
  307. public function setContent($content)
  308. {
  309. if (null !== $content) {
  310. throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
  311. }
  312. return $this;
  313. }
  314. /**
  315. * {@inheritdoc}
  316. */
  317. public function getContent()
  318. {
  319. return false;
  320. }
  321. /**
  322. * Trust X-Sendfile-Type header.
  323. */
  324. public static function trustXSendfileTypeHeader()
  325. {
  326. self::$trustXSendfileTypeHeader = true;
  327. }
  328. /**
  329. * If this is set to true, the file will be unlinked after the request is sent
  330. * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
  331. *
  332. * @param bool $shouldDelete
  333. *
  334. * @return $this
  335. */
  336. public function deleteFileAfterSend($shouldDelete = true)
  337. {
  338. $this->deleteFileAfterSend = $shouldDelete;
  339. return $this;
  340. }
  341. }