You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

365 lines
12 KiB

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