Esi.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. * Constructor.
  34. *
  35. * @param array $contentTypes An array of content-type that should be parsed for ESI information
  36. * (default: text/html, text/xml, application/xhtml+xml, and application/xml)
  37. */
  38. public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
  39. {
  40. $this->contentTypes = $contentTypes;
  41. }
  42. public function getName()
  43. {
  44. return 'esi';
  45. }
  46. /**
  47. * Returns a new cache strategy instance.
  48. *
  49. * @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
  50. */
  51. public function createCacheStrategy()
  52. {
  53. return new ResponseCacheStrategy();
  54. }
  55. /**
  56. * Checks that at least one surrogate has ESI/1.0 capability.
  57. *
  58. * @param Request $request A Request instance
  59. *
  60. * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
  61. */
  62. public function hasSurrogateCapability(Request $request)
  63. {
  64. if (null === $value = $request->headers->get('Surrogate-Capability')) {
  65. return false;
  66. }
  67. return false !== strpos($value, 'ESI/1.0');
  68. }
  69. /**
  70. * Adds ESI/1.0 capability to the given Request.
  71. *
  72. * @param Request $request A Request instance
  73. */
  74. public function addSurrogateCapability(Request $request)
  75. {
  76. $current = $request->headers->get('Surrogate-Capability');
  77. $new = 'symfony2="ESI/1.0"';
  78. $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
  79. }
  80. /**
  81. * Adds HTTP headers to specify that the Response needs to be parsed for ESI.
  82. *
  83. * This method only adds an ESI HTTP header if the Response has some ESI tags.
  84. *
  85. * @param Response $response A Response instance
  86. */
  87. public function addSurrogateControl(Response $response)
  88. {
  89. if (false !== strpos($response->getContent(), '<esi:include')) {
  90. $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
  91. }
  92. }
  93. /**
  94. * Checks that the Response needs to be parsed for ESI tags.
  95. *
  96. * @param Response $response A Response instance
  97. *
  98. * @return bool true if the Response needs to be parsed, false otherwise
  99. */
  100. public function needsParsing(Response $response)
  101. {
  102. if (!$control = $response->headers->get('Surrogate-Control')) {
  103. return false;
  104. }
  105. return (bool) preg_match('#content="[^"]*ESI/1.0[^"]*"#', $control);
  106. }
  107. /**
  108. * Renders an ESI tag.
  109. *
  110. * @param string $uri A URI
  111. * @param string $alt An alternate URI
  112. * @param bool $ignoreErrors Whether to ignore errors or not
  113. * @param string $comment A comment to add as an esi:include tag
  114. *
  115. * @return string
  116. */
  117. public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
  118. {
  119. $html = sprintf('<esi:include src="%s"%s%s />',
  120. $uri,
  121. $ignoreErrors ? ' onerror="continue"' : '',
  122. $alt ? sprintf(' alt="%s"', $alt) : ''
  123. );
  124. if (!empty($comment)) {
  125. return sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $html);
  126. }
  127. return $html;
  128. }
  129. /**
  130. * Replaces a Response ESI tags with the included resource content.
  131. *
  132. * @param Request $request A Request instance
  133. * @param Response $response A Response instance
  134. *
  135. * @return Response
  136. */
  137. public function process(Request $request, Response $response)
  138. {
  139. $type = $response->headers->get('Content-Type');
  140. if (empty($type)) {
  141. $type = 'text/html';
  142. }
  143. $parts = explode(';', $type);
  144. if (!in_array($parts[0], $this->contentTypes)) {
  145. return $response;
  146. }
  147. // we don't use a proper XML parser here as we can have ESI tags in a plain text response
  148. $content = $response->getContent();
  149. $content = preg_replace('#<esi\:remove>.*?</esi\:remove>#s', '', $content);
  150. $content = preg_replace('#<esi\:comment[^>]+>#s', '', $content);
  151. $chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
  152. $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
  153. $i = 1;
  154. while (isset($chunks[$i])) {
  155. $options = array();
  156. preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
  157. foreach ($matches as $set) {
  158. $options[$set[1]] = $set[2];
  159. }
  160. if (!isset($options['src'])) {
  161. throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
  162. }
  163. $chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
  164. var_export($options['src'], true),
  165. var_export(isset($options['alt']) ? $options['alt'] : '', true),
  166. isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false'
  167. );
  168. ++$i;
  169. $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]);
  170. ++$i;
  171. }
  172. $content = implode('', $chunks);
  173. $response->setContent($content);
  174. $response->headers->set('X-Body-Eval', 'ESI');
  175. // remove ESI/1.0 from the Surrogate-Control header
  176. if ($response->headers->has('Surrogate-Control')) {
  177. $value = $response->headers->get('Surrogate-Control');
  178. if ('content="ESI/1.0"' == $value) {
  179. $response->headers->remove('Surrogate-Control');
  180. } elseif (preg_match('#,\s*content="ESI/1.0"#', $value)) {
  181. $response->headers->set('Surrogate-Control', preg_replace('#,\s*content="ESI/1.0"#', '', $value));
  182. } elseif (preg_match('#content="ESI/1.0",\s*#', $value)) {
  183. $response->headers->set('Surrogate-Control', preg_replace('#content="ESI/1.0",\s*#', '', $value));
  184. }
  185. }
  186. }
  187. /**
  188. * Handles an ESI from the cache.
  189. *
  190. * @param HttpCache $cache An HttpCache instance
  191. * @param string $uri The main URI
  192. * @param string $alt An alternative URI
  193. * @param bool $ignoreErrors Whether to ignore errors or not
  194. *
  195. * @return string
  196. *
  197. * @throws \RuntimeException
  198. * @throws \Exception
  199. */
  200. public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
  201. {
  202. $subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
  203. try {
  204. $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
  205. if (!$response->isSuccessful()) {
  206. throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
  207. }
  208. return $response->getContent();
  209. } catch (\Exception $e) {
  210. if ($alt) {
  211. return $this->handle($cache, $alt, '', $ignoreErrors);
  212. }
  213. if (!$ignoreErrors) {
  214. throw $e;
  215. }
  216. }
  217. }
  218. }