4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\HttpCache;
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\Response;
16 use Symfony\Component\HttpKernel\HttpKernelInterface;
19 * Esi implements the ESI capabilities to Request and Response instances.
21 * For more information, read the following W3C notes:
23 * * ESI Language Specification 1.0 (http://www.w3.org/TR/esi-lang)
25 * * Edge Architecture Specification (http://www.w3.org/TR/edge-arch)
27 * @author Fabien Potencier <fabien@symfony.com>
29 class Esi implements SurrogateInterface
31 private $contentTypes;
32 private $phpEscapeMap = array(
33 array('<?', '<%', '<s', '<S'),
34 array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
40 * @param array $contentTypes An array of content-type that should be parsed for ESI information
41 * (default: text/html, text/xml, application/xhtml+xml, and application/xml)
43 public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
45 $this->contentTypes = $contentTypes;
48 public function getName()
54 * Returns a new cache strategy instance.
56 * @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
58 public function createCacheStrategy()
60 return new ResponseCacheStrategy();
64 * Checks that at least one surrogate has ESI/1.0 capability.
66 * @param Request $request A Request instance
68 * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
70 public function hasSurrogateCapability(Request $request)
72 if (null === $value = $request->headers->get('Surrogate-Capability')) {
76 return false !== strpos($value, 'ESI/1.0');
80 * Checks that at least one surrogate has ESI/1.0 capability.
82 * @param Request $request A Request instance
84 * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
86 * @deprecated since version 2.6, to be removed in 3.0. Use hasSurrogateCapability() instead
88 public function hasSurrogateEsiCapability(Request $request)
90 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the hasSurrogateCapability() method instead.', E_USER_DEPRECATED);
92 return $this->hasSurrogateCapability($request);
96 * Adds ESI/1.0 capability to the given Request.
98 * @param Request $request A Request instance
100 public function addSurrogateCapability(Request $request)
102 $current = $request->headers->get('Surrogate-Capability');
103 $new = 'symfony2="ESI/1.0"';
105 $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
109 * Adds ESI/1.0 capability to the given Request.
111 * @param Request $request A Request instance
113 * @deprecated since version 2.6, to be removed in 3.0. Use addSurrogateCapability() instead
115 public function addSurrogateEsiCapability(Request $request)
117 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the addSurrogateCapability() method instead.', E_USER_DEPRECATED);
119 $this->addSurrogateCapability($request);
123 * Adds HTTP headers to specify that the Response needs to be parsed for ESI.
125 * This method only adds an ESI HTTP header if the Response has some ESI tags.
127 * @param Response $response A Response instance
129 public function addSurrogateControl(Response $response)
131 if (false !== strpos($response->getContent(), '<esi:include')) {
132 $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
137 * Checks that the Response needs to be parsed for ESI tags.
139 * @param Response $response A Response instance
141 * @return bool true if the Response needs to be parsed, false otherwise
143 public function needsParsing(Response $response)
145 if (!$control = $response->headers->get('Surrogate-Control')) {
149 return (bool) preg_match('#content="[^"]*ESI/1.0[^"]*"#', $control);
153 * Checks that the Response needs to be parsed for ESI tags.
155 * @param Response $response A Response instance
157 * @return bool true if the Response needs to be parsed, false otherwise
159 * @deprecated since version 2.6, to be removed in 3.0. Use needsParsing() instead
161 public function needsEsiParsing(Response $response)
163 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the needsParsing() method instead.', E_USER_DEPRECATED);
165 return $this->needsParsing($response);
169 * Renders an ESI tag.
171 * @param string $uri A URI
172 * @param string $alt An alternate URI
173 * @param bool $ignoreErrors Whether to ignore errors or not
174 * @param string $comment A comment to add as an esi:include tag
178 public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
180 $html = sprintf('<esi:include src="%s"%s%s />',
182 $ignoreErrors ? ' onerror="continue"' : '',
183 $alt ? sprintf(' alt="%s"', $alt) : ''
186 if (!empty($comment)) {
187 return sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $html);
194 * Replaces a Response ESI tags with the included resource content.
196 * @param Request $request A Request instance
197 * @param Response $response A Response instance
201 public function process(Request $request, Response $response)
203 $type = $response->headers->get('Content-Type');
208 $parts = explode(';', $type);
209 if (!in_array($parts[0], $this->contentTypes)) {
213 // we don't use a proper XML parser here as we can have ESI tags in a plain text response
214 $content = $response->getContent();
215 $content = preg_replace('#<esi\:remove>.*?</esi\:remove>#s', '', $content);
216 $content = preg_replace('#<esi\:comment[^>]+>#s', '', $content);
218 $chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
219 $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
222 while (isset($chunks[$i])) {
224 preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
225 foreach ($matches as $set) {
226 $options[$set[1]] = $set[2];
229 if (!isset($options['src'])) {
230 throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
233 $chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
234 var_export($options['src'], true),
235 var_export(isset($options['alt']) ? $options['alt'] : '', true),
236 isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false'
239 $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]);
242 $content = implode('', $chunks);
244 $response->setContent($content);
245 $response->headers->set('X-Body-Eval', 'ESI');
247 // remove ESI/1.0 from the Surrogate-Control header
248 if ($response->headers->has('Surrogate-Control')) {
249 $value = $response->headers->get('Surrogate-Control');
250 if ('content="ESI/1.0"' == $value) {
251 $response->headers->remove('Surrogate-Control');
252 } elseif (preg_match('#,\s*content="ESI/1.0"#', $value)) {
253 $response->headers->set('Surrogate-Control', preg_replace('#,\s*content="ESI/1.0"#', '', $value));
254 } elseif (preg_match('#content="ESI/1.0",\s*#', $value)) {
255 $response->headers->set('Surrogate-Control', preg_replace('#content="ESI/1.0",\s*#', '', $value));
261 * Handles an ESI from the cache.
263 * @param HttpCache $cache An HttpCache instance
264 * @param string $uri The main URI
265 * @param string $alt An alternative URI
266 * @param bool $ignoreErrors Whether to ignore errors or not
270 * @throws \RuntimeException
273 public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
275 $subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
278 $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
280 if (!$response->isSuccessful()) {
281 throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
284 return $response->getContent();
285 } catch (\Exception $e) {
287 return $this->handle($cache, $alt, '', $ignoreErrors);
290 if (!$ignoreErrors) {