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 $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. * @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->headers->has('Content-Type')) {
  178. $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
  179. }
  180. if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) {
  181. $this->setProtocolVersion('1.1');
  182. }
  183. $this->ensureIEOverSSLCompatibility($request);
  184. $this->offset = 0;
  185. $this->maxlen = -1;
  186. if (false === $fileSize = $this->file->getSize()) {
  187. return $this;
  188. }
  189. $this->headers->set('Content-Length', $fileSize);
  190. if (!$this->headers->has('Accept-Ranges')) {
  191. // Only accept ranges on safe HTTP methods
  192. $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
  193. }
  194. if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
  195. // Use X-Sendfile, do not send any content.
  196. $type = $request->headers->get('X-Sendfile-Type');
  197. $path = $this->file->getRealPath();
  198. // Fall back to scheme://path for stream wrapped locations.
  199. if (false === $path) {
  200. $path = $this->file->getPathname();
  201. }
  202. if ('x-accel-redirect' === strtolower($type)) {
  203. // Do X-Accel-Mapping substitutions.
  204. // @link https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-redirect
  205. $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
  206. foreach ($parts as $part) {
  207. [$pathPrefix, $location] = $part;
  208. if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
  209. $path = $location.substr($path, \strlen($pathPrefix));
  210. // Only set X-Accel-Redirect header if a valid URI can be produced
  211. // as nginx does not serve arbitrary file paths.
  212. $this->headers->set($type, $path);
  213. $this->maxlen = 0;
  214. break;
  215. }
  216. }
  217. } else {
  218. $this->headers->set($type, $path);
  219. $this->maxlen = 0;
  220. }
  221. } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
  222. // Process the range headers.
  223. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
  224. $range = $request->headers->get('Range');
  225. if (str_starts_with($range, 'bytes=')) {
  226. [$start, $end] = explode('-', substr($range, 6), 2) + [0];
  227. $end = ('' === $end) ? $fileSize - 1 : (int) $end;
  228. if ('' === $start) {
  229. $start = $fileSize - $end;
  230. $end = $fileSize - 1;
  231. } else {
  232. $start = (int) $start;
  233. }
  234. if ($start <= $end) {
  235. $end = min($end, $fileSize - 1);
  236. if ($start < 0 || $start > $end) {
  237. $this->setStatusCode(416);
  238. $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
  239. } elseif ($end - $start < $fileSize - 1) {
  240. $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
  241. $this->offset = $start;
  242. $this->setStatusCode(206);
  243. $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
  244. $this->headers->set('Content-Length', $end - $start + 1);
  245. }
  246. }
  247. }
  248. }
  249. }
  250. return $this;
  251. }
  252. private function hasValidIfRangeHeader(?string $header): bool
  253. {
  254. if ($this->getEtag() === $header) {
  255. return true;
  256. }
  257. if (null === $lastModified = $this->getLastModified()) {
  258. return false;
  259. }
  260. return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
  261. }
  262. /**
  263. * {@inheritdoc}
  264. */
  265. public function sendContent()
  266. {
  267. if (!$this->isSuccessful()) {
  268. return parent::sendContent();
  269. }
  270. if (0 === $this->maxlen) {
  271. return $this;
  272. }
  273. $out = fopen('php://output', 'w');
  274. $file = fopen($this->file->getPathname(), 'r');
  275. ignore_user_abort(true);
  276. if (0 !== $this->offset) {
  277. fseek($file, $this->offset);
  278. }
  279. $length = $this->maxlen;
  280. while ($length && !feof($file)) {
  281. $read = ($length > $this->chunkSize) ? $this->chunkSize : $length;
  282. $length -= $read;
  283. stream_copy_to_stream($file, $out, $read);
  284. if (connection_aborted()) {
  285. break;
  286. }
  287. }
  288. fclose($out);
  289. fclose($file);
  290. if ($this->deleteFileAfterSend && is_file($this->file->getPathname())) {
  291. unlink($this->file->getPathname());
  292. }
  293. return $this;
  294. }
  295. /**
  296. * {@inheritdoc}
  297. *
  298. * @throws \LogicException when the content is not null
  299. */
  300. public function setContent(?string $content)
  301. {
  302. if (null !== $content) {
  303. throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
  304. }
  305. return $this;
  306. }
  307. /**
  308. * {@inheritdoc}
  309. */
  310. public function getContent()
  311. {
  312. return false;
  313. }
  314. /**
  315. * Trust X-Sendfile-Type header.
  316. */
  317. public static function trustXSendfileTypeHeader()
  318. {
  319. self::$trustXSendfileTypeHeader = true;
  320. }
  321. /**
  322. * If this is set to true, the file will be unlinked after the request is sent
  323. * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
  324. *
  325. * @return $this
  326. */
  327. public function deleteFileAfterSend(bool $shouldDelete = true)
  328. {
  329. $this->deleteFileAfterSend = $shouldDelete;
  330. return $this;
  331. }
  332. }