PageRenderTime 37ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpCache/Esi.php

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