Esi.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <?php
  2. namespace Symfony\Components\HttpKernel\Cache;
  3. use Symfony\Components\HttpFoundation\Request;
  4. use Symfony\Components\HttpFoundation\Response;
  5. use Symfony\Components\HttpKernel\HttpKernelInterface;
  6. /*
  7. * This file is part of the Symfony framework.
  8. *
  9. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  10. *
  11. * This source file is subject to the MIT license that is bundled
  12. * with this source code in the file LICENSE.
  13. */
  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. * @package Symfony
  24. * @subpackage Components_HttpKernel
  25. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  26. */
  27. class Esi
  28. {
  29. protected $contentTypes;
  30. /**
  31. * Constructor.
  32. *
  33. * @param array $contentTypes An array of content-type that should be parsed for ESI information.
  34. * (default: text/html, text/xml, and application/xml)
  35. */
  36. public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xml'))
  37. {
  38. $this->contentTypes = $contentTypes;
  39. }
  40. /**
  41. * Checks that at least one surrogate has ESI/1.0 capability.
  42. *
  43. * @param Symfony\Components\HttpFoundation\Request $request A Request instance
  44. *
  45. * @return Boolean true if one surrogate has ESI/1.0 capability, false otherwise
  46. */
  47. public function hasSurrogateEsiCapability(Request $request)
  48. {
  49. if (null === $value = $request->headers->get('Surrogate-Capability')) {
  50. return false;
  51. }
  52. return preg_match('#ESI/1.0#', $value);
  53. }
  54. /**
  55. * Adds ESI/1.0 capability to the given Request.
  56. *
  57. * @param Symfony\Components\HttpFoundation\Request $request A Request instance
  58. */
  59. public function addSurrogateEsiCapability(Request $request)
  60. {
  61. $current = $request->headers->get('Surrogate-Capability');
  62. $new = 'symfony2="ESI/1.0"';
  63. $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
  64. }
  65. /**
  66. * Adds HTTP headers to specify that the Response needs to be parsed for ESI.
  67. *
  68. * This method only adds an ESI HTTP header if the Response has some ESI tags.
  69. *
  70. * @param Symfony\Components\HttpFoundation\Response $response A Response instance
  71. */
  72. public function addSurrogateControl(Response $response)
  73. {
  74. if (false !== strpos($response->getContent(), '<esi:include')) {
  75. $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
  76. }
  77. }
  78. /**
  79. * Checks that the Response needs to be parsed for ESI tags.
  80. *
  81. * @param Symfony\Components\HttpFoundation\Response $response A Response instance
  82. *
  83. * @return Boolean true if the Response needs to be parsed, false otherwise
  84. */
  85. public function needsEsiParsing(Response $response)
  86. {
  87. if (!$control = $response->headers->get('Surrogate-Control')) {
  88. return false;
  89. }
  90. return preg_match('#content="[^"]*ESI/1.0[^"]*"#', $control);
  91. }
  92. /**
  93. * Renders an ESI tag.
  94. *
  95. * @param string $uri A URI
  96. * @param string $alt An alternate URI
  97. * @param Boolean $ignoreErrors Whether to ignore errors or not
  98. * @param string $comment A comment to add as an esi:include tag
  99. */
  100. public function renderTag($uri, $alt, $ignoreErrors = true, $comment = '')
  101. {
  102. $html = sprintf('<esi:include src="%s"%s%s />',
  103. $uri,
  104. $ignoreErrors ? ' onerror="continue"' : '',
  105. $alt ? sprintf(' alt="%s"', $alt) : ''
  106. );
  107. if (!empty($comment)) {
  108. $html .= sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $output);
  109. }
  110. return $html;
  111. }
  112. /**
  113. * Replaces a Response ESI tags with the included resource content.
  114. *
  115. * @param Symfony\Components\HttpFoundation\Request $request A Request instance
  116. * @param Symfony\Components\HttpFoundation\Response $response A Response instance
  117. */
  118. public function process(Request $request, Response $response)
  119. {
  120. $this->request = $request;
  121. $type = $response->headers->get('Content-Type');
  122. if (empty($type)) {
  123. $type = 'text/html';
  124. }
  125. $parts = implode(';', $type);
  126. if (!in_array($parts[0], $this->contentTypes)) {
  127. return $response;
  128. }
  129. // we don't use a proper XML parser here as we can have ESI tags in a plain text response
  130. $content = $response->getContent();
  131. $content = preg_replace_callback('#<esi\:include\s+(.+?)\s*/>#', array($this, 'handleEsiIncludeTag'), $content);
  132. $content = preg_replace('#<esi\:comment[^>]*/>#', '', $content);
  133. $content = preg_replace('#<esi\:remove>.*?</esi\:remove>#', '', $content);
  134. $response->setContent($content);
  135. $response->headers->set('X-Body-Eval', 'ESI');
  136. // remove ESI/1.0 from the Surrogate-Control header
  137. $value = $response->headers->get('Surrogate-Control');
  138. if (preg_match('#^content="ESI/1.0"$#', $value)) {
  139. $response->headers->delete('Surrogate-Control');
  140. } else {
  141. $response->headers->set('Surrogate-Control', preg_replace('#ESI/1.0#', '', $value));
  142. }
  143. }
  144. /**
  145. * Handles an ESI from the cache.
  146. *
  147. * @param Symfony\Components\HttpKernel\Cache\Cache $cache A Cache instance
  148. * @param string $uri The main URI
  149. * @param string $alt An alternative URI
  150. * @param Boolean $ignoreErrors Whether to ignore errors or not
  151. */
  152. public function handle(Cache $cache, $uri, $alt, $ignoreErrors)
  153. {
  154. $subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
  155. try {
  156. return $cache->handle($subRequest, HttpKernelInterface::EMBEDDED_REQUEST, true);
  157. } catch (\Exception $e) {
  158. if ($alt) {
  159. return $this->handle($cache, $alt, '', $ignoreErrors);
  160. }
  161. if (!$ignoreErrors) {
  162. throw $e;
  163. }
  164. }
  165. }
  166. /**
  167. * Handles an ESI include tag (called internally).
  168. *
  169. * @param array $attributes An array containing the attributes.
  170. *
  171. * @return string The response content for the include.
  172. */
  173. protected function handleEsiIncludeTag($attributes)
  174. {
  175. $options = array();
  176. preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $attributes[1], $matches, PREG_SET_ORDER);
  177. foreach ($matches as $set) {
  178. $options[$set[1]] = $set[2];
  179. }
  180. if (!isset($options['src'])) {
  181. throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
  182. }
  183. return sprintf('<?php echo $this->esi->handle($this, \'%s\', \'%s\', %s)->getContent() ?>'."\n",
  184. $options['src'],
  185. isset($options['alt']) ? $options['alt'] : null,
  186. isset($options['onerror']) && 'continue' == $options['onerror'] ? 'true' : 'false'
  187. );
  188. }
  189. }