composer package updates
[openemr.git] / vendor / symfony / http-foundation / BinaryFileResponse.php
blob7f1f7ed7e78e9fdb4876399df88fb472be5021f3
1 <?php
3 /*
4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
14 use Symfony\Component\HttpFoundation\File\File;
15 use Symfony\Component\HttpFoundation\File\Exception\FileException;
17 /**
18 * BinaryFileResponse represents an HTTP response delivering a file.
20 * @author Niklas Fiekas <niklas.fiekas@tu-clausthal.de>
21 * @author stealth35 <stealth35-php@live.fr>
22 * @author Igor Wiedler <igor@wiedler.ch>
23 * @author Jordan Alliot <jordan.alliot@gmail.com>
24 * @author Sergey Linnik <linniksa@gmail.com>
26 class BinaryFileResponse extends Response
28 protected static $trustXSendfileTypeHeader = false;
30 /**
31 * @var File
33 protected $file;
34 protected $offset;
35 protected $maxlen;
36 protected $deleteFileAfterSend = false;
38 /**
39 * @param \SplFileInfo|string $file The file to stream
40 * @param int $status The response status code
41 * @param array $headers An array of response headers
42 * @param bool $public Files are public by default
43 * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
44 * @param bool $autoEtag Whether the ETag header should be automatically set
45 * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
47 public function __construct($file, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
49 parent::__construct(null, $status, $headers);
51 $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
53 if ($public) {
54 $this->setPublic();
58 /**
59 * @param \SplFileInfo|string $file The file to stream
60 * @param int $status The response status code
61 * @param array $headers An array of response headers
62 * @param bool $public Files are public by default
63 * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
64 * @param bool $autoEtag Whether the ETag header should be automatically set
65 * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
67 * @return static
69 public static function create($file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
71 return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
74 /**
75 * Sets the file to stream.
77 * @param \SplFileInfo|string $file The file to stream
78 * @param string $contentDisposition
79 * @param bool $autoEtag
80 * @param bool $autoLastModified
82 * @return $this
84 * @throws FileException
86 public function setFile($file, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
88 if (!$file instanceof File) {
89 if ($file instanceof \SplFileInfo) {
90 $file = new File($file->getPathname());
91 } else {
92 $file = new File((string) $file);
96 if (!$file->isReadable()) {
97 throw new FileException('File must be readable.');
100 $this->file = $file;
102 if ($autoEtag) {
103 $this->setAutoEtag();
106 if ($autoLastModified) {
107 $this->setAutoLastModified();
110 if ($contentDisposition) {
111 $this->setContentDisposition($contentDisposition);
114 return $this;
118 * Gets the file.
120 * @return File The file to stream
122 public function getFile()
124 return $this->file;
128 * Automatically sets the Last-Modified header according the file modification date.
130 public function setAutoLastModified()
132 $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
134 return $this;
138 * Automatically sets the ETag header according to the checksum of the file.
140 public function setAutoEtag()
142 $this->setEtag(sha1_file($this->file->getPathname()));
144 return $this;
148 * Sets the Content-Disposition header with the given filename.
150 * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
151 * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file
152 * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
154 * @return $this
156 public function setContentDisposition($disposition, $filename = '', $filenameFallback = '')
158 if ('' === $filename) {
159 $filename = $this->file->getFilename();
162 if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || false !== strpos($filename, '%'))) {
163 $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
165 for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
166 $char = mb_substr($filename, $i, 1, $encoding);
168 if ('%' === $char || ord($char) < 32 || ord($char) > 126) {
169 $filenameFallback .= '_';
170 } else {
171 $filenameFallback .= $char;
176 $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
177 $this->headers->set('Content-Disposition', $dispositionHeader);
179 return $this;
183 * {@inheritdoc}
185 public function prepare(Request $request)
187 $this->headers->set('Content-Length', $this->file->getSize());
189 if (!$this->headers->has('Accept-Ranges')) {
190 // Only accept ranges on safe HTTP methods
191 $this->headers->set('Accept-Ranges', $request->isMethodSafe(false) ? 'bytes' : 'none');
194 if (!$this->headers->has('Content-Type')) {
195 $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
198 if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) {
199 $this->setProtocolVersion('1.1');
202 $this->ensureIEOverSSLCompatibility($request);
204 $this->offset = 0;
205 $this->maxlen = -1;
207 if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
208 // Use X-Sendfile, do not send any content.
209 $type = $request->headers->get('X-Sendfile-Type');
210 $path = $this->file->getRealPath();
211 // Fall back to scheme://path for stream wrapped locations.
212 if (false === $path) {
213 $path = $this->file->getPathname();
215 if ('x-accel-redirect' === strtolower($type)) {
216 // Do X-Accel-Mapping substitutions.
217 // @link http://wiki.nginx.org/X-accel#X-Accel-Redirect
218 foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) {
219 $mapping = explode('=', $mapping, 2);
221 if (2 === count($mapping)) {
222 $pathPrefix = trim($mapping[0]);
223 $location = trim($mapping[1]);
225 if (substr($path, 0, strlen($pathPrefix)) === $pathPrefix) {
226 $path = $location.substr($path, strlen($pathPrefix));
227 break;
232 $this->headers->set($type, $path);
233 $this->maxlen = 0;
234 } elseif ($request->headers->has('Range')) {
235 // Process the range headers.
236 if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
237 $range = $request->headers->get('Range');
238 $fileSize = $this->file->getSize();
240 list($start, $end) = explode('-', substr($range, 6), 2) + array(0);
242 $end = ('' === $end) ? $fileSize - 1 : (int) $end;
244 if ('' === $start) {
245 $start = $fileSize - $end;
246 $end = $fileSize - 1;
247 } else {
248 $start = (int) $start;
251 if ($start <= $end) {
252 if ($start < 0 || $end > $fileSize - 1) {
253 $this->setStatusCode(416);
254 $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
255 } elseif (0 !== $start || $end !== $fileSize - 1) {
256 $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
257 $this->offset = $start;
259 $this->setStatusCode(206);
260 $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
261 $this->headers->set('Content-Length', $end - $start + 1);
267 return $this;
270 private function hasValidIfRangeHeader($header)
272 if ($this->getEtag() === $header) {
273 return true;
276 if (null === $lastModified = $this->getLastModified()) {
277 return false;
280 return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
284 * Sends the file.
286 * {@inheritdoc}
288 public function sendContent()
290 if (!$this->isSuccessful()) {
291 return parent::sendContent();
294 if (0 === $this->maxlen) {
295 return $this;
298 $out = fopen('php://output', 'wb');
299 $file = fopen($this->file->getPathname(), 'rb');
301 stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
303 fclose($out);
304 fclose($file);
306 if ($this->deleteFileAfterSend) {
307 unlink($this->file->getPathname());
310 return $this;
314 * {@inheritdoc}
316 * @throws \LogicException when the content is not null
318 public function setContent($content)
320 if (null !== $content) {
321 throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
326 * {@inheritdoc}
328 * @return false
330 public function getContent()
332 return false;
336 * Trust X-Sendfile-Type header.
338 public static function trustXSendfileTypeHeader()
340 self::$trustXSendfileTypeHeader = true;
344 * If this is set to true, the file will be unlinked after the request is send
345 * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
347 * @param bool $shouldDelete
349 * @return $this
351 public function deleteFileAfterSend($shouldDelete)
353 $this->deleteFileAfterSend = $shouldDelete;
355 return $this;