Subversion Repositories php-qbpwcf

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 liveuser 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;
37
 
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 string|null         $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
46
     */
47
    public function __construct($file, int $status = 200, array $headers = [], bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
48
    {
49
        parent::__construct(null, $status, $headers);
50
 
51
        $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
52
 
53
        if ($public) {
54
            $this->setPublic();
55
        }
56
    }
57
 
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 string|null         $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
66
     *
67
     * @return static
68
     */
69
    public static function create($file = null, int $status = 200, array $headers = [], bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
70
    {
71
        return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
72
    }
73
 
74
    /**
75
     * Sets the file to stream.
76
     *
77
     * @param \SplFileInfo|string $file The file to stream
78
     *
79
     * @return $this
80
     *
81
     * @throws FileException
82
     */
83
    public function setFile($file, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
84
    {
85
        if (!$file instanceof File) {
86
            if ($file instanceof \SplFileInfo) {
87
                $file = new File($file->getPathname());
88
            } else {
89
                $file = new File((string) $file);
90
            }
91
        }
92
 
93
        if (!$file->isReadable()) {
94
            throw new FileException('File must be readable.');
95
        }
96
 
97
        $this->file = $file;
98
 
99
        if ($autoEtag) {
100
            $this->setAutoEtag();
101
        }
102
 
103
        if ($autoLastModified) {
104
            $this->setAutoLastModified();
105
        }
106
 
107
        if ($contentDisposition) {
108
            $this->setContentDisposition($contentDisposition);
109
        }
110
 
111
        return $this;
112
    }
113
 
114
    /**
115
     * Gets the file.
116
     *
117
     * @return File The file to stream
118
     */
119
    public function getFile()
120
    {
121
        return $this->file;
122
    }
123
 
124
    /**
125
     * Automatically sets the Last-Modified header according the file modification date.
126
     */
127
    public function setAutoLastModified()
128
    {
129
        $this->setLastModified(\DateTime::createFromFormat('U', $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
    public function setAutoEtag()
138
    {
139
        $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));
140
 
141
        return $this;
142
    }
143
 
144
    /**
145
     * Sets the Content-Disposition header with the given filename.
146
     *
147
     * @param string $disposition      ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
148
     * @param string $filename         Optionally use this UTF-8 encoded filename instead of the real name of the file
149
     * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
150
     *
151
     * @return $this
152
     */
153
    public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = '')
154
    {
155
        if ('' === $filename) {
156
            $filename = $this->file->getFilename();
157
        }
158
 
159
        if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || false !== strpos($filename, '%'))) {
160
            $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
161
 
162
            for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
163
                $char = mb_substr($filename, $i, 1, $encoding);
164
 
165
                if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
166
                    $filenameFallback .= '_';
167
                } else {
168
                    $filenameFallback .= $char;
169
                }
170
            }
171
        }
172
 
173
        $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
174
        $this->headers->set('Content-Disposition', $dispositionHeader);
175
 
176
        return $this;
177
    }
178
 
179
    /**
180
     * {@inheritdoc}
181
     */
182
    public function prepare(Request $request)
183
    {
184
        if (!$this->headers->has('Content-Type')) {
185
            $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
186
        }
187
 
188
        if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) {
189
            $this->setProtocolVersion('1.1');
190
        }
191
 
192
        $this->ensureIEOverSSLCompatibility($request);
193
 
194
        $this->offset = 0;
195
        $this->maxlen = -1;
196
 
197
        if (false === $fileSize = $this->file->getSize()) {
198
            return $this;
199
        }
200
        $this->headers->set('Content-Length', $fileSize);
201
 
202
        if (!$this->headers->has('Accept-Ranges')) {
203
            // Only accept ranges on safe HTTP methods
204
            $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none');
205
        }
206
 
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();
214
            }
