annotate vendor/symfony/http-foundation/BinaryFileResponse.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents 129ea1e6d783
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of the Symfony package.
Chris@0 5 *
Chris@0 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Symfony\Component\HttpFoundation;
Chris@0 13
Chris@17 14 use Symfony\Component\HttpFoundation\File\Exception\FileException;
Chris@0 15 use Symfony\Component\HttpFoundation\File\File;
Chris@0 16
Chris@0 17 /**
Chris@0 18 * BinaryFileResponse represents an HTTP response delivering a file.
Chris@0 19 *
Chris@0 20 * @author Niklas Fiekas <niklas.fiekas@tu-clausthal.de>
Chris@0 21 * @author stealth35 <stealth35-php@live.fr>
Chris@0 22 * @author Igor Wiedler <igor@wiedler.ch>
Chris@0 23 * @author Jordan Alliot <jordan.alliot@gmail.com>
Chris@0 24 * @author Sergey Linnik <linniksa@gmail.com>
Chris@0 25 */
Chris@0 26 class BinaryFileResponse extends Response
Chris@0 27 {
Chris@0 28 protected static $trustXSendfileTypeHeader = false;
Chris@0 29
Chris@0 30 /**
Chris@0 31 * @var File
Chris@0 32 */
Chris@0 33 protected $file;
Chris@17 34 protected $offset = 0;
Chris@17 35 protected $maxlen = -1;
Chris@0 36 protected $deleteFileAfterSend = false;
Chris@0 37
Chris@0 38 /**
Chris@0 39 * @param \SplFileInfo|string $file The file to stream
Chris@0 40 * @param int $status The response status code
Chris@0 41 * @param array $headers An array of response headers
Chris@0 42 * @param bool $public Files are public by default
Chris@17 43 * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
Chris@0 44 * @param bool $autoEtag Whether the ETag header should be automatically set
Chris@0 45 * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
Chris@0 46 */
Chris@17 47 public function __construct($file, $status = 200, $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
Chris@0 48 {
Chris@0 49 parent::__construct(null, $status, $headers);
Chris@0 50
Chris@0 51 $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
Chris@0 52
Chris@0 53 if ($public) {
Chris@0 54 $this->setPublic();
Chris@0 55 }
Chris@0 56 }
Chris@0 57
Chris@0 58 /**
Chris@0 59 * @param \SplFileInfo|string $file The file to stream
Chris@0 60 * @param int $status The response status code
Chris@0 61 * @param array $headers An array of response headers
Chris@0 62 * @param bool $public Files are public by default
Chris@17 63 * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
Chris@0 64 * @param bool $autoEtag Whether the ETag header should be automatically set
Chris@0 65 * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
Chris@0 66 *
Chris@0 67 * @return static
Chris@0 68 */
Chris@17 69 public static function create($file = null, $status = 200, $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
Chris@0 70 {
Chris@0 71 return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
Chris@0 72 }
Chris@0 73
Chris@0 74 /**
Chris@0 75 * Sets the file to stream.
Chris@0 76 *
Chris@0 77 * @param \SplFileInfo|string $file The file to stream
Chris@0 78 * @param string $contentDisposition
Chris@0 79 * @param bool $autoEtag
Chris@0 80 * @param bool $autoLastModified
Chris@0 81 *
Chris@0 82 * @return $this
Chris@0 83 *
Chris@0 84 * @throws FileException
Chris@0 85 */
Chris@0 86 public function setFile($file, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
Chris@0 87 {
Chris@0 88 if (!$file instanceof File) {
Chris@0 89 if ($file instanceof \SplFileInfo) {
Chris@0 90 $file = new File($file->getPathname());
Chris@0 91 } else {
Chris@0 92 $file = new File((string) $file);
Chris@0 93 }
Chris@0 94 }
Chris@0 95
Chris@0 96 if (!$file->isReadable()) {
Chris@0 97 throw new FileException('File must be readable.');
Chris@0 98 }
Chris@0 99
Chris@0 100 $this->file = $file;
Chris@0 101
Chris@0 102 if ($autoEtag) {
Chris@0 103 $this->setAutoEtag();
Chris@0 104 }
Chris@0 105
Chris@0 106 if ($autoLastModified) {
Chris@0 107 $this->setAutoLastModified();
Chris@0 108 }
Chris@0 109
Chris@0 110 if ($contentDisposition) {
Chris@0 111 $this->setContentDisposition($contentDisposition);
Chris@0 112 }
Chris@0 113
Chris@0 114 return $this;
Chris@0 115 }
Chris@0 116
Chris@0 117 /**
Chris@0 118 * Gets the file.
Chris@0 119 *
Chris@0 120 * @return File The file to stream
Chris@0 121 */
Chris@0 122 public function getFile()
Chris@0 123 {
Chris@0 124 return $this->file;
Chris@0 125 }
Chris@0 126
Chris@0 127 /**
Chris@0 128 * Automatically sets the Last-Modified header according the file modification date.
Chris@0 129 */
Chris@0 130 public function setAutoLastModified()
Chris@0 131 {
Chris@0 132 $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
Chris@0 133
Chris@0 134 return $this;
Chris@0 135 }
Chris@0 136
Chris@0 137 /**
Chris@0 138 * Automatically sets the ETag header according to the checksum of the file.
Chris@0 139 */
Chris@0 140 public function setAutoEtag()
Chris@0 141 {
Chris@14 142 $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));
Chris@0 143
Chris@0 144 return $this;
Chris@0 145 }
Chris@0 146
Chris@0 147 /**
Chris@0 148 * Sets the Content-Disposition header with the given filename.
Chris@0 149 *
Chris@0 150 * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
Chris@14 151 * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file
Chris@0 152 * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
Chris@0 153 *
Chris@0 154 * @return $this
Chris@0 155 */
Chris@0 156 public function setContentDisposition($disposition, $filename = '', $filenameFallback = '')
Chris@0 157 {
Chris@14 158 if ('' === $filename) {
Chris@0 159 $filename = $this->file->getFilename();
Chris@0 160 }
Chris@0 161
Chris@0 162 if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || false !== strpos($filename, '%'))) {
Chris@14 163 $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
Chris@0 164
Chris@0 165 for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
Chris@0 166 $char = mb_substr($filename, $i, 1, $encoding);
Chris@0 167
Chris@17 168 if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
Chris@0 169 $filenameFallback .= '_';
Chris@0 170 } else {
Chris@0 171 $filenameFallback .= $char;
Chris@0 172 }
Chris@0 173 }
Chris@0 174 }
Chris@0 175
Chris@0 176 $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
Chris@0 177 $this->headers->set('Content-Disposition', $dispositionHeader);
Chris@0 178
Chris@0 179 return $this;
Chris@0 180 }
Chris@0 181
Chris@0 182 /**
Chris@0 183 * {@inheritdoc}
Chris@0 184 */
Chris@0 185 public function prepare(Request $request)
Chris@0 186 {
Chris@0 187 if (!$this->headers->has('Content-Type')) {
Chris@0 188 $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
Chris@0 189 }
Chris@0 190
Chris@0 191 if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) {
Chris@0 192 $this->setProtocolVersion('1.1');
Chris@0 193 }
Chris@0 194
Chris@0 195 $this->ensureIEOverSSLCompatibility($request);
Chris@0 196
Chris@0 197 $this->offset = 0;
Chris@0 198 $this->maxlen = -1;
Chris@0 199
Chris@14 200 if (false === $fileSize = $this->file->getSize()) {
Chris@14 201 return $this;
Chris@14 202 }
Chris@14 203 $this->headers->set('Content-Length', $fileSize);
Chris@14 204
Chris@14 205 if (!$this->headers->has('Accept-Ranges')) {
Chris@14 206 // Only accept ranges on safe HTTP methods
Chris@14 207 $this->headers->set('Accept-Ranges', $request->isMethodSafe(false) ? 'bytes' : 'none');
Chris@14 208 }
Chris@14 209
Chris@0 210 if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
Chris@0 211 // Use X-Sendfile, do not send any content.
Chris@0 212 $type = $request->headers->get('X-Sendfile-Type');
Chris@0 213 $path = $this->file->getRealPath();
Chris@0 214 // Fall back to scheme://path for stream wrapped locations.
Chris@0 215 if (false === $path) {
Chris@0 216 $path = $this->file->getPathname();
Chris@0 217 }
Chris@14 218 if ('x-accel-redirect' === strtolower($type)) {
Chris@0 219 // Do X-Accel-Mapping substitutions.
Chris@0 220 // @link http://wiki.nginx.org/X-accel#X-Accel-Redirect
Chris@0 221 foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) {
Chris@0 222 $mapping = explode('=', $mapping, 2);
Chris@0 223
Chris@17 224 if (2 === \count($mapping)) {
Chris@0 225 $pathPrefix = trim($mapping[0]);
Chris@0 226 $location = trim($mapping[1]);
Chris@0 227
Chris@17 228 if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
Chris@17 229 $path = $location.substr($path, \strlen($pathPrefix));
Chris@0 230 break;
Chris@0 231 }
Chris@0 232 }
Chris@0 233 }
Chris@0 234 }
Chris@0 235 $this->headers->set($type, $path);
Chris@0 236 $this->maxlen = 0;
Chris@0 237 } elseif ($request->headers->has('Range')) {
Chris@0 238 // Process the range headers.
Chris@0 239 if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
Chris@0 240 $range = $request->headers->get('Range');
Chris@0 241
Chris@17 242 list($start, $end) = explode('-', substr($range, 6), 2) + [0];
Chris@0 243
Chris@0 244 $end = ('' === $end) ? $fileSize - 1 : (int) $end;
Chris@0 245
Chris@0 246 if ('' === $start) {
Chris@0 247 $start = $fileSize - $end;
Chris@0 248 $end = $fileSize - 1;
Chris@0 249 } else {
Chris@0 250 $start = (int) $start;
Chris@0 251 }
Chris@0 252
Chris@0 253 if ($start <= $end) {
Chris@0 254 if ($start < 0 || $end > $fileSize - 1) {
Chris@0 255 $this->setStatusCode(416);
Chris@0 256 $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
Chris@14 257 } elseif (0 !== $start || $end !== $fileSize - 1) {
Chris@0 258 $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
Chris@0 259 $this->offset = $start;
Chris@0 260
Chris@0 261 $this->setStatusCode(206);
Chris@0 262 $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
Chris@0 263 $this->headers->set('Content-Length', $end - $start + 1);
Chris@0 264 }
Chris@0 265 }
Chris@0 266 }
Chris@0 267 }
Chris@0 268
Chris@0 269 return $this;
Chris@0 270 }
Chris@0 271
Chris@0 272 private function hasValidIfRangeHeader($header)
Chris@0 273 {
Chris@0 274 if ($this->getEtag() === $header) {
Chris@0 275 return true;
Chris@0 276 }
Chris@0 277
Chris@0 278 if (null === $lastModified = $this->getLastModified()) {
Chris@0 279 return false;
Chris@0 280 }
Chris@0 281
Chris@0 282 return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
Chris@0 283 }
Chris@0 284
Chris@0 285 /**
Chris@0 286 * Sends the file.
Chris@0 287 *
Chris@0 288 * {@inheritdoc}
Chris@0 289 */
Chris@0 290 public function sendContent()
Chris@0 291 {
Chris@0 292 if (!$this->isSuccessful()) {
Chris@0 293 return parent::sendContent();
Chris@0 294 }
Chris@0 295
Chris@0 296 if (0 === $this->maxlen) {
Chris@0 297 return $this;
Chris@0 298 }
Chris@0 299
Chris@0 300 $out = fopen('php://output', 'wb');
Chris@0 301 $file = fopen($this->file->getPathname(), 'rb');
Chris@0 302
Chris@0 303 stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
Chris@0 304
Chris@0 305 fclose($out);
Chris@0 306 fclose($file);
Chris@0 307
Chris@17 308 if ($this->deleteFileAfterSend && file_exists($this->file->getPathname())) {
Chris@0 309 unlink($this->file->getPathname());
Chris@0 310 }
Chris@0 311
Chris@0 312 return $this;
Chris@0 313 }
Chris@0 314
Chris@0 315 /**
Chris@0 316 * {@inheritdoc}
Chris@0 317 *
Chris@0 318 * @throws \LogicException when the content is not null
Chris@0 319 */
Chris@0 320 public function setContent($content)
Chris@0 321 {
Chris@0 322 if (null !== $content) {
Chris@0 323 throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
Chris@0 324 }
Chris@0 325 }
Chris@0 326
Chris@0 327 /**
Chris@0 328 * {@inheritdoc}
Chris@0 329 *
Chris@0 330 * @return false
Chris@0 331 */
Chris@0 332 public function getContent()
Chris@0 333 {
Chris@0 334 return false;
Chris@0 335 }
Chris@0 336
Chris@0 337 /**
Chris@0 338 * Trust X-Sendfile-Type header.
Chris@0 339 */
Chris@0 340 public static function trustXSendfileTypeHeader()
Chris@0 341 {
Chris@0 342 self::$trustXSendfileTypeHeader = true;
Chris@0 343 }
Chris@0 344
Chris@0 345 /**
Chris@0 346 * If this is set to true, the file will be unlinked after the request is send
Chris@0 347 * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
Chris@0 348 *
Chris@0 349 * @param bool $shouldDelete
Chris@0 350 *
Chris@0 351 * @return $this
Chris@0 352 */
Chris@0 353 public function deleteFileAfterSend($shouldDelete)
Chris@0 354 {
Chris@0 355 $this->deleteFileAfterSend = $shouldDelete;
Chris@0 356
Chris@0 357 return $this;
Chris@0 358 }
Chris@0 359 }