No Description

Esi.php 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. /**
  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. public function getName()
  39. {
  40. return 'esi';
  41. }
  42. /**
  43. * Returns a new cache strategy instance.
  44. *
  45. * @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
  46. */
  47. public function createCacheStrategy()
  48. {
  49. return new EsiResponseCacheStrategy();
  50. }
  51. /**
  52. * Checks that at least one surrogate has ESI/1.0 capability.
  53. *
  54. * @param Request $request A Request instance
  55. *
  56. * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
  57. */
  58. public function hasSurrogateCapability(Request $request)
  59. {
  60. return $this->hasSurrogateEsiCapability($request);
  61. }
  62. /**
  63. * Checks that at least one surrogate has ESI/1.0 capability.
  64. *
  65. * @param Request $request A Request instance
  66. *
  67. * @return bool true if one surrogate has ESI/1.0 capability, false otherwise
  68. *
  69. * @deprecated Deprecated since version 2.6, to be removed in 3.0. Use hasSurrogateCapability() instead
  70. */
  71. public function hasSurrogateEsiCapability(Request $request)
  72. {
  73. if (null === $value = $request->headers->get('Surrogate-Capability')) {
  74. return false;
  75. }
  76. return false !== strpos($value, 'ESI/1.0');
  77. }
  78. /**
  79. * Adds ESI/1.0 capability to the given Request.
  80. *
  81. * @param Request $request A Request instance
  82. */
  83. public function addSurrogateCapability(Request $request)
  84. {
  85. $this->addSurrogateEsiCapability($request);
  86. }
  87. /**
  88. * Adds ESI/1.0 capability to the given Request.
  89. *
  90. * @param Request $request A Request instance
  91. *
  92. * @deprecated Deprecated since version 2.6, to be removed in 3.0. Use addSurrogateCapability() instead
  93. */
  94. public function addSurrogateEsiCapability(Request $request)
  95. {
  96. $current = $request->headers->get('Surrogate-Capability');
  97. $new = 'symfony2="ESI/1.0"';
  98. $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new);
  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. * @param Response $response A Response instance
  106. */
  107. public function addSurrogateControl(Response $response)
  108. {
  109. if (false !== strpos($response->getContent(), '<esi:include')) {
  110. $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
  111. }
  112. }
  113. /**
  114. * Checks that the Response needs to be parsed for ESI tags.
  115. *
  116. * @param Response $response A Response instance
  117. *
  118. * @return bool true if the Response needs to be parsed, false otherwise
  119. */
  120. public function needsParsing(Response $response)
  121. {
  122. return $this->needsEsiParsing($response);
  123. }
  124. /**
  125. * Checks that the Response needs to be parsed for ESI tags.
  126. *
  127. * @param Response $response A Response instance
  128. *
  129. * @return bool true if the Response needs to be parsed, false otherwise
  130. *
  131. * @deprecated Deprecated since version 2.6, to be removed in 3.0. Use needsParsing() instead
  132. */
  133. public function needsEsiParsing(Response $response)
  134. {
  135. if (!$control = $response->headers->get('Surrogate-Control')) {
  136. return false;
  137. }
  138. return (bool) preg_match('#content="[^"]*ESI/1.0[^"]*"#', $control);
  139. }
  140. /**
  141. * Renders an ESI tag.
  142. *
  143. * @param string $uri A URI
  144. * @param string $alt An alternate URI
  145. * @param bool $ignoreErrors Whether to ignore errors or not
  146. * @param string $comment A comment to add as an esi:include tag
  147. *
  148. * @return string
  149. */
  150. public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
  151. {
  152. $html = sprintf('<esi:include src="%s"%s%s />',
  153. $uri,
  154. $ignoreErrors ? ' onerror="continue"' : '',
  155. $alt ? sprintf(' alt="%s"', $alt) : ''
  156. );
  157. if (!empty($comment)) {
  158. return sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $html);
  159. }
  160. return $html;
  161. }
  162. /**
  163. * Replaces a Response ESI tags with the included resource content.
  164. *
  165. * @param Request $request A Request instance
  166. * @param Response $response A Response instance
  167. *
  168. * @return Response
  169. */
  170. public function process(Request $request, Response $response)
  171. {
  172. $this->request = $request;
  173. $type = $response->headers->get('Content-Type');
  174. if (empty($type)) {
  175. $type = 'text/html';
  176. }
  177. $parts = explode(';', $type);
  178. if (!in_array($parts[0], $this->contentTypes)) {
  179. return $response;
  180. }
  181. // we don't use a proper XML parser here as we can have ESI tags in a plain text response
  182. $content = $response->getContent();
  183. $content = str_replace(array('<?', '<%'), array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>'), $content);
  184. $content = preg_replace_callback('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', array($this, 'handleEsiIncludeTag'), $content);
  185. $content = preg_replace('#<esi\:comment[^>]*(?:/|</esi\:comment)>#', '', $content);
  186. $content = preg_replace('#<esi\:remove>.*?</esi\:remove>#', '', $content);
  187. $response->setContent($content);
  188. $response->headers->set('X-Body-Eval', 'ESI');
  189. // remove ESI/1.0 from the Surrogate-Control header
  190. if ($response->headers->has('Surrogate-Control')) {
  191. $value = $response->headers->get('Surrogate-Control');
  192. if ('content="ESI/1.0"' == $value) {
  193. $response->headers->remove('Surrogate-Control');
  194. } elseif (preg_match('#,\s*content="ESI/1.0"#', $value)) {
  195. $response->headers->set('Surrogate-Control', preg_replace('#,\s*content="ESI/1.0"#', '', $value));
  196. } elseif (preg_match('#content="ESI/1.0",\s*#', $value)) {
  197. $response->headers->set('Surrogate-Control', preg_replace('#content="ESI/1.0",\s*#', '', $value));
  198. }
  199. }
  200. }
  201. /**
  202. * Handles an ESI from the cache.
  203. *
  204. * @param HttpCache $cache An HttpCache instance
  205. * @param string $uri The main URI
  206. * @param string $alt An alternative URI
  207. * @param bool $ignoreErrors Whether to ignore errors or not
  208. *
  209. * @return string
  210. *
  211. * @throws \RuntimeException
  212. * @throws \Exception
  213. */
  214. public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
  215. {
  216. $subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
  217. try {
  218. $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
  219. if (!$response->isSuccessful()) {
  220. throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
  221. }
  222. return $response->getContent();
  223. } catch (\Exception $e) {
  224. if ($alt) {
  225. return $this->handle($cache, $alt, '', $ignoreErrors);
  226. }
  227. if (!$ignoreErrors) {
  228. throw $e;
  229. }
  230. }
  231. }
  232. /**
  233. * Handles an ESI include tag (called internally).
  234. *
  235. * @param array $attributes An array containing the attributes.
  236. *
  237. * @return string The response content for the include.
  238. *
  239. * @throws \RuntimeException
  240. */
  241. private function handleEsiIncludeTag($attributes)
  242. {
  243. $options = array();
  244. preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $attributes[1], $matches, PREG_SET_ORDER);
  245. foreach ($matches as $set) {
  246. $options[$set[1]] = $set[2];
  247. }
  248. if (!isset($options['src'])) {
  249. throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
  250. }
  251. return sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
  252. var_export($options['src'], true),
  253. var_export(isset($options['alt']) ? $options['alt'] : '', true),
  254. isset($options['onerror']) && 'continue' == $options['onerror'] ? 'true' : 'false'
  255. );
  256. }
  257. }