Yaffs site version 1.1
[yaffs-website] / vendor / symfony / http-kernel / HttpCache / Esi.php
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\HttpKernel\HttpCache;
13
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\Response;
16 use Symfony\Component\HttpKernel\HttpKernelInterface;
17
18 /**
19  * Esi implements the ESI capabilities to Request and Response instances.
20  *
21  * For more information, read the following W3C notes:
22  *
23  *  * ESI Language Specification 1.0 (http://www.w3.org/TR/esi-lang)
24  *
25  *  * Edge Architecture Specification (http://www.w3.org/TR/edge-arch)
26  *
27  * @author Fabien Potencier <fabien@symfony.com>
28  */
29 class Esi implements SurrogateInterface
30 {
31     private $contentTypes;
32     private $phpEscapeMap = array(
33         array('<?', '<%', '<s', '<S'),
34         array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
35     );
36
37     /**
38      * Constructor.
39      *
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)
42      */
43     public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
44     {
45         $this->contentTypes = $contentTypes;
46     }
47
48     public function getName()
49     {
50         return 'esi';
51     }
52
53     /**
54      * Returns a new cache strategy instance.
55      *
56      * @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
57      */
58     public function createCacheStrategy()
59     {
60         return new ResponseCacheStrategy();
61     }
62
63     /**
64      * Checks that at least one surrogate has ESI/1.0 capability.
65      *
66      * @param Request $request A Request instance
67      *
68      * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
69      */
70     public function hasSurrogateCapability(Request $request)
71     {
72         if (null === $value = $request->headers->get('Surrogate-Capability')) {
73             return false;
74         }
75
76         return false !== strpos($value, 'ESI/1.0');
77     }
78
79     /**
80      * Checks that at least one surrogate has ESI/1.0 capability.
81      *
82      * @param Request $request A Request instance
83      *
84      * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
85      *
86      * @deprecated since version 2.6, to be removed in 3.0. Use hasSurrogateCapability() instead
87      */
88     public function hasSurrogateEsiCapability(Request $request)
89     {
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);
91
92         return $this->hasSurrogateCapability($request);
93     }
94
95     /**
96      * Adds ESI/1.0 capability to the given Request.
97      *
98      * @param Request $request A Request instance
99      */
100     public function addSurrogateCapability(Request $request)
101     {
102         $current = $request->headers->get('Surrogate-Capability');
103         $new = 'symfony2="ESI/1.0"';
104
105         $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
106     }
107
108     /**
109      * Adds ESI/1.0 capability to the given Request.
110      *
111      * @param Request $request A Request instance
112      *
113      * @deprecated since version 2.6, to be removed in 3.0. Use addSurrogateCapability() instead
114      */
115     public function addSurrogateEsiCapability(Request $request)
116     {
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);
118
119         $this->addSurrogateCapability($request);
120     }
121
122     /**
123      * Adds HTTP headers to specify that the Response needs to be parsed for ESI.
124      *
125      * This method only adds an ESI HTTP header if the Response has some ESI tags.
126      *
127      * @param Response $response A Response instance
128      */
129     public function addSurrogateControl(Response $response)
130     {
131         if (false !== strpos($response->getContent(), '<esi:include')) {
132             $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
133         }
134     }
135
136     /**
137      * Checks that the Response needs to be parsed for ESI tags.
138      *
139      * @param Response $response A Response instance
140      *
141      * @return bool true if the Response needs to be parsed, false otherwise
142      */
143     public function needsParsing(Response $response)
144     {
145         if (!$control = $response->headers->get('Surrogate-Control')) {
146             return false;
147         }
148
149         return (bool) preg_match('#content="[^"]*ESI/1.0[^"]*"#', $control);
150     }
151
152     /**
153      * Checks that the Response needs to be parsed for ESI tags.
154      *
155      * @param Response $response A Response instance
156      *
157      * @return bool true if the Response needs to be parsed, false otherwise
158      *
159      * @deprecated since version 2.6, to be removed in 3.0. Use needsParsing() instead
160      */
161     public function needsEsiParsing(Response $response)
162     {
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);
164
165         return $this->needsParsing($response);
166     }
167
168     /**
169      * Renders an ESI tag.
170      *
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
175      *
176      * @return string
177      */
178     public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
179     {
180         $html = sprintf('<esi:include src="%s"%s%s />',
181             $uri,
182             $ignoreErrors ? ' onerror="continue"' : '',
183             $alt ? sprintf(' alt="%s"', $alt) : ''
184         );
185
186         if (!empty($comment)) {
187             return sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $html);
188         }
189
190         return $html;
191     }
192
193     /**
194      * Replaces a Response ESI tags with the included resource content.
195      *
196      * @param Request  $request  A Request instance
197      * @param Response $response A Response instance
198      *
199      * @return Response
200      */
201     public function process(Request $request, Response $response)
202     {
203         $type = $response->headers->get('Content-Type');
204         if (empty($type)) {
205             $type = 'text/html';
206         }
207
208         $parts = explode(';', $type);
209         if (!in_array($parts[0], $this->contentTypes)) {
210             return $response;
211         }
212
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);
217
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]);
220
221         $i = 1;
222         while (isset($chunks[$i])) {
223             $options = array();
224             preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
225             foreach ($matches as $set) {
226                 $options[$set[1]] = $set[2];
227             }
228
229             if (!isset($options['src'])) {
230                 throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
231             }
232
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'
237             );
238             ++$i;
239             $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]);
240             ++$i;
241         }
242         $content = implode('', $chunks);
243
244         $response->setContent($content);
245         $response->headers->set('X-Body-Eval', 'ESI');
246
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));
256             }
257         }
258     }
259
260     /**
261      * Handles an ESI from the cache.
262      *
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
267      *
268      * @return string
269      *
270      * @throws \RuntimeException
271      * @throws \Exception
272      */
273     public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
274     {
275         $subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
276
277         try {
278             $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
279
280             if (!$response->isSuccessful()) {
281                 throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
282             }
283
284             return $response->getContent();
285         } catch (\Exception $e) {
286             if ($alt) {
287                 return $this->handle($cache, $alt, '', $ignoreErrors);
288             }
289
290             if (!$ignoreErrors) {
291                 throw $e;
292             }
293         }
294     }
295 }