BinaryFileResponse.php 8.5 KB

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