BinaryFileResponse.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-redirect
  208. $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
  209. foreach ($parts as $part) {
  210. [$pathPrefix, $location] = $part;
  211. if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
  212. $path = $location.substr($path, \strlen($pathPrefix));
  213. // Only set X-Accel-Redirect header if a valid URI can be produced
  214. // as nginx does not serve arbitrary file paths.
  215. $this->headers->set($type, $path);
  216. $this->maxlen = 0;
  217. break;
  218. }
  219. }
  220. } else {
  221. $this->headers->set($type, $path);
  222. $this->maxlen = 0;
  223. }
  224. } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
  225. // Process the range headers.
  226. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
  227. $range = $request->headers->get('Range');
  228. if (str_starts_with($range, 'bytes=')) {
  229. [$start, $end] = explode('-', substr($range, 6), 2) + [1 => 0];
  230. $end = ('' === $end) ? $fileSize - 1 : (int) $end;
  231. if ('' === $start) {
  232. $start = $fileSize - $end;
  233. $end = $fileSize - 1;
  234. } else {
  235. $start = (int) $start;
  236. }
  237. if ($start <= $end) {
  238. $end = min($end, $fileSize - 1);
  239. if ($start < 0 || $start > $end) {
  240. $this->setStatusCode(416);
  241. $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
  242. } elseif ($end - $start < $fileSize - 1) {
  243. $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
  244. $this->offset = $start;
  245. $this->setStatusCode(206);
  246. $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
  247. $this->headers->set('Content-Length', $end - $start + 1);
  248. }
  249. }
  250. }
  251. }
  252. }
  253. if ($request->isMethod('HEAD')) {
  254. $this->maxlen = 0;
  255. }
  256. return $this;
  257. }
  258. private function hasValidIfRangeHeader(?string $header): bool
  259. {
  260. if ($this->getEtag() === $header) {
  261. return true;
  262. }
  263. if (null === $lastModified = $this->getLastModified()) {
  264. return false;
  265. }
  266. return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
  267. }
  268. /**
  269. * {@inheritdoc}
  270. */
  271. public function sendContent()
  272. {
  273. try {
  274. if (!$this->isSuccessful()) {
  275. return parent::sendContent();
  276. }
  277. if (0 === $this->maxlen) {
  278. return $this;
  279. }
  280. $out = fopen('php://output', 'w');
  281. $file = fopen($this->file->getPathname(), 'r');
  282. ignore_user_abort(true);
  283. if (0 !== $this->offset) {
  284. fseek($file, $this->offset);
  285. }
  286. $length = $this->maxlen;
  287. while ($length && !feof($file)) {
  288. $read = $length > $this->chunkSize || 0 > $length ? $this->chunkSize : $length;
  289. if (false === $data = fread($file, $read)) {
  290. break;
  291. }
  292. while ('' !== $data) {
  293. $read = fwrite($out, $data);
  294. if (false === $read || connection_aborted()) {
  295. break 2;
  296. }
  297. if (0 < $length) {
  298. $length -= $read;
  299. }
  300. $data = substr($data, $read);
  301. }
  302. }
  303. fclose($out);
  304. fclose($file);
  305. } finally {
  306. if ($this->deleteFileAfterSend && is_file($this->file->getPathname())) {
  307. unlink($this->file->getPathname());
  308. }
  309. }
  310. return $this;
  311. }
  312. /**
  313. * {@inheritdoc}
  314. *
  315. * @throws \LogicException when the content is not null
  316. */
  317. public function setContent(?string $content)
  318. {
  319. if (null !== $content) {
  320. throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
  321. }
  322. return $this;
  323. }
  324. /**
  325. * {@inheritdoc}
  326. */
  327. public function getContent()
  328. {
  329. return false;
  330. }
  331. /**
  332. * Trust X-Sendfile-Type header.
  333. */
  334. public static function trustXSendfileTypeHeader()
  335. {
  336. self::$trustXSendfileTypeHeader = true;
  337. }
  338. /**
  339. * If this is set to true, the file will be unlinked after the request is sent
  340. * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
  341. *
  342. * @return $this
  343. */
  344. public function deleteFileAfterSend(bool $shouldDelete = true)
  345. {
  346. $this->deleteFileAfterSend = $shouldDelete;
  347. return $this;
  348. }
  349. }