Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

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