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

/vendor/symfony/http-kernel/HttpCache/Esi.php

https://gitlab.com/judielsm/Handora
PHP | 296 lines | 145 code | 37 blank | 114 comment | 15 complexity | 657eae8d4b9a7b74ac776611ca3eb08f 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 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. $this->request = $request;
  180. $type = $response->headers->get('Content-Type');
  181. if (empty($type)) {
  182. $type = 'text/html';
  183. }
  184. $parts = explode(';', $type);
  185. if (!in_array($parts[0], $this->contentTypes)) {
  186. return $response;
  187. }
  188. // we don't use a proper XML parser here as we can have ESI tags in a plain text response
  189. $content = $response->getContent();
  190. $content = preg_replace('#<esi\:remove>.*?</esi\:remove>#', '', $content);
  191. $content = preg_replace('#<esi\:comment[^>]*(?:/|</esi\:comment)>#', '', $content);
  192. $chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
  193. $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
  194. $i = 1;
  195. while (isset($chunks[$i])) {
  196. $options = array();
  197. preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
  198. foreach ($matches as $set) {
  199. $options[$set[1]] = $set[2];
  200. }
  201. if (!isset($options['src'])) {
  202. throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
  203. }
  204. $chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
  205. var_export($options['src'], true),
  206. var_export(isset($options['alt']) ? $options['alt'] : '', true),
  207. isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false'
  208. );
  209. ++$i;
  210. $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]);
  211. ++$i;
  212. }
  213. $content = implode('', $chunks);
  214. $response->setContent($content);
  215. $response->headers->set('X-Body-Eval', 'ESI');
  216. // remove ESI/1.0 from the Surrogate-Control header
  217. if ($response->headers->has('Surrogate-Control')) {
  218. $value = $response->headers->get('Surrogate-Control');
  219. if ('content="ESI/1.0"' == $value) {
  220. $response->headers->remove('Surrogate-Control');
  221. } elseif (preg_match('#,\s*content="ESI/1.0"#', $value)) {
  222. $response->headers->set('Surrogate-Control', preg_replace('#,\s*content="ESI/1.0"#', '', $value));
  223. } elseif (preg_match('#content="ESI/1.0",\s*#', $value)) {
  224. $response->headers->set('Surrogate-Control', preg_replace('#content="ESI/1.0",\s*#', '', $value));
  225. }
  226. }
  227. }
  228. /**
  229. * Handles an ESI from the cache.
  230. *
  231. * @param HttpCache $cache An HttpCache instance
  232. * @param string $uri The main URI
  233. * @param string $alt An alternative URI
  234. * @param bool $ignoreErrors Whether to ignore errors or not
  235. *
  236. * @return string
  237. *
  238. * @throws \RuntimeException
  239. * @throws \Exception
  240. */
  241. public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
  242. {
  243. $subRequest = Request::create($uri, 'get', array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
  244. try {
  245. $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
  246. if (!$response->isSuccessful()) {
  247. throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
  248. }
  249. return $response->getContent();
  250. } catch (\Exception $e) {
  251. if ($alt) {
  252. return $this->handle($cache, $alt, '', $ignoreErrors);
  253. }
  254. if (!$ignoreErrors) {
  255. throw $e;
  256. }
  257. }
  258. }
  259. }