Esi.php 8.1 KB

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