Merge branch '2.3' into 2.6

* 2.3:
  [HttpFoundation] MongoDbSessionHandler::read() now checks for valid session age
  [WebProfilerBundle] Set debug+charset on the ExceptionHandler fallback
  used HTML5 meta charset tag and removed hardcoded ones
  Revert "bug #13715 Enforce UTF-8 charset for core controllers (WouterJ)"

Conflicts:
	src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php
	src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php
	src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php
	src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php
This commit is contained in:
Fabien Potencier 2015-03-12 15:30:42 +01:00
commit 43efb1ac1c
12 changed files with 125 additions and 151 deletions

View File

@ -1,7 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta charset="{{ _charset }}" />
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}{% endblock %}
<link rel="shortcut icon" href="{{ asset('favicon.ico') }}" />

View File

@ -62,7 +62,7 @@ class ExceptionController
$code = $exception->getStatusCode();
return Response::create($this->twig->render(
return new Response($this->twig->render(
$this->findTemplate($request, $request->getRequestFormat(), $code, $showException),
array(
'status_code' => $code,
@ -71,7 +71,7 @@ class ExceptionController
'logger' => $logger,
'currentContent' => $currentContent,
)
))->setCharset('UTF-8');
));
}
/**

View File

@ -1,7 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta charset="{{ _charset }}" />
<title>An Error Occurred: {{ status_text }}</title>
</head>
<body>

View File

@ -40,8 +40,7 @@ class ExceptionControllerTest extends TestCase
$request->headers->set('X-Php-Ob-Level', 1);
$controller = new ExceptionController($twig, false);
$response = $controller->showAction($request, $flatten);
$this->assertEquals('UTF-8', $response->getCharset(), 'Request charset is explicitly set to UTF-8');
$controller->showAction($request, $flatten);
}
public function testShowActionCanBeForcedToShowErrorPage()

View File

@ -55,24 +55,23 @@ class ExceptionController
$template = $this->getTemplate();
if (!$this->twig->getLoader()->exists($template)) {
$handler = new ExceptionHandler();
$handler = new ExceptionHandler($this->debug, $this->twig->getCharset());
return new Response($handler->getContent($exception), 200, array('Content-Type' => 'text/html'));
}
$code = $exception->getStatusCode();
return Response::create(
$this->twig->render($template, array(
return new Response($this->twig->render(
$template,
array(
'status_code' => $code,
'status_text' => Response::$statusTexts[$code],
'exception' => $exception,
'logger' => null,
'currentContent' => '',
)),
200,
array('Content-Type' => 'text/html')
)->setCharset('UTF-8');
)
), 200, array('Content-Type' => 'text/html'));
}
/**
@ -96,16 +95,12 @@ class ExceptionController
$template = $this->getTemplate();
if (!$this->templateExists($template)) {
$handler = new ExceptionHandler();
$handler = new ExceptionHandler($this->debug, $this->twig->getCharset());
$response = new Response($handler->getStylesheet($exception), 200, array('Content-Type' => 'text/css'));
} else {
$response = new Response($this->twig->render('@WebProfiler/Collector/exception.css.twig'), 200, array('Content-Type' => 'text/css'));
return new Response($handler->getStylesheet($exception), 200, array('Content-Type' => 'text/css'));
}
$response->setCharset('UTF-8');
return $response;
return new Response($this->twig->render('@WebProfiler/Collector/exception.css.twig'), 200, array('Content-Type' => 'text/css'));
}
protected function getTemplate()

View File

@ -99,20 +99,16 @@ class ProfilerController
throw new NotFoundHttpException(sprintf('Panel "%s" is not available for token "%s".', $panel, $token));
}
return Response::create(
$this->twig->render($this->getTemplateManager()->getName($profile, $panel), array(
'token' => $token,
'profile' => $profile,
'collector' => $profile->getCollector($panel),
'panel' => $panel,
'page' => $page,
'request' => $request,
'templates' => $this->getTemplateManager()->getTemplates($profile),
'is_ajax' => $request->isXmlHttpRequest(),
)),
200,
array('Content-Type' => 'text/html')
)->setCharset('UTF-8');
return new Response($this->twig->render($this->getTemplateManager()->getName($profile, $panel), array(
'token' => $token,
'profile' => $profile,
'collector' => $profile->getCollector($panel),
'panel' => $panel,
'page' => $page,
'request' => $request,
'templates' => $this->getTemplateManager()->getTemplates($profile),
'is_ajax' => $request->isXmlHttpRequest(),
)), 200, array('Content-Type' => 'text/html'));
}
/**
@ -151,13 +147,9 @@ class ProfilerController
$this->profiler->disable();
return Response::create(
$this->twig->render('@WebProfiler/Profiler/info.html.twig', array(
'about' => $about,
)),
200,
array('Content-Type' => 'text/html')
)->setCharset('UTF-8');
return new Response($this->twig->render('@WebProfiler/Profiler/info.html.twig', array(
'about' => $about,
)), 200, array('Content-Type' => 'text/html'));
}
/**
@ -205,17 +197,13 @@ class ProfilerController
// the profiler is not enabled
}
return Response::create(
$this->twig->render('@WebProfiler/Profiler/toolbar.html.twig', array(
'position' => $position,
'profile' => $profile,
'templates' => $this->getTemplateManager()->getTemplates($profile),
'profiler_url' => $url,
'token' => $token,
)),
200,
array('Content-Type' => 'text/html')
)->setCharset('UTF-8');
return new Response($this->twig->render('@WebProfiler/Profiler/toolbar.html.twig', array(
'position' => $position,
'profile' => $profile,
'templates' => $this->getTemplateManager()->getTemplates($profile),
'profiler_url' => $url,
'token' => $token,
)), 200, array('Content-Type' => 'text/html'));
}
/**
@ -253,7 +241,7 @@ class ProfilerController
$token = $session->get('_profiler_search_token');
}
return Response::create(
return new Response(
$this->twig->render('@WebProfiler/Profiler/search.html.twig', array(
'token' => $token,
'ip' => $ip,
@ -266,7 +254,7 @@ class ProfilerController
)),
200,
array('Content-Type' => 'text/html')
)->setCharset('UTF-8');
);
}
/**
@ -296,22 +284,18 @@ class ProfilerController
$end = $request->query->get('end', null);
$limit = $request->query->get('limit');
return Response::create(
$this->twig->render('@WebProfiler/Profiler/results.html.twig', array(
'token' => $token,
'profile' => $profile,
'tokens' => $this->profiler->find($ip, $url, $limit, $method, $start, $end),
'ip' => $ip,
'method' => $method,
'url' => $url,
'start' => $start,
'end' => $end,
'limit' => $limit,
'panel' => null,
)),
200,
array('Content-Type' => 'text/html')
)->setCharset('UTF-8');
return new Response($this->twig->render('@WebProfiler/Profiler/results.html.twig', array(
'token' => $token,
'profile' => $profile,
'tokens' => $this->profiler->find($ip, $url, $limit, $method, $start, $end),
'ip' => $ip,
'method' => $method,
'url' => $url,
'start' => $start,
'end' => $end,
'limit' => $limit,
'panel' => null,
)), 200, array('Content-Type' => 'text/html'));
}
/**
@ -385,7 +369,7 @@ class ProfilerController
phpinfo();
$phpinfo = ob_get_clean();
return Response::create($phpinfo, 200, array('Content-Type' => 'text/html'))->setCharset('UTF-8');
return new Response($phpinfo, 200, array('Content-Type' => 'text/html'));
}
/**

View File

@ -68,14 +68,10 @@ class RouterController
$request = $profile->getCollector('request');
return Response::create(
$this->twig->render('@WebProfiler/Router/panel.html.twig', array(
'request' => $request,
'router' => $profile->getCollector('router'),
'traces' => $matcher->getTraces($request->getPathInfo()),
)),
200,
array('Content-Type' => 'text/html')
)->setCharset('UTF-8');
return new Response($this->twig->render('@WebProfiler/Router/panel.html.twig', array(
'request' => $request,
'router' => $profile->getCollector('router'),
'traces' => $matcher->getTraces($request->getPathInfo()),
)), 200, array('Content-Type' => 'text/html'));
}
}

View File

@ -1,8 +1,8 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex,nofollow">
<meta charset="{{ _charset }}" />
<meta name="robots" content="noindex,nofollow" />
<title>{% block title 'Profiler' %}</title>
<link rel="icon" type="image/x-icon" sizes="16x16" href="data:image/ico;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAABMLAAATCwAAAAAAAAAAAAAAAAAAAAAAADIvMQAyLzEIMi8xSzEuMKoyLzHkMi8x/TIvMf0yLzHlMi8xrDIvMU4yLzEJMi8xAAAAAAAAAAAAAAAAADIvMQAyLzEYMS4wkTMwMu45Njj/MS4w/zEuMP8yLzH/Mi8x/zIvMf8yLzHvMi8xlDIvMRkyLzEAAAAAADIvMQAyLzEXMS4wrTk2OPyVk5T7kI6P/nl3ef8+Oz3/MS4w/zIvMf8yLzH/Mi8x/zIvMf4yLzGxMi8xGjIvMQAyLzEGMi8xkDEuMP4/PD79wcDA+oB+gP6Ni4z/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LzHdMi8x+jIvMfoyLzHeMi8xoDIvMUUyLzEGMi8xAAAAAAAAAAAA4AcAAMADAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABAADAAwAA4AcAAA==">
<style>

View File

@ -69,7 +69,6 @@ class ProfilerControllerTest extends \PHPUnit_Framework_TestCase
$response = $controller->toolbarAction(Request::create('/_wdt/found'), 'found');
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('UTF-8', $response->getCharset(), 'Request charset is explicitly set to UTF-8');
$response = $controller->toolbarAction(Request::create('/_wdt/notFound'), 'notFound');
$this->assertEquals(404, $response->getStatusCode());

View File

@ -177,6 +177,7 @@ class ExceptionHandler
foreach ($exception->getHeaders() as $name => $value) {
header($name.': '.$value, false);
}
header('Content-Type: text/html; charset='.$this->charset);
}
echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
@ -195,7 +196,7 @@ class ExceptionHandler
$exception = FlattenException::create($exception);
}
return new Response($this->decorate($this->getContent($exception), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders());
return Response::create($this->decorate($this->getContent($exception), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders())->setCharset($this->charset);
}
/**

View File

@ -42,6 +42,24 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
* * id_field: The field name for storing the session id [default: _id]
* * data_field: The field name for storing the session data [default: data]
* * time_field: The field name for storing the timestamp [default: time]
* * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]
*
* It is strongly recommended to put an index on the `expiry_field` for
* garbage-collection. Alternatively it's possible to automatically expire
* the sessions in the database as described below:
*
* A TTL collections can be used on MongoDB 2.2+ to cleanup expired sessions
* automatically. Such an index can for example look like this:
*
* db.<session-collection>.ensureIndex(
* { "<expiry-field>": 1 },
* { "expireAfterSeconds": 0 }
* )
*
* More details on: http://docs.mongodb.org/manual/tutorial/expire-data/
*
* If you use such an index, you can drop `gc_probability` to 0 since
* no garbage-collection is required.
*
* @param \Mongo|\MongoClient $mongo A MongoClient or Mongo instance
* @param array $options An associative array of field options
@ -65,7 +83,7 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
'id_field' => '_id',
'data_field' => 'data',
'time_field' => 'time',
'expiry_field' => false,
'expiry_field' => 'expires_at',
), $options);
}
@ -102,21 +120,8 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
*/
public function gc($maxlifetime)
{
/* Note: MongoDB 2.2+ supports TTL collections, which may be used in
* place of this method by indexing the "time_field" field with an
* "expireAfterSeconds" option. Regardless of whether TTL collections
* are used, consider indexing this field to make the remove query more
* efficient.
*
* See: http://docs.mongodb.org/manual/tutorial/expire-data/
*/
if (false !== $this->options['expiry_field']) {
return true;
}
$time = new \MongoDate(time() - $maxlifetime);
$this->getCollection()->remove(array(
$this->options['time_field'] => array('$lt' => $time),
$this->options['expiry_field'] => array('$lt' => new \MongoDate()),
));
return true;
@ -127,24 +132,14 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
*/
public function write($sessionId, $data)
{
$expiry = new \MongoDate(time() + (int) ini_get('session.gc_maxlifetime'));
$fields = array(
$this->options['data_field'] => new \MongoBinData($data, \MongoBinData::BYTE_ARRAY),
$this->options['time_field'] => new \MongoDate(),
$this->options['expiry_field'] => $expiry,
);
/* Note: As discussed in the gc method of this class. You can utilise
* TTL collections in MongoDB 2.2+
* We are setting the "expiry_field" as part of the write operation here
* You will need to create the index on your collection that expires documents
* at that time
* e.g.
* db.MySessionCollection.ensureIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )
*/
if (false !== $this->options['expiry_field']) {
$expiry = new \MongoDate(time() + (int) ini_get('session.gc_maxlifetime'));
$fields[$this->options['expiry_field']] = $expiry;
}
$this->getCollection()->update(
array($this->options['id_field'] => $sessionId),
array('$set' => $fields),
@ -160,7 +155,8 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
public function read($sessionId)
{
$dbData = $this->getCollection()->findOne(array(
$this->options['id_field'] => $sessionId,
$this->options['id_field'] => $sessionId,
$this->options['expiry_field'] => array('$gte' => new \MongoDate()),
));
return null === $dbData ? '' : $dbData[$this->options['data_field']]->bin;

View File

@ -40,6 +40,7 @@ class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase
'id_field' => '_id',
'data_field' => 'data',
'time_field' => 'time',
'expiry_field' => 'expires_at',
'database' => 'sf2-test',
'collection' => 'session-test',
);
@ -73,6 +74,42 @@ class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($this->storage->close(), 'The "close" method should always return true');
}
public function testRead()
{
$collection = $this->createMongoCollectionMock();
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
$that = $this;
// defining the timeout before the actual method call
// allows to test for "greater than" values in the $criteria
$testTimeout = time();
$collection->expects($this->once())
->method('findOne')
->will($this->returnCallback(function ($criteria) use ($that, $testTimeout) {
$that->assertArrayHasKey($that->options['id_field'], $criteria);
$that->assertEquals($criteria[$that->options['id_field']], 'foo');
$that->assertArrayHasKey($that->options['expiry_field'], $criteria);
$that->assertArrayHasKey('$gte', $criteria[$that->options['expiry_field']]);
$that->assertInstanceOf('MongoDate', $criteria[$that->options['expiry_field']]['$gte']);
$that->assertGreaterThanOrEqual($criteria[$that->options['expiry_field']]['$gte']->sec, $testTimeout);
return array(
$that->options['id_field'] => 'foo',
$that->options['data_field'] => new \MongoBinData('bar', \MongoBinData::BYTE_ARRAY),
$that->options['id_field'] => new \MongoDate(),
);
}));
$this->assertEquals('bar', $this->storage->read('foo'));
}
public function testWrite()
{
$collection = $this->createMongoCollectionMock();
@ -94,10 +131,13 @@ class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase
$data = $updateData['$set'];
}));
$expectedExpiry = time() + (int) ini_get('session.gc_maxlifetime');
$this->assertTrue($this->storage->write('foo', 'bar'));
$this->assertEquals('bar', $data[$this->options['data_field']]->bin);
$that->assertInstanceOf('MongoDate', $data[$this->options['time_field']]);
$this->assertInstanceOf('MongoDate', $data[$this->options['expiry_field']]);
$this->assertGreaterThanOrEqual($expectedExpiry, $data[$this->options['expiry_field']]->sec);
}
public function testWriteWhenUsingExpiresField()
@ -192,49 +232,13 @@ class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase
$collection->expects($this->once())
->method('remove')
->will($this->returnCallback(function ($criteria) use ($that) {
$that->assertInstanceOf('MongoDate', $criteria[$that->options['time_field']]['$lt']);
$that->assertGreaterThanOrEqual(time() - 1, $criteria[$that->options['time_field']]['$lt']->sec);
$that->assertInstanceOf('MongoDate', $criteria[$that->options['expiry_field']]['$lt']);
$that->assertGreaterThanOrEqual(time() - 1, $criteria[$that->options['expiry_field']]['$lt']->sec);
}));
$this->assertTrue($this->storage->gc(1));
}
public function testGcWhenUsingExpiresField()
{
$this->options = array(
'id_field' => '_id',
'data_field' => 'data',
'time_field' => 'time',
'database' => 'sf2-test',
'collection' => 'session-test',
'expiry_field' => 'expiresAt',
);
$this->storage = new MongoDbSessionHandler($this->mongo, $this->options);
$collection = $this->createMongoCollectionMock();
$this->mongo->expects($this->never())
->method('selectCollection');
$that = $this;
$collection->expects($this->never())
->method('remove');
$this->assertTrue($this->storage->gc(1));
}
public function testGetConnection()
{
$method = new \ReflectionMethod($this->storage, 'getMongo');
$method->setAccessible(true);
$mongoClass = (version_compare(phpversion('mongo'), '1.3.0', '<')) ? '\Mongo' : '\MongoClient';
$this->assertInstanceOf($mongoClass, $method->invoke($this->storage));
}
private function createMongoCollectionMock()
{
$mongoClient = $this->getMockBuilder('MongoClient')