BinaryFileResponse.php 12 KB

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