8000 [HttpFoundation] Added BinaryFileResponse. · symfony/symfony@2f7bbbf · GitHub
[go: up one dir, main page]

Skip to content

Commit 2f7bbbf

Browse files
committed
[HttpFoundation] Added BinaryFileResponse.
1 parent 7dbadbf commit 2f7bbbf

File tree

2 files changed

+383
-0
lines changed

2 files changed

+383
-0
lines changed
Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
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\File;
15+
use Symfony\Component\HttpFoundation\File\Exception\FileException;
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+
protected $file;
31+
protected $offset;
32+
protected $maxlen;
33+
34+
/**
35+
* Constructor.
36+
*
37+
* @param SplFileInfo|string $file The file to stream
38+
* @param integer $status The response status code
39+
* @param array $headers An array of response headers
40+
* @param boolean $public Files are public by default
41+
* @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
42+
* @param boolean $autoEtag Whether the ETag header should be automatically set
43+
* @param boolean $autoLastModified Whether the Last-Modified header should be automatically set
44+
*/
45+
public function __construct($file, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
46+
{
47+
parent::__construct(null, $status, $headers);
48+
49+
$this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
50+
51+
if ($public) {
52+
$this->setPublic();
53+
}
54+
}
55+
56+
/**
57+
* {@inheritdoc}
58+
*/
59+
public static function create($file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
60+
{
61+
return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
62+
}
63+
64+
/**
65+
* Sets the file to stream.
66+
*
67+
* @param SplFileInfo|string $file The file to stream
68+
*/
69+
public function setFile($file, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
70+
{
71+
$file = new File((string) $file);
72+
73+
if (!$file->isReadable()) {
74+
throw new FileException('File must be readable.');
75+
}
76+
77+
$this->file = $file;
78+
79+
if ($autoEtag) {
80+
$this->setAutoEtag();
81+
}
82+
83+
if ($autoLastModified) {
84+
$this->setAutoLastModified();
85+
}
86+
87+
if ($contentDisposition) {
88+
$this->setContentDisposition($contentDisposition);
89+
}
90+
91+
return $this;
92+
}
93+
94+
/**
95+
* Gets the file.
96+
*
97+
* @return File The file to stream
98+
*/
99+
public function getFile()
100+
{
101+
return $this->file;
102+
}
103+
104+
/**
105+
* Automatically sets the Last-Modified header according the file modification date.
106+
*/
107+
public function setAutoLastModified()
108+
{
109+
$this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
110+
111+
return $this;
112+
}
113+
114+
/**
115+
* Automatically sets the ETag header according to the checksum of the file.
116+
*/
117+
public function setAutoEtag()
118+
{
119+
$this->setEtag(sha1_file($this->file->getPathname()));
120+
121+
return $this;
122+
}
123+
124+
/**
125+
* Sets the Content-Disposition header with the given filename.
126+
*
127+
* @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
128+
* @param string $filename Optionally use this filename instead of the real name of the file
129+
* @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
130+
*/
131+
public function setContentDisposition($disposition, $filename = '', $filenameFallback = '')
132+
{
133+
if ($filename === '') {
134+
$filename = $this->file->getFilename();
135+
}
136+
137+
$dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
138+
$this->headers->set('Content-Disposition', $dispositionHeader);
139+
140+
return $this;
141+
}
142+
143+
/**
144+
* {@inheritdoc}
145+
*/
146+
public function prepare(Request $request)
147+
{
148+
$this->headers->set('Content-Length', $this->file->getSize());
149+
$this->headers->set('Accept-Ranges', 'bytes');
150+
$this->headers->set('Content-Transfer-Encoding', 'binary');
151+
152+
if (!$this->headers->has('Content-Type')) {
153+
$this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
154+
}
155+
156+
if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
157+
$this->setProtocolVersion('1.1');
158+
}
159+
160+
$this->offset = 0;
161+
$this->maxlen = -1;
162+
163+
if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
164+
// Use X-Sendfile, do not send any content.
165+
$type = $request->headers->get('X-Sendfile-Type');
166+
$path = $this->file->getRealPath();
167+
if (strtolower($type) == 'x-accel-redirect') {
168+
// Do X-Accel-Mapping substitutions.
169+
foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) {
170+
$mapping = explode('=', $mapping, 2);
171+
172+
if (2 == count($mapping)) {
173+
$location = trim($mapping[0]);
174+
$pathPrefix = trim($mapping[1]);
175+
176+
if (substr($path, 0, strlen($pathPrefix)) == $pathPrefix) {
177+
$path = $location . substr($path, strlen($pathPrefix));
178+
break;
179+
}
180+
}
181+
}
182+
}
183+
$this->headers->set($type, $path);
184+
$this->maxlen = 0;
185+
} elseif ($request->headers->has('Range')) {
186+
// Process the range headers.
187+
if (!$request->headers->has('If-Range') || $this->getEtag() == $request->headers->get('If-Range')) {
188+
$range = $request->headers->get('Range');
189+
190+
list($start, $end) = array_map('intval', explode('-', substr($range, 6), 2)) + array(0);
191+
192+
if ('' !== $end) {
193+
$this->maxlen = $end - $start;
194+
} else {
195+
$end = $this->file->getSize() - 1;
196+
}
197+
198+
$this->offset = $start;
199+
200+
$this->setStatusCode(206);
201+
$this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $this->file->getSize()));
202+
}
203+
}
204+
}
205+
206+
/**
207+
* Sends the file.
208+
*/
209+
public function sendContent()
210+
{
211+
if (!$this->isSuccessful()) {
212+
parent::sendContent();
213+
214+
return;
215+
}
216+
217+
if (0 === $this->maxlen) {
218+
return;
219+
}
220+
221+
$out = fopen('php://output', 'wb');
222+
$file = fopen($this->file->getPathname(), 'rb');
223+
224+
stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
225+
226+
fclose($out);
227+
fclose($file);
228+
}
229+
230+
/**
231+
* {@inheritdoc}
232+
*
233+
* @throws \LogicException when the content is not null
234+
*/
235+
public function setContent($content)
236+
{
237+
if (null !== $content) {
238+
throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
239+
}
240+
}
241+
242+
/**
243+
* {@inheritdoc}
244+
*
245+
* @return false
246+
*/
247+
public function getContent()
248+
{
249+
return false;
250+
}
251+
252+
/**
253+
* Trust X-Sendfile-Type header.
254+
*/
255+
public static function trustXSendfileTypeHeader()
256+
{
257+
self::$trustXSendfileTypeHeader = true;
258+
}
259+
}
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
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\Tests;
13+
14+
use Symfony\Component\HttpFoundation\BinaryFileResponse;
15+
use Symfony\Component\HttpFoundation\Request;
16+
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
17+
18+
class BinaryFileResponseTest extends \PHPUnit_Framework_TestCase
19+
{
20+
public function testConstruction()
21+
{
22+
$response = new BinaryFileResponse('README.md', 404, array('X-Header' => 'Foo'), true, null, true, true);
23+
$this->assertEquals(404, $response->getStatusCode());
24+
$this->assertEquals('Foo', $response->headers->get('X-Header'));
25+
$this->assertTrue($response->headers->has('ETag'));
26+
$this->assertTrue($response->headers->has('Last-Modified'));
27+
$this->assertFalse($response->headers->has('Content-Disposition'));
28+
29+
$response = BinaryFileResponse::create('README.md', 404, array(), true, ResponseHeaderBag::DISPOSITION_INLINE);
30+
$this->assertEquals(404, $response->getStatusCode());
31+
$this->assertFalse($response->headers->has('ETag'));
32+
$this->assertEquals('inline; filename="README.md"', $response->headers->get('Content-Disposition'));
33+
}
34+
35+
/**
36+
* @expectedException \LogicException
37+
*/
38+
public function testSetContent()
39+
{
40+
$response = new BinaryFileResponse('README.md');
41+
$response->setContent('foo');
42+
}
43+
44+
public function testGetContent()
45+
{
46+
$response = new BinaryFileResponse('README.md');
47+
$this->assertFalse($response->getContent());
48+
}
49+
50+
public function testRequests()
51+
{
52+
$response = BinaryFileResponse::create('src/Symfony/Component/HttpFoundation/Tests/File/Fixtures/test.gif')->setAutoEtag();
53+
54+
// do a request to get the ETag
55+
$request = Request::create('/');
56+
$response->prepare($request);
57+
$etag = $response->headers->get('ETag');
58+
59+
// prepare a request for a range of the testing file
60+
$request = Request::create('/');
61+
$request->headers->set('If-Range', $etag);
62+
$request->headers->set('Range', 'bytes=1-4');
63+
64+
$this->expectOutputString('IF8');
65+
$response = clone $response;
66+
$response->prepare($request);
67+
$response->sendContent();
68+
69+
$this->assertEquals('binary', $response->headers->get('Content-Transfer-Encoding'));
70+
}
71+
72+
public function testXSendfile()
73+
{
74+
$request = Request::create('/');
75+
$request->headers->set('X-Sendfile-Type', 'X-Sendfile');
76+
77+
BinaryFileResponse::trustXSendfileTypeHeader();
78+
$response = BinaryFileResponse::create('README.md');
79+
$response->prepare($request);
80+
81+
$this->expectOutputString('');
82+
$response->sendContent();
83+
84+
$this->assertContains('README.md', $response->headers->get('X-Sendfile'));
85+
}
86+
87+
/**
88+
* @dataProvider getSampleXAccelMappings
89+
*/
90+
public function testXAccelMapping($realpath, $mapping, $virtual)
91+
{
92+
$request = Request::create('/');
93+
$request->headers->set('X-Sendfile-Type', 'X-Accel-Redirect');
94+
$request->headers->set('X-Accel-Mapping', $mapping);
95+
96+
$file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
97+
->disableOriginalConstructor()
98+
->getMock();
99+
$file->expects($this->any())
100+
->method('getRealPath')
101+
->will($this->returnValue($realpath));
102+
$file->expects($this->any())
103+
->method('isReadable')
104+
->will($this->returnValue(true));
105+
106+
BinaryFileResponse::trustXSendFileTypeHeader();
107+
$response = new BinaryFileResponse('README.md');
108+
$reflection = new \ReflectionObject($response);
109+
$property = $reflection->getProperty('file');
110+
$property->setAccessible(true);
111+
$property->setValue($response, $file);
112+
113+
$response->prepare($request);
114+
$this->assertEquals($virtual, $response->headers->get('X-Accel-Redirect'));
115+
}
116+
117+
public function getSampleXAccelMappings()
118+
{
119+
return array(
120+
array('/var/www/var/www/files/foo.txt', '/files/=/var/www/', '/files/var/www/files/foo.txt'),
121+
array('/home/foo/bar.txt', '/files/=/var/www/,/baz/=/home/foo/', '/baz/bar.txt'),
122+
);
123+
}
124+
}

0 commit comments

Comments
 (0)
0