BinaryFileResponse.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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->ensureIEOverSSLCompatibility($request);
  142. $this->offset = 0;
  143. $this->maxlen = -1;
  144. if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
  145. // Use X-Sendfile, do not send any content.
  146. $type = $request->headers->get('X-Sendfile-Type');
  147. $path = $this->file->getRealPath();
  148. if (strtolower($type) == 'x-accel-redirect') {
  149. // Do X-Accel-Mapping substitutions.
  150. foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) {
  151. $mapping = explode('=', $mapping, 2);
  152. if (2 == count($mapping)) {
  153. $location = trim($mapping[0]);
  154. $pathPrefix = trim($mapping[1]);
  155. if (substr($path, 0, strlen($pathPrefix)) == $pathPrefix) {
  156. $path = $location.substr($path, strlen($pathPrefix));
  157. break;
  158. }
  159. }
  160. }
  161. }
  162. $this->headers->set($type, $path);
  163. $this->maxlen = 0;
  164. } elseif ($request->headers->has('Range')) {
  165. // Process the range headers.
  166. if (!$request->headers->has('If-Range') || $this->getEtag() == $request->headers->get('If-Range')) {
  167. $range = $request->headers->get('Range');
  168. $fileSize = $this->file->getSize();
  169. list($start, $end) = explode('-', substr($range, 6), 2) + array(0);
  170. $end = ('' === $end) ? $fileSize - 1 : (int) $end;
  171. if ('' === $start) {
  172. $start = $fileSize - $end;
  173. $end = $fileSize - 1;
  174. } else {
  175. $start = (int) $start;
  176. }
  177. $start = max($start, 0);
  178. $end = min($end, $fileSize - 1);
  179. $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
  180. $this->offset = $start;
  181. $this->setStatusCode(206);
  182. $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
  183. }
  184. }
  185. return $this;
  186. }
  187. /**
  188. * Sends the file.
  189. */
  190. public function sendContent()
  191. {
  192. if (!$this->isSuccessful()) {
  193. parent::sendContent();
  194. return;
  195. }
  196. if (0 === $this->maxlen) {
  197. return;
  198. }
  199. $out = fopen('php://output', 'wb');
  200. $file = fopen($this->file->getPathname(), 'rb');
  201. stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
  202. fclose($out);
  203. fclose($file);
  204. }
  205. /**
  206. * {@inheritdoc}
  207. *
  208. * @throws \LogicException when the content is not null
  209. */
  210. public function setContent($content)
  211. {
  212. if (null !== $content) {
  213. throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
  214. }
  215. }
  216. /**
  217. * {@inheritdoc}
  218. *
  219. * @return false
  220. */
  221. public function getContent()
  222. {
  223. return false;
  224. }
  225. /**
  226. * Trust X-Sendfile-Type header.
  227. */
  228. public static function trustXSendfileTypeHeader()
  229. {
  230. self::$trustXSendfileTypeHeader = true;
  231. }
  232. }