Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\HttpFoundation; Chris@0: Chris@17: use Symfony\Component\HttpFoundation\File\Exception\FileException; Chris@0: use Symfony\Component\HttpFoundation\File\File; Chris@0: Chris@0: /** Chris@0: * BinaryFileResponse represents an HTTP response delivering a file. Chris@0: * Chris@0: * @author Niklas Fiekas Chris@0: * @author stealth35 Chris@0: * @author Igor Wiedler Chris@0: * @author Jordan Alliot Chris@0: * @author Sergey Linnik Chris@0: */ Chris@0: class BinaryFileResponse extends Response Chris@0: { Chris@0: protected static $trustXSendfileTypeHeader = false; Chris@0: Chris@0: /** Chris@0: * @var File Chris@0: */ Chris@0: protected $file; Chris@17: protected $offset = 0; Chris@17: protected $maxlen = -1; Chris@0: protected $deleteFileAfterSend = false; Chris@0: Chris@0: /** Chris@0: * @param \SplFileInfo|string $file The file to stream Chris@0: * @param int $status The response status code Chris@0: * @param array $headers An array of response headers Chris@0: * @param bool $public Files are public by default Chris@17: * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename Chris@0: * @param bool $autoEtag Whether the ETag header should be automatically set Chris@0: * @param bool $autoLastModified Whether the Last-Modified header should be automatically set Chris@0: */ Chris@17: public function __construct($file, $status = 200, $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) Chris@0: { Chris@0: parent::__construct(null, $status, $headers); Chris@0: Chris@0: $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified); Chris@0: Chris@0: if ($public) { Chris@0: $this->setPublic(); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * @param \SplFileInfo|string $file The file to stream Chris@0: * @param int $status The response status code Chris@0: * @param array $headers An array of response headers Chris@0: * @param bool $public Files are public by default Chris@17: * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename Chris@0: * @param bool $autoEtag Whether the ETag header should be automatically set Chris@0: * @param bool $autoLastModified Whether the Last-Modified header should be automatically set Chris@0: * Chris@0: * @return static Chris@0: */ Chris@17: public static function create($file = null, $status = 200, $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) Chris@0: { Chris@0: return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the file to stream. Chris@0: * Chris@0: * @param \SplFileInfo|string $file The file to stream Chris@0: * @param string $contentDisposition Chris@0: * @param bool $autoEtag Chris@0: * @param bool $autoLastModified Chris@0: * Chris@0: * @return $this Chris@0: * Chris@0: * @throws FileException Chris@0: */ Chris@0: public function setFile($file, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) Chris@0: { Chris@0: if (!$file instanceof File) { Chris@0: if ($file instanceof \SplFileInfo) { Chris@0: $file = new File($file->getPathname()); Chris@0: } else { Chris@0: $file = new File((string) $file); Chris@0: } Chris@0: } Chris@0: Chris@0: if (!$file->isReadable()) { Chris@0: throw new FileException('File must be readable.'); Chris@0: } Chris@0: Chris@0: $this->file = $file; Chris@0: Chris@0: if ($autoEtag) { Chris@0: $this->setAutoEtag(); Chris@0: } Chris@0: Chris@0: if ($autoLastModified) { Chris@0: $this->setAutoLastModified(); Chris@0: } Chris@0: Chris@0: if ($contentDisposition) { Chris@0: $this->setContentDisposition($contentDisposition); Chris@0: } Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the file. Chris@0: * Chris@0: * @return File The file to stream Chris@0: */ Chris@0: public function getFile() Chris@0: { Chris@0: return $this->file; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Automatically sets the Last-Modified header according the file modification date. Chris@0: */ Chris@0: public function setAutoLastModified() Chris@0: { Chris@0: $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime())); Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Automatically sets the ETag header according to the checksum of the file. Chris@0: */ Chris@0: public function setAutoEtag() Chris@0: { Chris@14: $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true))); Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the Content-Disposition header with the given filename. Chris@0: * Chris@0: * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT Chris@14: * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file Chris@0: * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function setContentDisposition($disposition, $filename = '', $filenameFallback = '') Chris@0: { Chris@14: if ('' === $filename) { Chris@0: $filename = $this->file->getFilename(); Chris@0: } Chris@0: Chris@0: if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || false !== strpos($filename, '%'))) { Chris@14: $encoding = mb_detect_encoding($filename, null, true) ?: '8bit'; Chris@0: Chris@0: for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) { Chris@0: $char = mb_substr($filename, $i, 1, $encoding); Chris@0: Chris@17: if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) { Chris@0: $filenameFallback .= '_'; Chris@0: } else { Chris@0: $filenameFallback .= $char; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback); Chris@0: $this->headers->set('Content-Disposition', $dispositionHeader); Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function prepare(Request $request) Chris@0: { Chris@0: if (!$this->headers->has('Content-Type')) { Chris@0: $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream'); Chris@0: } Chris@0: Chris@0: if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) { Chris@0: $this->setProtocolVersion('1.1'); Chris@0: } Chris@0: Chris@0: $this->ensureIEOverSSLCompatibility($request); Chris@0: Chris@0: $this->offset = 0; Chris@0: $this->maxlen = -1; Chris@0: Chris@14: if (false === $fileSize = $this->file->getSize()) { Chris@14: return $this; Chris@14: } Chris@14: $this->headers->set('Content-Length', $fileSize); Chris@14: Chris@14: if (!$this->headers->has('Accept-Ranges')) { Chris@14: // Only accept ranges on safe HTTP methods Chris@14: $this->headers->set('Accept-Ranges', $request->isMethodSafe(false) ? 'bytes' : 'none'); Chris@14: } Chris@14: Chris@0: if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) { Chris@0: // Use X-Sendfile, do not send any content. Chris@0: $type = $request->headers->get('X-Sendfile-Type'); Chris@0: $path = $this->file->getRealPath(); Chris@0: // Fall back to scheme://path for stream wrapped locations. Chris@0: if (false === $path) { Chris@0: $path = $this->file->getPathname(); Chris@0: } Chris@14: if ('x-accel-redirect' === strtolower($type)) { Chris@0: // Do X-Accel-Mapping substitutions. Chris@0: // @link http://wiki.nginx.org/X-accel#X-Accel-Redirect Chris@0: foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) { Chris@0: $mapping = explode('=', $mapping, 2); Chris@0: Chris@17: if (2 === \count($mapping)) { Chris@0: $pathPrefix = trim($mapping[0]); Chris@0: $location = trim($mapping[1]); Chris@0: Chris@17: if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) { Chris@17: $path = $location.substr($path, \strlen($pathPrefix)); Chris@0: break; Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: $this->headers->set($type, $path); Chris@0: $this->maxlen = 0; Chris@0: } elseif ($request->headers->has('Range')) { Chris@0: // Process the range headers. Chris@0: if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) { Chris@0: $range = $request->headers->get('Range'); Chris@0: Chris@17: list($start, $end) = explode('-', substr($range, 6), 2) + [0]; Chris@0: Chris@0: $end = ('' === $end) ? $fileSize - 1 : (int) $end; Chris@0: Chris@0: if ('' === $start) { Chris@0: $start = $fileSize - $end; Chris@0: $end = $fileSize - 1; Chris@0: } else { Chris@0: $start = (int) $start; Chris@0: } Chris@0: Chris@0: if ($start <= $end) { Chris@0: if ($start < 0 || $end > $fileSize - 1) { Chris@0: $this->setStatusCode(416); Chris@0: $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize)); Chris@14: } elseif (0 !== $start || $end !== $fileSize - 1) { Chris@0: $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1; Chris@0: $this->offset = $start; Chris@0: Chris@0: $this->setStatusCode(206); Chris@0: $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize)); Chris@0: $this->headers->set('Content-Length', $end - $start + 1); Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: private function hasValidIfRangeHeader($header) Chris@0: { Chris@0: if ($this->getEtag() === $header) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: if (null === $lastModified = $this->getLastModified()) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: return $lastModified->format('D, d M Y H:i:s').' GMT' === $header; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sends the file. Chris@0: * Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function sendContent() Chris@0: { Chris@0: if (!$this->isSuccessful()) { Chris@0: return parent::sendContent(); Chris@0: } Chris@0: Chris@0: if (0 === $this->maxlen) { Chris@0: return $this; Chris@0: } Chris@0: Chris@0: $out = fopen('php://output', 'wb'); Chris@0: $file = fopen($this->file->getPathname(), 'rb'); Chris@0: Chris@0: stream_copy_to_stream($file, $out, $this->maxlen, $this->offset); Chris@0: Chris@0: fclose($out); Chris@0: fclose($file); Chris@0: Chris@17: if ($this->deleteFileAfterSend && file_exists($this->file->getPathname())) { Chris@0: unlink($this->file->getPathname()); Chris@0: } Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: * Chris@0: * @throws \LogicException when the content is not null Chris@0: */ Chris@0: public function setContent($content) Chris@0: { Chris@0: if (null !== $content) { Chris@0: throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.'); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: * Chris@0: * @return false Chris@0: */ Chris@0: public function getContent() Chris@0: { Chris@0: return false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Trust X-Sendfile-Type header. Chris@0: */ Chris@0: public static function trustXSendfileTypeHeader() Chris@0: { Chris@0: self::$trustXSendfileTypeHeader = true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * If this is set to true, the file will be unlinked after the request is send Chris@0: * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used. Chris@0: * Chris@0: * @param bool $shouldDelete Chris@0: * Chris@0: * @return $this Chris@0: */ Chris@0: public function deleteFileAfterSend($shouldDelete) Chris@0: { Chris@0: $this->deleteFileAfterSend = $shouldDelete; Chris@0: Chris@0: return $this; Chris@0: } Chris@0: }