215
            if ('x-accel-redirect' === strtolower($type)) {
216
                // Do X-Accel-Mapping substitutions.
217
                // @link https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-redirect
218
                $parts = HeaderUtils::split($request->headers->get('X-Accel-Mapping', ''), ',=');
219
                foreach ($parts as $part) {
220
                    list($pathPrefix, $location) = $part;
221
                    if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix) {
222
                        $path = $location.substr($path, \strlen($pathPrefix));
223
                        // Only set X-Accel-Redirect header if a valid URI can be produced
224
                        // as nginx does not serve arbitrary file paths.
225
                        $this->headers->set($type, $path);
226
                        $this->maxlen = 0;
227
                        break;
228
                    }
229
                }
230
            } else {
231
                $this->headers->set($type, $path);
232
                $this->maxlen = 0;
233
            }
234
        } elseif ($request->headers->has('Range') && $request->isMethod('GET')) {
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
 
239
                if (0 === strpos($range, 'bytes=')) {
240
                    list($start, $end) = explode('-', substr($range, 6), 2) + [0];
241
 
242
                    $end = ('' === $end) ? $fileSize - 1 : (int) $end;
243
 
244
                    if ('' === $start) {
245
                        $start = $fileSize - $end;
246
                        $end = $fileSize - 1;
247
                    } else {
248
                        $start = (int) $start;
249
                    }
250
 
251
                    if ($start <= $end) {
252
                        $end = min($end, $fileSize - 1);
253
                        if ($start < 0 || $start > $end) {
254
                            $this->setStatusCode(416);
255
                            $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
256
                        } elseif ($end - $start < $fileSize - 1) {
257
                            $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
258
                            $this->offset = $start;
259
 
260
                            $this->setStatusCode(206);
261
                            $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
262
                            $this->headers->set('Content-Length', $end - $start + 1);
263
                        }
264
                    }
265
                }
266
            }
267
        }
268
 
269
        return $this;
270
    }
271
 
272
    private function hasValidIfRangeHeader(?string $header): bool
273
    {
274
        if ($this->getEtag() === $header) {
275
            return true;
276
        }
277
 
278
        if (null === $lastModified = $this->getLastModified()) {
279
            return false;
280
        }
281
 
282
        return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
283
    }
284
 
285
    /**
286
     * Sends the file.
287
     *
288
     * {@inheritdoc}
289
     */
290
    public function sendContent()
291
    {
292
        if (!$this->isSuccessful()) {
293
            return parent::sendContent();
294
        }
295
 
296
        if (0 === $this->maxlen) {
297
            return $this;
298
        }
299
 
300
        $out = fopen('php://output', 'wb');
301
        $file = fopen($this->file->getPathname(), 'rb');
302
 
303
        stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
304
 
305
        fclose($out);
306
        fclose($file);
307
 
308
        if ($this->deleteFileAfterSend && file_exists($this->file->getPathname())) {
309
            unlink($this->file->getPathname());
310
        }
311
 
312
        return $this;
313
    }
314
 
315
    /**
316
     * {@inheritdoc}
317
     *
318
     * @throws \LogicException when the content is not null
319
     */
320
    public function setContent(?string $content)
321
    {
322
        if (null !== $content) {
323
            throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
324
        }
325
 
326
        return $this;
327
    }
328
 
329
    /**
330
     * {@inheritdoc}
331
     */
332
    public function getContent()
333
    {
334
        return false;
335
    }
336
 
337
    /**
338
     * Trust X-Sendfile-Type header.
339
     */
340
    public static function trustXSendfileTypeHeader()
341
    {
342
        self::$trustXSendfileTypeHeader = true;
343
    }
344
 
345
    /**
346
     * If this is set to true, the file will be unlinked after the request is sent
347
     * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
348
     *
349
     * @return $this
350
     */
351
    public function deleteFileAfterSend(bool $shouldDelete = true)
352
    {
353
        $this->deleteFileAfterSend = $shouldDelete;
354
 
355
        return $this;
356
    }
357
}