No Description

BinaryFileResponse.php 10KB

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