Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/BinaryFileResponse.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation;
13
14 use Symfony\Component\HttpFoundation\File\Exception\FileException;
15 use Symfony\Component\HttpFoundation\File\File;
16
17 /**
18 * BinaryFileResponse represents an HTTP response delivering a file.
19 *
20 * @author Niklas Fiekas <[email protected]>
21 * @author stealth35 <[email protected]>
22 * @author Igor Wiedler <[email protected]>
23 * @author Jordan Alliot <[email protected]>
24 * @author Sergey Linnik <[email protected]>
25 */
26 class BinaryFileResponse extends Response
27 {
28 protected static bool $trustXSendfileTypeHeader = false;
29
30 protected File $file;
31 protected ?\SplTempFileObject $tempFileObject = null;
32 protected int $offset = 0;
33 protected int $maxlen = -1;
34 protected bool $deleteFileAfterSend = false;
35 protected int $chunkSize = 16 * 1024;
36
37 /**
38 * @param \SplFileInfo|string $file The file to stream
39 * @param int $status The response status code (200 "OK" by default)
40 * @param array $headers An array of response headers
41 * @param bool $public Files are public by default
42 * @param string|null $contentDisposition The type of Content-Disposition to set automatically with the filename
43 * @param bool $autoEtag Whether the ETag header should be automatically set
44 * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
45 */
46 public function __construct(\SplFileInfo|string $file, int $status = 200, array $headers = [], bool $public = true, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
47 {
48 parent::__construct(null, $status, $headers);
49
50 $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
51
52 if ($public) {
53 $this->setPublic();
54 }
55 }
56
57 /**
58 * Sets the file to stream.
59 *
60 * @return $this
61 *
62 * @throws FileException
63 */
64 public function setFile(\SplFileInfo|string $file, ?string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true): static
65 {
66 $isTemporaryFile = $file instanceof \SplTempFileObject;
67 $this->tempFileObject = $isTemporaryFile ? $file : null;
68
69 if (!$file instanceof File) {
70 if ($file instanceof \SplFileInfo) {
71 $file = new File($file->getPathname(), !$isTemporaryFile);
72 } else {
73 $file = new File($file);
74 }
75 }
76
77 if (!$file->isReadable() && !$isTemporaryFile) {
78 throw new FileException('File must be readable.');
79 }
80
81 $this->file = $file;
82
83 if ($autoEtag) {
84 $this->setAutoEtag();
85 }
86
87 if ($autoLastModified && !$isTemporaryFile) {
88 $this->setAutoLastModified();
89 }
90
91 if ($contentDisposition) {
92 $this->setContentDisposition($contentDisposition);
93 }
94
95 return $this;
96 }
97
98 /**
99 * Gets the file.
100 */
101 public function getFile(): File
102 {
103 return $this->file;
104 }
105
106 /**
107 * Sets the response stream chunk size.
108 *
109 * @return $this
110 */
111 public function setChunkSize(int $chunkSize): static
112 {
113 if ($chunkSize < 1) {
114 throw new \InvalidArgumentException('The chunk size of a BinaryFileResponse cannot be less than 1.');
115 }
116
117 $this->chunkSize = $chunkSize;
118
119 return $this;
120 }
121
122 /**
123 * Automatically sets the Last-Modified header according the file modification date.
124 *
125 * @return $this
126 */
127 public function setAutoLastModified(): static
128 {
129 $this->setLastModified(\DateTimeImmutable::createFromFormat('U', $this->tempFileObject ? time() : $this->file->getMTime()));
130
131 return $this;
132 }
133
134 /**
135 * Automatically sets the ETag header according to the checksum of the file.
136 *
137 * @return $this
138 */
139 public function setAutoEtag(): static
140 {
141 $this->setEtag(base64_encode(hash_file('xxh128', $this->file->getPathname(), true)));
142
143 return $this;
144 }
145
146 /**
147 * Sets the Content-Disposition header with the given filename.
148 *
149 * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
150 * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file
151 * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
152 *
153 * @return $this
154 */
155 public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = ''): static
156 {
157 if ('' === $filename) {
158 $filename = $this->file->getFilename();
159 }
160
161 if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) {
162 $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
163
164 for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
165 $char = mb_substr($filename, $i, 1, $encoding);
166
167 if ('%' === $char || \ord($char[0]) < 32 || \ord($char[0]) > 126) {
168 $filenameFallback .= '_';
169 } else {
170 $filenameFallback .= $char;
171 }
172 }
173 }
174
175 $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
176 $this->headers->set('Content-Disposition', $dispositionHeader);
177
178 return $this;
179 }
180
181 public function prepare(Request $request): static
182 {
183 if ($this->isInformational() || $this->isEmpty()) {
184 parent::prepare($request);
185
186 $this->maxlen = 0;
187
188 return $this;
189 }
190
191 if (!$this->headers->has('Content-Type')) {
192 $mimeType = null;
193 if (!$this->tempFileObject) {
194 $mimeType = $this->file->getMimeType();
195 }
196
197 $this->headers->set('Content-Type', $mimeType ?: 'application/octet-stream');
198 }
199
200 parent::prepare($request);
201
202 $this->offset = 0;
203 $this->maxlen = -1;
204
205 if ($this->tempFileObject) {
206 $fileSize = $this->tempFileObject->fstat()['size'];
207 } elseif (false === $fileSize = $this->file->getSize()) {
208 return $this;
209 }
210 $this->headers->remove('Transfer-Encoding');
211 $this->headers->set('Content-Length', $fileSize);
212
213 if (!$this->headers->has('Accept-Ranges')) {
214 // Only accept ranges on safe HTTP methods
215 $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
216 }
217
218 if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
219 // Use X-Sendfile, do not send any content.
220 $type = $request->headers->get('X-Sendfile-Type');
221 $path = $this->file->getRealPath();
222 // Fall back to scheme://path for stream wrapped locations.
223 if (false === $path) {
224 $path = $this->file->getPathname();
225 }
226 if ('x-accel-redirect' === strtolower($type)) {
227 // Do X-Accel-Mapping substitutions.
228 // @link https://github.com/rack/rack/blob/main/lib/rack/sendfile.rb
229 // @link https://mattbrictson.com/blog/accelerated-rails-downloads
230 if (!$request->headers->has('X-Accel-Mapping')) {
231 throw new \LogicException('The "X-Accel-Mapping" header must be set when "X-Sendfile-Type" is set to "X-Accel-Redirect".');
232 }
233 $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping'), ',=');
234 foreach ($parts as $part) {
235 [$pathPrefix, $location] = $part;
236 if (str_starts_with($path, $pathPrefix)) {
237 $path = $location.substr($path, \strlen($pathPrefix));
238 // Only set X-Accel-Redirect header if a valid URI can be produced
239 // as nginx does not serve arbitrary file paths.
240 $this->headers->set($type, rawurlencode($path));
241 $this->maxlen = 0;
242 break;
243 }
244 }
245 } else {
246 $this->headers->set($type, $path);
247 $this->maxlen = 0;
248 }
249 } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
250 // Process the range headers.
251 if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
252 $range = $request->headers->get('Range');
253
254 if (str_starts_with($range, 'bytes=')) {
255 [$start, $end] = explode('-', substr($range, 6), 2) + [1 => 0];
256
257 $end = ('' === $end) ? $fileSize - 1 : (int) $end;
258
259 if ('' === $start) {
260 $start = $fileSize - $end;
261 $end = $fileSize - 1;
262 } else {
263 $start = (int) $start;
264 }
265
266 if ($start <= $end) {
267 $end = min($end, $fileSize - 1);
268 if ($start < 0 || $start > $end) {
269 $this->setStatusCode(416);
270 $this->headers->set('Content-Range', \sprintf('bytes */%s', $fileSize));
271 } else {
272 $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
273 $this->offset = $start;
274
275 $this->setStatusCode(206);
276 $this->headers->set('Content-Range', \sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
277 $this->headers->set('Content-Length', $end - $start + 1);
278 }
279 }
280 }
281 }
282 }
283
284 if ($request->isMethod('HEAD')) {
285 $this->maxlen = 0;
286 }
287
288 return $this;
289 }
290
291 private function hasValidIfRangeHeader(?string $header): bool
292 {
293 if ($this->getEtag() === $header) {
294 return true;
295 }
296
297 if (null === $lastModified = $this->getLastModified()) {
298 return false;
299 }
300
301 return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
302 }
303
304 public function sendContent(): static
305 {
306 try {
307 if (!$this->isSuccessful()) {
308 return $this;
309 }
310
311 if (0 === $this->maxlen) {
312 return $this;
313 }
314
315 $out = fopen('php://output', 'w');
316
317 if ($this->tempFileObject) {
318 $file = $this->tempFileObject;
319 $file->rewind();
320 } else {
321 $file = new \SplFileObject($this->file->getPathname(), 'r');
322 }
323
324 ignore_user_abort(true);
325
326 if (0 !== $this->offset) {
327 $file->fseek($this->offset);
328 }
329
330 $length = $this->maxlen;
331 while ($length && !$file->eof()) {
332 $read = $length > $this->chunkSize || 0 > $length ? $this->chunkSize : $length;
333
334 if (false === $data = $file->fread($read)) {
335 break;
336 }
337 while ('' !== $data) {
338 $read = fwrite($out, $data);
339 if (false === $read || connection_aborted()) {
340 break 2;
341 }
342 if (0 < $length) {
343 $length -= $read;
344 }
345 $data = substr($data, $read);
346 }
347 }
348
349 fclose($out);
350 } finally {
351 if (null === $this->tempFileObject && $this->deleteFileAfterSend && is_file($this->file->getPathname())) {
352 unlink($this->file->getPathname());
353 }
354 }
355
356 return $this;
357 }
358
359 /**
360 * @throws \LogicException when the content is not null
361 */
362 public function setContent(?string $content): static
363 {
364 if (null !== $content) {
365 throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
366 }
367
368 return $this;
369 }
370
371 public function getContent(): string|false
372 {
373 return false;
374 }
375
376 /**
377 * Trust X-Sendfile-Type header.
378 */
379 public static function trustXSendfileTypeHeader(): void
380 {
381 self::$trustXSendfileTypeHeader = true;
382 }
383
384 /**
385 * If this is set to true, the file will be unlinked after the request is sent
386 * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
387 *
388 * @return $this
389 */
390 public function deleteFileAfterSend(bool $shouldDelete = true): static
391 {
392 $this->deleteFileAfterSend = $shouldDelete;
393
394 return $this;
395 }
396 }