PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/Pasantias/pasantiasASLG
PHP | 706 lines | 357 code | 105 blank | 244 comment | 67 complexity | 67ff01be810b39b77ab67d627b8ef4d6 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. * This code is partially based on the Rack-Cache library by Ryan Tomayko,
  8. * which is released under the MIT license.
  9. * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
  10. *
  11. * For the full copyright and license information, please view the LICENSE
  12. * file that was distributed with this source code.
  13. */
  14. namespace Symfony\Component\HttpKernel\HttpCache;
  15. use Symfony\Component\HttpKernel\HttpKernelInterface;
  16. use Symfony\Component\HttpKernel\TerminableInterface;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. /**
  20. * Cache provides HTTP caching.
  21. *
  22. * @author Fabien Potencier <fabien@symfony.com>
  23. */
  24. class HttpCache implements HttpKernelInterface, TerminableInterface
  25. {
  26. private $kernel;
  27. private $store;
  28. private $request;
  29. private $surrogate;
  30. private $surrogateCacheStrategy;
  31. private $options = array();
  32. private $traces = array();
  33. /**
  34. * Constructor.
  35. *
  36. * The available options are:
  37. *
  38. * * debug: If true, the traces are added as a HTTP header to ease debugging
  39. *
  40. * * default_ttl The number of seconds that a cache entry should be considered
  41. * fresh when no explicit freshness information is provided in
  42. * a response. Explicit Cache-Control or Expires headers
  43. * override this value. (default: 0)
  44. *
  45. * * private_headers Set of request headers that trigger "private" cache-control behavior
  46. * on responses that don't explicitly state whether the response is
  47. * public or private via a Cache-Control directive. (default: Authorization and Cookie)
  48. *
  49. * * allow_reload Specifies whether the client can force a cache reload by including a
  50. * Cache-Control "no-cache" directive in the request. Set it to ``true``
  51. * for compliance with RFC 2616. (default: false)
  52. *
  53. * * allow_revalidate Specifies whether the client can force a cache revalidate by including
  54. * a Cache-Control "max-age=0" directive in the request. Set it to ``true``
  55. * for compliance with RFC 2616. (default: false)
  56. *
  57. * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the
  58. * Response TTL precision is a second) during which the cache can immediately return
  59. * a stale response while it revalidates it in the background (default: 2).
  60. * This setting is overridden by the stale-while-revalidate HTTP Cache-Control
  61. * extension (see RFC 5861).
  62. *
  63. * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which
  64. * the cache can serve a stale response when an error is encountered (default: 60).
  65. * This setting is overridden by the stale-if-error HTTP Cache-Control extension
  66. * (see RFC 5861).
  67. *
  68. * @param HttpKernelInterface $kernel An HttpKernelInterface instance
  69. * @param StoreInterface $store A Store instance
  70. * @param SurrogateInterface $surrogate A SurrogateInterface instance
  71. * @param array $options An array of options
  72. */
  73. public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
  74. {
  75. $this->store = $store;
  76. $this->kernel = $kernel;
  77. $this->surrogate = $surrogate;
  78. // needed in case there is a fatal error because the backend is too slow to respond
  79. register_shutdown_function(array($this->store, 'cleanup'));
  80. $this->options = array_merge(array(
  81. 'debug' => false,
  82. 'default_ttl' => 0,
  83. 'private_headers' => array('Authorization', 'Cookie'),
  84. 'allow_reload' => false,
  85. 'allow_revalidate' => false,
  86. 'stale_while_revalidate' => 2,
  87. 'stale_if_error' => 60,
  88. ), $options);
  89. }
  90. /**
  91. * Gets the current store.
  92. *
  93. * @return StoreInterface $store A StoreInterface instance
  94. */
  95. public function getStore()
  96. {
  97. return $this->store;
  98. }
  99. /**
  100. * Returns an array of events that took place during processing of the last request.
  101. *
  102. * @return array An array of events
  103. */
  104. public function getTraces()
  105. {
  106. return $this->traces;
  107. }
  108. /**
  109. * Returns a log message for the events of the last request processing.
  110. *
  111. * @return string A log message
  112. */
  113. public function getLog()
  114. {
  115. $log = array();
  116. foreach ($this->traces as $request => $traces) {
  117. $log[] = sprintf('%s: %s', $request, implode(', ', $traces));
  118. }
  119. return implode('; ', $log);
  120. }
  121. /**
  122. * Gets the Request instance associated with the master request.
  123. *
  124. * @return Request A Request instance
  125. */
  126. public function getRequest()
  127. {
  128. return $this->request;
  129. }
  130. /**
  131. * Gets the Kernel instance.
  132. *
  133. * @return HttpKernelInterface An HttpKernelInterface instance
  134. */
  135. public function getKernel()
  136. {
  137. return $this->kernel;
  138. }
  139. /**
  140. * Gets the Surrogate instance.
  141. *
  142. * @throws \LogicException
  143. *
  144. * @return SurrogateInterface A Surrogate instance
  145. */
  146. public function getSurrogate()
  147. {
  148. if (!$this->surrogate instanceof Esi) {
  149. throw new \LogicException('This instance of HttpCache was not set up to use ESI as surrogate handler. You must overwrite and use createSurrogate');
  150. }
  151. return $this->surrogate;
  152. }
  153. /**
  154. * Gets the Esi instance.
  155. *
  156. * @throws \LogicException
  157. *
  158. * @return Esi An Esi instance
  159. *
  160. * @deprecated since version 2.6, to be removed in 3.0. Use getSurrogate() instead
  161. */
  162. public function getEsi()
  163. {
  164. @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the getSurrogate() method instead.', E_USER_DEPRECATED);
  165. return $this->getSurrogate();
  166. }
  167. /**
  168. * {@inheritdoc}
  169. */
  170. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  171. {
  172. // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
  173. if (HttpKernelInterface::MASTER_REQUEST === $type) {
  174. $this->traces = array();
  175. $this->request = $request;
  176. if (null !== $this->surrogate) {
  177. $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy();
  178. }
  179. }
  180. $path = $request->getPathInfo();
  181. if ($qs = $request->getQueryString()) {
  182. $path .= '?'.$qs;
  183. }
  184. $this->traces[$request->getMethod().' '.$path] = array();
  185. if (!$request->isMethodSafe()) {
  186. $response = $this->invalidate($request, $catch);
  187. } elseif ($request->headers->has('expect')) {
  188. $response = $this->pass($request, $catch);
  189. } else {
  190. $response = $this->lookup($request, $catch);
  191. }
  192. $this->restoreResponseBody($request, $response);
  193. $response->setDate(\DateTime::createFromFormat('U', time(), new \DateTimeZone('UTC')));
  194. if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
  195. $response->headers->set('X-Symfony-Cache', $this->getLog());
  196. }
  197. if (null !== $this->surrogate) {
  198. if (HttpKernelInterface::MASTER_REQUEST === $type) {
  199. $this->surrogateCacheStrategy->update($response);
  200. } else {
  201. $this->surrogateCacheStrategy->add($response);
  202. }
  203. }
  204. $response->prepare($request);
  205. $response->isNotModified($request);
  206. return $response;
  207. }
  208. /**
  209. * {@inheritdoc}
  210. */
  211. public function terminate(Request $request, Response $response)
  212. {
  213. if ($this->getKernel() instanceof TerminableInterface) {
  214. $this->getKernel()->terminate($request, $response);
  215. }
  216. }
  217. /**
  218. * Forwards the Request to the backend without storing the Response in the cache.
  219. *
  220. * @param Request $request A Request instance
  221. * @param bool $catch Whether to process exceptions
  222. *
  223. * @return Response A Response instance
  224. */
  225. protected function pass(Request $request, $catch = false)
  226. {
  227. $this->record($request, 'pass');
  228. return $this->forward($request, $catch);
  229. }
  230. /**
  231. * Invalidates non-safe methods (like POST, PUT, and DELETE).
  232. *
  233. * @param Request $request A Request instance
  234. * @param bool $catch Whether to process exceptions
  235. *
  236. * @return Response A Response instance
  237. *
  238. * @throws \Exception
  239. *
  240. * @see RFC2616 13.10
  241. */
  242. protected function invalidate(Request $request, $catch = false)
  243. {
  244. $response = $this->pass($request, $catch);
  245. // invalidate only when the response is successful
  246. if ($response->isSuccessful() || $response->isRedirect()) {
  247. try {
  248. $this->store->invalidate($request);
  249. // As per the RFC, invalidate Location and Content-Location URLs if present
  250. foreach (array('Location', 'Content-Location') as $header) {
  251. if ($uri = $response->headers->get($header)) {
  252. $subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
  253. $this->store->invalidate($subRequest);
  254. }
  255. }
  256. $this->record($request, 'invalidate');
  257. } catch (\Exception $e) {
  258. $this->record($request, 'invalidate-failed');
  259. if ($this->options['debug']) {
  260. throw $e;
  261. }
  262. }
  263. }
  264. return $response;
  265. }
  266. /**
  267. * Lookups a Response from the cache for the given Request.
  268. *
  269. * When a matching cache entry is found and is fresh, it uses it as the
  270. * response without forwarding any request to the backend. When a matching
  271. * cache entry is found but is stale, it attempts to "validate" the entry with
  272. * the backend using conditional GET. When no matching cache entry is found,
  273. * it triggers "miss" processing.
  274. *
  275. * @param Request $request A Request instance
  276. * @param bool $catch whether to process exceptions
  277. *
  278. * @return Response A Response instance
  279. *
  280. * @throws \Exception
  281. */
  282. protected function lookup(Request $request, $catch = false)
  283. {
  284. // if allow_reload and no-cache Cache-Control, allow a cache reload
  285. if ($this->options['allow_reload'] && $request->isNoCache()) {
  286. $this->record($request, 'reload');
  287. return $this->fetch($request, $catch);
  288. }
  289. try {
  290. $entry = $this->store->lookup($request);
  291. } catch (\Exception $e) {
  292. $this->record($request, 'lookup-failed');
  293. if ($this->options['debug']) {
  294. throw $e;
  295. }
  296. return $this->pass($request, $catch);
  297. }
  298. if (null === $entry) {
  299. $this->record($request, 'miss');
  300. return $this->fetch($request, $catch);
  301. }
  302. if (!$this->isFreshEnough($request, $entry)) {
  303. $this->record($request, 'stale');
  304. return $this->validate($request, $entry, $catch);
  305. }
  306. $this->record($request, 'fresh');
  307. $entry->headers->set('Age', $entry->getAge());
  308. return $entry;
  309. }
  310. /**
  311. * Validates that a cache entry is fresh.
  312. *
  313. * The original request is used as a template for a conditional
  314. * GET request with the backend.
  315. *
  316. * @param Request $request A Request instance
  317. * @param Response $entry A Response instance to validate
  318. * @param bool $catch Whether to process exceptions
  319. *
  320. * @return Response A Response instance
  321. */
  322. protected function validate(Request $request, Response $entry, $catch = false)
  323. {
  324. $subRequest = clone $request;
  325. // send no head requests because we want content
  326. $subRequest->setMethod('GET');
  327. // add our cached last-modified validator
  328. $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
  329. // Add our cached etag validator to the environment.
  330. // We keep the etags from the client to handle the case when the client
  331. // has a different private valid entry which is not cached here.
  332. $cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
  333. $requestEtags = $request->getETags();
  334. if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
  335. $subRequest->headers->set('if_none_match', implode(', ', $etags));
  336. }
  337. $response = $this->forward($subRequest, $catch, $entry);
  338. if (304 == $response->getStatusCode()) {
  339. $this->record($request, 'valid');
  340. // return the response and not the cache entry if the response is valid but not cached
  341. $etag = $response->getEtag();
  342. if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
  343. return $response;
  344. }
  345. $entry = clone $entry;
  346. $entry->headers->remove('Date');
  347. foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
  348. if ($response->headers->has($name)) {
  349. $entry->headers->set($name, $response->headers->get($name));
  350. }
  351. }
  352. $response = $entry;
  353. } else {
  354. $this->record($request, 'invalid');
  355. }
  356. if ($response->isCacheable()) {
  357. $this->store($request, $response);
  358. }
  359. return $response;
  360. }
  361. /**
  362. * Forwards the Request to the backend and determines whether the response should be stored.
  363. *
  364. * This methods is triggered when the cache missed or a reload is required.
  365. *
  366. * @param Request $request A Request instance
  367. * @param bool $catch whether to process exceptions
  368. *
  369. * @return Response A Response instance
  370. */
  371. protected function fetch(Request $request, $catch = false)
  372. {
  373. $subRequest = clone $request;
  374. // send no head requests because we want content
  375. $subRequest->setMethod('GET');
  376. // avoid that the backend sends no content
  377. $subRequest->headers->remove('if_modified_since');
  378. $subRequest->headers->remove('if_none_match');
  379. $response = $this->forward($subRequest, $catch);
  380. if ($response->isCacheable()) {
  381. $this->store($request, $response);
  382. }
  383. return $response;
  384. }
  385. /**
  386. * Forwards the Request to the backend and returns the Response.
  387. *
  388. * @param Request $request A Request instance
  389. * @param bool $catch Whether to catch exceptions or not
  390. * @param Response $entry A Response instance (the stale entry if present, null otherwise)
  391. *
  392. * @return Response A Response instance
  393. */
  394. protected function forward(Request $request, $catch = false, Response $entry = null)
  395. {
  396. if ($this->surrogate) {
  397. $this->surrogate->addSurrogateCapability($request);
  398. }
  399. // modify the X-Forwarded-For header if needed
  400. $forwardedFor = $request->headers->get('X-Forwarded-For');
  401. if ($forwardedFor) {
  402. $request->headers->set('X-Forwarded-For', $forwardedFor.', '.$request->server->get('REMOTE_ADDR'));
  403. } else {
  404. $request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR'));
  405. }
  406. // fix the client IP address by setting it to 127.0.0.1 as HttpCache
  407. // is always called from the same process as the backend.
  408. $request->server->set('REMOTE_ADDR', '127.0.0.1');
  409. // make sure HttpCache is a trusted proxy
  410. if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) {
  411. $trustedProxies[] = '127.0.0.1';
  412. Request::setTrustedProxies($trustedProxies);
  413. }
  414. // always a "master" request (as the real master request can be in cache)
  415. $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
  416. // FIXME: we probably need to also catch exceptions if raw === true
  417. // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
  418. if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
  419. if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
  420. $age = $this->options['stale_if_error'];
  421. }
  422. if (abs($entry->getTtl()) < $age) {
  423. $this->record($request, 'stale-if-error');
  424. return $entry;
  425. }
  426. }
  427. $this->processResponseBody($request, $response);
  428. if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
  429. $response->setPrivate();
  430. } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
  431. $response->setTtl($this->options['default_ttl']);
  432. }
  433. return $response;
  434. }
  435. /**
  436. * Checks whether the cache entry is "fresh enough" to satisfy the Request.
  437. *
  438. * @param Request $request A Request instance
  439. * @param Response $entry A Response instance
  440. *
  441. * @return bool true if the cache entry if fresh enough, false otherwise
  442. */
  443. protected function isFreshEnough(Request $request, Response $entry)
  444. {
  445. if (!$entry->isFresh()) {
  446. return $this->lock($request, $entry);
  447. }
  448. if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
  449. return $maxAge > 0 && $maxAge >= $entry->getAge();
  450. }
  451. return true;
  452. }
  453. /**
  454. * Locks a Request during the call to the backend.
  455. *
  456. * @param Request $request A Request instance
  457. * @param Response $entry A Response instance
  458. *
  459. * @return bool true if the cache entry can be returned even if it is staled, false otherwise
  460. */
  461. protected function lock(Request $request, Response $entry)
  462. {
  463. // try to acquire a lock to call the backend
  464. $lock = $this->store->lock($request);
  465. // there is already another process calling the backend
  466. if (true !== $lock) {
  467. // check if we can serve the stale entry
  468. if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) {
  469. $age = $this->options['stale_while_revalidate'];
  470. }
  471. if (abs($entry->getTtl()) < $age) {
  472. $this->record($request, 'stale-while-revalidate');
  473. // server the stale response while there is a revalidation
  474. return true;
  475. }
  476. // wait for the lock to be released
  477. $wait = 0;
  478. while ($this->store->isLocked($request) && $wait < 5000000) {
  479. usleep(50000);
  480. $wait += 50000;
  481. }
  482. if ($wait < 5000000) {
  483. // replace the current entry with the fresh one
  484. $new = $this->lookup($request);
  485. $entry->headers = $new->headers;
  486. $entry->setContent($new->getContent());
  487. $entry->setStatusCode($new->getStatusCode());
  488. $entry->setProtocolVersion($new->getProtocolVersion());
  489. foreach ($new->headers->getCookies() as $cookie) {
  490. $entry->headers->setCookie($cookie);
  491. }
  492. } else {
  493. // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
  494. $entry->setStatusCode(503);
  495. $entry->setContent('503 Service Unavailable');
  496. $entry->headers->set('Retry-After', 10);
  497. }
  498. return true;
  499. }
  500. // we have the lock, call the backend
  501. return false;
  502. }
  503. /**
  504. * Writes the Response to the cache.
  505. *
  506. * @param Request $request A Request instance
  507. * @param Response $response A Response instance
  508. *
  509. * @throws \Exception
  510. */
  511. protected function store(Request $request, Response $response)
  512. {
  513. try {
  514. $this->store->write($request, $response);
  515. $this->record($request, 'store');
  516. $response->headers->set('Age', $response->getAge());
  517. } catch (\Exception $e) {
  518. $this->record($request, 'store-failed');
  519. if ($this->options['debug']) {
  520. throw $e;
  521. }
  522. }
  523. // now that the response is cached, release the lock
  524. $this->store->unlock($request);
  525. }
  526. /**
  527. * Restores the Response body.
  528. *
  529. * @param Request $request A Request instance
  530. * @param Response $response A Response instance
  531. */
  532. private function restoreResponseBody(Request $request, Response $response)
  533. {
  534. if ($request->isMethod('HEAD') || 304 === $response->getStatusCode()) {
  535. $response->setContent(null);
  536. $response->headers->remove('X-Body-Eval');
  537. $response->headers->remove('X-Body-File');
  538. return;
  539. }
  540. if ($response->headers->has('X-Body-Eval')) {
  541. ob_start();
  542. if ($response->headers->has('X-Body-File')) {
  543. include $response->headers->get('X-Body-File');
  544. } else {
  545. eval('; ?>'.$response->getContent().'<?php ;');
  546. }
  547. $response->setContent(ob_get_clean());
  548. $response->headers->remove('X-Body-Eval');
  549. if (!$response->headers->has('Transfer-Encoding')) {
  550. $response->headers->set('Content-Length', strlen($response->getContent()));
  551. }
  552. } elseif ($response->headers->has('X-Body-File')) {
  553. $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
  554. } else {
  555. return;
  556. }
  557. $response->headers->remove('X-Body-File');
  558. }
  559. protected function processResponseBody(Request $request, Response $response)
  560. {
  561. if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) {
  562. $this->surrogate->process($request, $response);
  563. }
  564. }
  565. /**
  566. * Checks if the Request includes authorization or other sensitive information
  567. * that should cause the Response to be considered private by default.
  568. *
  569. * @param Request $request A Request instance
  570. *
  571. * @return bool true if the Request is private, false otherwise
  572. */
  573. private function isPrivateRequest(Request $request)
  574. {
  575. foreach ($this->options['private_headers'] as $key) {
  576. $key = strtolower(str_replace('HTTP_', '', $key));
  577. if ('cookie' === $key) {
  578. if (count($request->cookies->all())) {
  579. return true;
  580. }
  581. } elseif ($request->headers->has($key)) {
  582. return true;
  583. }
  584. }
  585. return false;
  586. }
  587. /**
  588. * Records that an event took place.
  589. *
  590. * @param Request $request A Request instance
  591. * @param string $event The event name
  592. */
  593. private function record(Request $request, $event)
  594. {
  595. $path = $request->getPathInfo();
  596. if ($qs = $request->getQueryString()) {
  597. $path .= '?'.$qs;
  598. }
  599. $this->traces[$request->getMethod().' '.$path][] = $event;
  600. }
  601. }