Esi.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\HttpCache;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\HttpKernelInterface;
  14. /**
  15. * Esi implements the ESI capabilities to Request and Response instances.
  16. *
  17. * For more information, read the following W3C notes:
  18. *
  19. * * ESI Language Specification 1.0 (http://www.w3.org/TR/esi-lang)
  20. *
  21. * * Edge Architecture Specification (http://www.w3.org/TR/edge-arch)
  22. *
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. */
  25. class Esi implements SurrogateInterface
  26. {
  27. private $contentTypes;
  28. private $phpEscapeMap = array(
  29. array('<?', '<%', '<s', '<S'),
  30. array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
  31. );
  32. /**
  33. * @param array $contentTypes An array of content-type that should be parsed for ESI information
  34. * (default: text/html, text/xml, application/xhtml+xml, and application/xml)
  35. */
  36. public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
  37. {
  38. $this->contentTypes = $contentTypes;
  39. }
  40. public function getName()
  41. {
  42. return 'esi';
  43. }
  44. /**
  45. * Returns a new cache strategy instance.
  46. *
  47. * @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
  48. */
  49. public function createCacheStrategy()
  50. {
  51. return new ResponseCacheStrategy();
  52. }
  53. /**
  54. * Checks that at least one surrogate has ESI/1.0 capability.
  55. *
  56. * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
  57. */
  58. public function hasSurrogateCapability(Request $request)
  59. {
  60. if (null === $value = $request->headers->get('Surrogate-Capability')) {
  61. return false;
  62. }
  63. return false !== strpos($value, 'ESI/1.0');
  64. }
  65. /**
  66. * Checks that at least one surrogate has ESI/1.0 capability.
  67. *
  68. * @param Request $request A Request instance
  69. *
  70. * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
  71. *
  72. * @deprecated since version 2.6, to be removed in 3.0. Use hasSurrogateCapability() instead
  73. */
  74. public function hasSurrogateEsiCapability(Request $request)
  75. {
  76. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the hasSurrogateCapability() method instead.', E_USER_DEPRECATED);
  77. return $this->hasSurrogateCapability($request);
  78. }
  79. /**
  80. * Adds ESI/1.0 capability to the given Request.
  81. */
  82. public function addSurrogateCapability(Request $request)
  83. {
  84. $current = $request->headers->get('Surrogate-Capability');
  85. $new = 'symfony2="ESI/1.0"';
  86. $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
  87. }
  88. /**
  89. * Adds ESI/1.0 capability to the given Request.
  90. *
  91. * @param Request $request A Request instance
  92. *
  93. * @deprecated since version 2.6, to be removed in 3.0. Use addSurrogateCapability() instead
  94. */
  95. public function addSurrogateEsiCapability(Request $request)
  96. {
  97. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the addSurrogateCapability() method instead.', E_USER_DEPRECATED);
  98. $this->addSurrogateCapability($request);
  99. }
  100. /**
  101. * Adds HTTP headers to specify that the Response needs to be parsed for ESI.
  102. *
  103. * This method only adds an ESI HTTP header if the Response has some ESI tags.
  104. */
  105. public function addSurrogateControl(Response $response)
  106. {
  107. if (false !== strpos($response->getContent(), '<esi:include')) {
  108. $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
  109. }
  110. }
  111. /**
  112. * Checks that the Response needs to be parsed for ESI tags.
  113. *
  114. * @return bool true if the Response needs to be parsed, false otherwise
  115. */
  116. public function needsParsing(Response $response)
  117. {
  118. if (!$control = $response->headers->get('Surrogate-Control')) {
  119. return false;
  120. }
  121. return (bool) preg_match('#content="[^"]*ESI/1.0[^"]*"#', $control);
  122. }
  123. /**
  124. * Checks that the Response needs to be parsed for ESI tags.
  125. *
  126. * @param Response $response A Response instance
  127. *
  128. * @return bool true if the Response needs to be parsed, false otherwise
  129. *
  130. * @deprecated since version 2.6, to be removed in 3.0. Use needsParsing() instead
  131. */
  132. public function needsEsiParsing(Response $response)
  133. {
  134. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the needsParsing() method instead.', E_USER_DEPRECATED);
  135. return $this->needsParsing($response);
  136. }
  137. /**
  138. * Renders an ESI tag.
  139. *
  140. * @param string $uri A URI
  141. * @param string $alt An alternate URI
  142. * @param bool $ignoreErrors Whether to ignore errors or not
  143. * @param string $comment A comment to add as an esi:include tag
  144. *
  145. * @return string
  146. */
  147. public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
  148. {
  149. $html = sprintf('<esi:include src="%s"%s%s />',
  150. $uri,
  151. $ignoreErrors ? ' onerror="continue"' : '',
  152. $alt ? sprintf(' alt="%s"', $alt) : ''
  153. );
  154. if (!empty($comment)) {
  155. return sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $html);
  156. }
  157. return $html;
  158. }
  159. /**
  160. * Replaces a Response ESI tags with the included resource content.
  161. *
  162. * @return Response
  163. */
  164. public function process(Request $request, Response $response)
  165. {
  166. $type = $response->headers->get('Content-Type');
  167. if (empty($type)) {
  168. $type = 'text/html';
  169. }
  170. $parts = explode(';', $type);
  171. if (!\in_array($parts[0], $this->contentTypes)) {
  172. return $response;
  173. }
  174. // we don't use a proper XML parser here as we can have ESI tags in a plain text response
  175. $content = $response->getContent();
  176. $content = preg_replace('#<esi\:remove>.*?</esi\:remove>#s', '', $content);
  177. $content = preg_replace('#<esi\:comment[^>]+>#s', '', $content);
  178. $chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
  179. $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
  180. $i = 1;
  181. while (isset($chunks[$i])) {
  182. $options = array();
  183. preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
  184. foreach ($matches as $set) {
  185. $options[$set[1]] = $set[2];
  186. }
  187. if (!isset($options['src'])) {
  188. throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
  189. }
  190. $chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
  191. var_export($options['src'], true),
  192. var_export(isset($options['alt']) ? $options['alt'] : '', true),
  193. isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false'
  194. );
  195. ++$i;
  196. $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]);
  197. ++$i;
  198. }
  199. $content = implode('', $chunks);
  200. $response->setContent($content);
  201. $response->headers->set('X-Body-Eval', 'ESI');
  202. // remove ESI/1.0 from the Surrogate-Control header
  203. if ($response->headers->has('Surrogate-Control')) {
  204. $value = $response->headers->get('Surrogate-Control');
  205. if ('content="ESI/1.0"' == $value) {
  206. $response->headers->remove('Surrogate-Control');
  207. } elseif (preg_match('#,\s*content="ESI/1.0"#', $value)) {
  208. $response->headers->set('Surrogate-Control', preg_replace('#,\s*content="ESI/1.0"#', '', $value));
  209. } elseif (preg_match('#content="ESI/1.0",\s*#', $value)) {
  210. $response->headers->set('Surrogate-Control', preg_replace('#content="ESI/1.0",\s*#', '', $value));
  211. }
  212. }
  213. }
  214. /**
  215. * Handles an ESI from the cache.
  216. *
  217. * @param HttpCache $cache An HttpCache instance
  218. * @param string $uri The main URI
  219. * @param string $alt An alternative URI
  220. * @param bool $ignoreErrors Whether to ignore errors or not
  221. *
  222. * @return string
  223. *
  224. * @throws \RuntimeException
  225. * @throws \Exception
  226. */
  227. public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
  228. {
  229. $subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
  230. try {
  231. $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
  232. if (!$response->isSuccessful()) {
  233. throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
  234. }
  235. return $response->getContent();
  236. } catch (\Exception $e) {
  237. if ($alt) {
  238. return $this->handle($cache, $alt, '', $ignoreErrors);
  239. }
  240. if (!$ignoreErrors) {
  241. throw $e;
  242. }
  243. }
  244. }
  245. }