Drupal investigation

Esi.php 10KB

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