BinaryFileResponse.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. /**
  33. * @param \SplFileInfo|string $file The file to stream
  34. * @param int $status The response status code
  35. * @param array $headers An array of response headers
  36. * @param bool $public Files are public by default
  37. * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
  38. * @param bool $autoEtag Whether the ETag header should be automatically set
  39. * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
  40. */
  41. public function __construct(\SplFileInfo|string $file, int $status = 200, array $headers = [], bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
  42. {
  43. parent::__construct(null, $status, $headers);
  44. $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
  45. if ($public) {
  46. $this->setPublic();
  47. }
  48. }
  49. /**
  50. * Sets the file to stream.
  51. *
  52. * @return $this
  53. *
  54. * @throws FileException
  55. */
  56. public function setFile(\SplFileInfo|string $file, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true): static
  57. {
  58. if (!$file instanceof File) {
  59. if ($file instanceof \SplFileInfo) {
  60. $file = new File($file->getPathname());
  61. } else {
  62. $file = new File((string) $file);
  63. }
  64. }
  65. if (!$file->isReadable()) {
  66. throw new FileException('File must be readable.');
  67. }
  68. $this->file = $file;
  69. if ($autoEtag) {
  70. $this->setAutoEtag();
  71. }
  72. if ($autoLastModified) {
  73. $this->setAutoLastModified();
  74. }
  75. if ($contentDisposition) {
  76. $this->setContentDisposition($contentDisposition);
  77. }
  78. return $this;
  79. }
  80. /**
  81. * Gets the file.
  82. */
  83. public function getFile(): File
  84. {
  85. return $this->file;
  86. }
  87. /**
  88. * Automatically sets the Last-Modified header according the file modification date.
  89. *
  90. * @return $this
  91. */
  92. public function setAutoLastModified(): static
  93. {
  94. $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
  95. return $this;
  96. }
  97. /**
  98. * Automatically sets the ETag header according to the checksum of the file.
  99. *
  100. * @return $this
  101. */
  102. public function setAutoEtag(): static
  103. {
  104. $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));
  105. return $this;
  106. }
  107. /**
  108. * Sets the Content-Disposition header with the given filename.
  109. *
  110. * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
  111. * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file
  112. * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
  113. *
  114. * @return $this
  115. */
  116. public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = ''): static
  117. {
  118. if ('' === $filename) {
  119. $filename = $this->file->getFilename();
  120. }
  121. if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) {
  122. $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
  123. for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
  124. $char = mb_substr($filename, $i, 1, $encoding);
  125. if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
  126. $filenameFallback .= '_';
  127. } else {
  128. $filenameFallback .= $char;
  129. }
  130. }
  131. }
  132. $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
  133. $this->headers->set('Content-Disposition', $dispositionHeader);
  134. return $this;
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function prepare(Request $request): static
  140. {
  141. if (!$this->headers->has('Content-Type')) {
  142. $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
  143. }
  144. if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) {
  145. $this->setProtocolVersion('1.1');
  146. }
  147. $this->ensureIEOverSSLCompatibility($request);
  148. $this->offset = 0;
  149. $this->maxlen = -1;
  150. if (false === $fileSize = $this->file->getSize()) {
  151. return $this;
  152. }
  153. $this->headers->set('Content-Length', $fileSize);
  154. if (!$this->headers->has('Accept-Ranges')) {
  155. // Only accept ranges on safe HTTP methods
  156. $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
  157. }
  158. if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
  159. // Use X-Sendfile, do not send any content.
  160. $type = $request->headers->get('X-Sendfile-Type');
  161. $path = $this->file->getRealPath();
  162. // Fall back to scheme://path for stream wrapped locations.
  163. if (false === $path) {
  164. $path = $this->file->getPathname();
  165. }
  166. if ('x-accel-redirect' === strtolower($type)) {
  167. // Do X-Accel-Mapping substitutions.
  168. // @link https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-redirect
  169. $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
  170. foreach ($parts as $part) {
  171. [$pathPrefix, $location] = $part;
  172. if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
  173. $path = $location.substr($path, \strlen($pathPrefix));
  174. // Only set X-Accel-Redirect header if a valid URI can be produced
  175. // as nginx does not serve arbitrary file paths.
  176. $this->headers->set($type, $path);
  177. $this->maxlen = 0;
  178. break;
  179. }
  180. }
  181. } else {
  182. $this->headers->set($type, $path);
  183. $this->maxlen = 0;
  184. }
  185. } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
  186. // Process the range headers.
  187. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
  188. $range = $request->headers->get('Range');
  189. if (str_starts_with($range, 'bytes=')) {
  190. [$start, $end] = explode('-', substr($range, 6), 2) + [0];
  191. $end = ('' === $end) ? $fileSize - 1 : (int) $end;
  192. if ('' === $start) {
  193. $start = $fileSize - $end;
  194. $end = $fileSize - 1;
  195. } else {
  196. $start = (int) $start;
  197. }
  198. if ($start <= $end) {
  199. $end = min($end, $fileSize - 1);
  200. if ($start < 0 || $start > $end) {
  201. $this->setStatusCode(416);
  202. $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
  203. } elseif ($end - $start < $fileSize - 1) {
  204. $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
  205. $this->offset = $start;
  206. $this->setStatusCode(206);
  207. $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
  208. $this->headers->set('Content-Length', $end - $start + 1);
  209. }
  210. }
  211. }
  212. }
  213. }
  214. return $this;
  215. }
  216. private function hasValidIfRangeHeader(?string $header): bool
  217. {
  218. if ($this->getEtag() === $header) {
  219. return true;
  220. }
  221. if (null === $lastModified = $this->getLastModified()) {
  222. return false;
  223. }
  224. return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
  225. }
  226. /**
  227. * {@inheritdoc}
  228. */
  229. public function sendContent(): static
  230. {
  231. if (!$this->isSuccessful()) {
  232. return parent::sendContent();
  233. }
  234. if (0 === $this->maxlen) {
  235. return $this;
  236. }
  237. $out = fopen('php://output', 'w');
  238. $file = fopen($this->file->getPathname(), 'r');
  239. stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
  240. fclose($out);
  241. fclose($file);
  242. if ($this->deleteFileAfterSend && is_file($this->file->getPathname())) {
  243. unlink($this->file->getPathname());
  244. }
  245. return $this;
  246. }
  247. /**
  248. * {@inheritdoc}
  249. *
  250. * @throws \LogicException when the content is not null
  251. */
  252. public function setContent(?string $content): static
  253. {
  254. if (null !== $content) {
  255. throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
  256. }
  257. return $this;
  258. }
  259. /**
  260. * {@inheritdoc}
  261. */
  262. public function getContent(): string|false
  263. {
  264. return false;
  265. }
  266. /**
  267. * Trust X-Sendfile-Type header.
  268. */
  269. public static function trustXSendfileTypeHeader()
  270. {
  271. self::$trustXSendfileTypeHeader = true;
  272. }
  273. /**
  274. * If this is set to true, the file will be unlinked after the request is sent
  275. * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
  276. *
  277. * @return $this
  278. */
  279. public function deleteFileAfterSend(bool $shouldDelete = true): static
  280. {
  281. $this->deleteFileAfterSend = $shouldDelete;
  282. return $this;
  283. }
  284. }