BinaryFileResponse.php 11 KB

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