PageRenderTime 46ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php

https://github.com/casoetan/ServerGroveLiveChat
PHP | 591 lines | 297 code | 91 blank | 203 comment | 56 complexity | adc71631724776d5861ee6dccddcf41b MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0, ISC, BSD-3-Clause
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.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\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. /**
  19. * Cache provides HTTP caching.
  20. *
  21. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  22. */
  23. class HttpCache implements HttpKernelInterface
  24. {
  25. protected $kernel;
  26. protected $traces;
  27. protected $store;
  28. protected $request;
  29. protected $esi;
  30. /**
  31. * Constructor.
  32. *
  33. * The available options are:
  34. *
  35. * * debug: If true, the traces are added as a HTTP header to ease debugging
  36. *
  37. * * default_ttl The number of seconds that a cache entry should be considered
  38. * fresh when no explicit freshness information is provided in
  39. * a response. Explicit Cache-Control or Expires headers
  40. * override this value. (default: 0)
  41. *
  42. * * private_headers Set of request headers that trigger "private" cache-control behavior
  43. * on responses that don't explicitly state whether the response is
  44. * public or private via a Cache-Control directive. (default: Authorization and Cookie)
  45. *
  46. * * allow_reload Specifies whether the client can force a cache reload by including a
  47. * Cache-Control "no-cache" directive in the request. Set it to ``true``
  48. * for compliance with RFC 2616. (default: false)
  49. *
  50. * * allow_revalidate Specifies whether the client can force a cache revalidate by including
  51. * a Cache-Control "max-age=0" directive in the request. Set it to ``true``
  52. * for compliance with RFC 2616. (default: false)
  53. *
  54. * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the
  55. * Response TTL precision is a second) during which the cache can immediately return
  56. * a stale response while it revalidates it in the background (default: 2).
  57. * This setting is overridden by the stale-while-revalidate HTTP Cache-Control
  58. * extension (see RFC 5861).
  59. *
  60. * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which
  61. * the cache can serve a stale response when an error is encountered (default: 60).
  62. * This setting is overridden by the stale-if-error HTTP Cache-Control extension
  63. * (see RFC 5861).
  64. *
  65. * @param HttpKernelInterface $kernel An HttpKernelInterface instance
  66. * @param StoreInterface $store A Store instance
  67. * @param Esi $esi An Esi instance
  68. * @param array $options An array of options
  69. */
  70. public function __construct(HttpKernelInterface $kernel, StoreInterface $store, Esi $esi = null, array $options = array())
  71. {
  72. $this->store = $store;
  73. $this->kernel = $kernel;
  74. // needed in case there is a fatal error because the backend is too slow to respond
  75. register_shutdown_function(array($this->store, 'cleanup'));
  76. $this->options = array_merge(array(
  77. 'debug' => false,
  78. 'default_ttl' => 0,
  79. 'private_headers' => array('Authorization', 'Cookie'),
  80. 'allow_reload' => false,
  81. 'allow_revalidate' => false,
  82. 'stale_while_revalidate' => 2,
  83. 'stale_if_error' => 60,
  84. ), $options);
  85. $this->esi = $esi;
  86. }
  87. /**
  88. * Returns an array of events that took place during processing of the last request.
  89. *
  90. * @return array An array of events
  91. */
  92. public function getTraces()
  93. {
  94. return $this->traces;
  95. }
  96. /**
  97. * Returns a log message for the events of the last request processing.
  98. *
  99. * @return string A log message
  100. */
  101. public function getLog()
  102. {
  103. $log = array();
  104. foreach ($this->traces as $request => $traces) {
  105. $log[] = sprintf('%s: %s', $request, implode(', ', $traces));
  106. }
  107. return implode('; ', $log);
  108. }
  109. /**
  110. * Gets the Request instance associated with the master request.
  111. *
  112. * @return Symfony\Component\HttpFoundation\Request A Request instance
  113. */
  114. public function getRequest()
  115. {
  116. return $this->request;
  117. }
  118. /**
  119. * {@inheritdoc}
  120. */
  121. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  122. {
  123. // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
  124. if (HttpKernelInterface::MASTER_REQUEST === $type) {
  125. $this->traces = array();
  126. $this->request = $request;
  127. }
  128. $path = $request->getPathInfo();
  129. if ($qs = $request->getQueryString()) {
  130. $path .= '?'.$qs;
  131. }
  132. $this->traces[$request->getMethod().' '.$path] = array();
  133. if (!$request->isMethodSafe($request)) {
  134. $response = $this->invalidate($request, $catch);
  135. } elseif ($request->headers->has('expect')) {
  136. $response = $this->pass($request, $catch);
  137. } else {
  138. $response = $this->lookup($request, $catch);
  139. }
  140. $response->isNotModified($request);
  141. $this->restoreResponseBody($request, $response);
  142. if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
  143. $response->headers->set('X-Symfony-Cache', $this->getLog());
  144. }
  145. return $response;
  146. }
  147. /**
  148. * Forwards the Request to the backend without storing the Response in the cache.
  149. *
  150. * @param Request $request A Request instance
  151. * @param Boolean $catch whether to process exceptions
  152. *
  153. * @return Response A Response instance
  154. */
  155. protected function pass(Request $request, $catch = false)
  156. {
  157. $this->record($request, 'pass');
  158. return $this->forward($request, $catch);
  159. }
  160. /**
  161. * Invalidates non-safe methods (like POST, PUT, and DELETE).
  162. *
  163. * @param Request $request A Request instance
  164. * @param Boolean $catch whether to process exceptions
  165. *
  166. * @return Response A Response instance
  167. *
  168. * @see RFC2616 13.10
  169. */
  170. protected function invalidate(Request $request, $catch = false)
  171. {
  172. $response = $this->pass($request, $catch);
  173. // invalidate only when the response is successful
  174. if ($response->isSuccessful() || $response->isRedirect()) {
  175. try {
  176. $this->store->invalidate($request, $catch);
  177. $this->record($request, 'invalidate');
  178. } catch (\Exception $e) {
  179. $this->record($request, 'invalidate-failed');
  180. if ($this->options['debug']) {
  181. throw $e;
  182. }
  183. }
  184. }
  185. return $response;
  186. }
  187. /**
  188. * Lookups a Response from the cache for the given Request.
  189. *
  190. * When a matching cache entry is found and is fresh, it uses it as the
  191. * response without forwarding any request to the backend. When a matching
  192. * cache entry is found but is stale, it attempts to "validate" the entry with
  193. * the backend using conditional GET. When no matching cache entry is found,
  194. * it triggers "miss" processing.
  195. *
  196. * @param Request $request A Request instance
  197. * @param Boolean $catch whether to process exceptions
  198. *
  199. * @return Response A Response instance
  200. */
  201. protected function lookup(Request $request, $catch = false)
  202. {
  203. // if allow_reload and no-cache Cache-Control, allow a cache reload
  204. if ($this->options['allow_reload'] && $request->isNoCache()) {
  205. $this->record($request, 'reload');
  206. return $this->fetch($request);
  207. }
  208. try {
  209. $entry = $this->store->lookup($request);
  210. } catch (\Exception $e) {
  211. $this->record($request, 'lookup-failed');
  212. if ($this->options['debug']) {
  213. throw $e;
  214. }
  215. return $this->pass($request, $catch);
  216. }
  217. if (null === $entry) {
  218. $this->record($request, 'miss');
  219. return $this->fetch($request, $catch);
  220. }
  221. if (!$this->isFreshEnough($request, $entry)) {
  222. $this->record($request, 'stale');
  223. return $this->validate($request, $entry);
  224. }
  225. $this->record($request, 'fresh');
  226. $entry->headers->set('Age', $entry->getAge());
  227. return $entry;
  228. }
  229. /**
  230. * Validates that a cache entry is fresh.
  231. *
  232. * The original request is used as a template for a conditional
  233. * GET request with the backend.
  234. *
  235. * @param Request $request A Request instance
  236. * @param Response $entry A Response instance to validate
  237. *
  238. * @return Response A Response instance
  239. */
  240. protected function validate(Request $request, Response $entry)
  241. {
  242. $subRequest = clone $request;
  243. // send no head requests because we want content
  244. $subRequest->setMethod('get');
  245. // add our cached last-modified validator
  246. $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
  247. // Add our cached etag validator to the environment.
  248. // We keep the etags from the client to handle the case when the client
  249. // has a different private valid entry which is not cached here.
  250. $cachedEtags = array($entry->getEtag());
  251. $requestEtags = $request->getEtags();
  252. $etags = array_unique(array_merge($cachedEtags, $requestEtags));
  253. $subRequest->headers->set('if_none_match', $etags ? implode(', ', $etags) : '');
  254. $response = $this->forward($subRequest, false, $entry);
  255. if (304 == $response->getStatusCode()) {
  256. $this->record($request, 'valid');
  257. // return the response and not the cache entry if the response is valid but not cached
  258. $etag = $response->getEtag();
  259. if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) {
  260. return $response;
  261. }
  262. $entry = clone $entry;
  263. $entry->headers->remove('Date');
  264. foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
  265. if ($response->headers->has($name)) {
  266. $entry->headers->set($name, $response->headers->get($name));
  267. }
  268. }
  269. $response = $entry;
  270. } else {
  271. $this->record($request, 'invalid');
  272. }
  273. if ($response->isCacheable()) {
  274. $this->store($request, $response);
  275. }
  276. return $response;
  277. }
  278. /**
  279. * Forwards the Request to the backend and determines whether the response should be stored.
  280. *
  281. * This methods is trigered when the cache missed or a reload is required.
  282. *
  283. * @param Request $request A Request instance
  284. * @param Boolean $catch whether to process exceptions
  285. *
  286. * @return Response A Response instance
  287. */
  288. protected function fetch(Request $request, $catch = false)
  289. {
  290. $subRequest = clone $request;
  291. // send no head requests because we want content
  292. $subRequest->setMethod('get');
  293. // avoid that the backend sends no content
  294. $subRequest->headers->remove('if_modified_since');
  295. $subRequest->headers->remove('if_none_match');
  296. $response = $this->forward($subRequest, $catch);
  297. if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
  298. $response->setPrivate(true);
  299. } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
  300. $response->setTtl($this->options['default_ttl']);
  301. }
  302. if ($response->isCacheable()) {
  303. $this->store($request, $response);
  304. }
  305. return $response;
  306. }
  307. /**
  308. * Forwards the Request to the backend and returns the Response.
  309. *
  310. * @param Request $request A Request instance
  311. * @param Boolean $catch Whether to catch exceptions or not
  312. * @param Response $response A Response instance (the stale entry if present, null otherwise)
  313. *
  314. * @return Response A Response instance
  315. */
  316. protected function forward(Request $request, $catch = false, Response $entry = null)
  317. {
  318. if ($this->esi) {
  319. $this->esi->addSurrogateEsiCapability($request);
  320. }
  321. // always a "master" request (as the real master request can be in cache)
  322. $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
  323. // FIXME: we probably need to also catch exceptions if raw === true
  324. // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
  325. if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
  326. if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
  327. $age = $this->options['stale_if_error'];
  328. }
  329. if (abs($entry->getTtl()) < $age) {
  330. $this->record($request, 'stale-if-error');
  331. return $entry;
  332. }
  333. }
  334. $this->processResponseBody($request, $response);
  335. return $response;
  336. }
  337. /**
  338. * Checks whether the cache entry is "fresh enough" to satisfy the Request.
  339. *
  340. * @param Request $request A Request instance
  341. * @param Response $entry A Response instance
  342. *
  343. * @return Boolean true if the cache entry if fresh enough, false otherwise
  344. */
  345. protected function isFreshEnough(Request $request, Response $entry)
  346. {
  347. if (!$entry->isFresh()) {
  348. return $this->lock($request, $entry);
  349. }
  350. if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) {
  351. return $maxAge > 0 && $maxAge >= $entry->getAge();
  352. }
  353. return true;
  354. }
  355. /**
  356. * Locks a Request during the call to the backend.
  357. *
  358. * @param Request $request A Request instance
  359. * @param Response $entry A Response instance
  360. *
  361. * @return Boolean true if the cache entry can be returned even if it is staled, false otherwise
  362. */
  363. protected function lock(Request $request, Response $entry)
  364. {
  365. // try to acquire a lock to call the backend
  366. $lock = $this->store->lock($request, $entry);
  367. // there is already another process calling the backend
  368. if (true !== $lock) {
  369. // check if we can serve the stale entry
  370. if (null === $age = $entry->headers->getCacheControlDirective('stale-while-revalidate')) {
  371. $age = $this->options['stale_while_revalidate'];
  372. }
  373. if (abs($entry->getTtl()) < $age) {
  374. $this->record($request, 'stale-while-revalidate');
  375. // server the stale response while there is a revalidation
  376. return true;
  377. } else {
  378. // wait for the lock to be released
  379. $wait = 0;
  380. while (file_exists($lock) && $wait < 5000000) {
  381. usleep($wait += 50000);
  382. }
  383. if ($wait < 2000000) {
  384. // replace the current entry with the fresh one
  385. $new = $this->lookup($request);
  386. $entry->headers = $new->headers;
  387. $entry->setContent($new->getContent());
  388. $entry->setStatusCode($new->getStatusCode());
  389. $entry->setProtocolVersion($new->getProtocolVersion());
  390. $entry->setCookies($new->getCookies());
  391. return true;
  392. } else {
  393. // backend is slow as hell, send a 503 response (to avoid the dog pile effect)
  394. $entry->setStatusCode(503);
  395. $entry->setContent('503 Service Unavailable');
  396. $entry->headers->set('Retry-After', 10);
  397. return true;
  398. }
  399. }
  400. }
  401. // we have the lock, call the backend
  402. return false;
  403. }
  404. /**
  405. * Writes the Response to the cache.
  406. *
  407. * @param Request $request A Request instance
  408. * @param Response $response A Response instance
  409. */
  410. protected function store(Request $request, Response $response)
  411. {
  412. try {
  413. $this->store->write($request, $response);
  414. $this->record($request, 'store');
  415. $response->headers->set('Age', $response->getAge());
  416. } catch (\Exception $e) {
  417. $this->record($request, 'store-failed');
  418. if ($this->options['debug']) {
  419. throw $e;
  420. }
  421. }
  422. // now that the response is cached, release the lock
  423. $this->store->unlock($request);
  424. }
  425. /**
  426. * Restores the Response body.
  427. *
  428. * @param Response $response A Response instance
  429. *
  430. * @return Response A Response instance
  431. */
  432. protected function restoreResponseBody(Request $request, Response $response)
  433. {
  434. if ('head' === strtolower($request->getMethod())) {
  435. $response->setContent('');
  436. $response->headers->remove('X-Body-Eval');
  437. $response->headers->remove('X-Body-File');
  438. return;
  439. }
  440. if ($response->headers->has('X-Body-Eval')) {
  441. ob_start();
  442. if ($response->headers->has('X-Body-File')) {
  443. include $response->headers->get('X-Body-File');
  444. } else {
  445. eval('; ?>'.$response->getContent().'<?php ;');
  446. }
  447. $response->setContent(ob_get_clean());
  448. $response->headers->remove('X-Body-Eval');
  449. } elseif ($response->headers->has('X-Body-File')) {
  450. $response->setContent(file_get_contents($response->headers->get('X-Body-File')));
  451. } else {
  452. return;
  453. }
  454. $response->headers->remove('X-Body-File');
  455. if (!$response->headers->has('Transfer-Encoding')) {
  456. $response->headers->set('Content-Length', strlen($response->getContent()));
  457. }
  458. }
  459. protected function processResponseBody(Request $request, Response $response)
  460. {
  461. if (null !== $this->esi && $this->esi->needsEsiParsing($response)) {
  462. $this->esi->process($request, $response);
  463. }
  464. }
  465. /**
  466. * Checks if the Request includes authorization or other sensitive information
  467. * that should cause the Response to be considered private by default.
  468. *
  469. * @param Request $request A Request instance
  470. *
  471. * @return Boolean true if the Request is private, false otherwise
  472. */
  473. protected function isPrivateRequest(Request $request)
  474. {
  475. foreach ($this->options['private_headers'] as $key) {
  476. $key = strtolower(str_replace('HTTP_', '', $key));
  477. if ('cookie' === $key) {
  478. if (count($request->cookies->all())) {
  479. return true;
  480. }
  481. } elseif ($request->headers->has($key)) {
  482. return true;
  483. }
  484. }
  485. return false;
  486. }
  487. /**
  488. * Records that an event took place.
  489. *
  490. * @param string $event The event name
  491. */
  492. protected function record(Request $request, $event)
  493. {
  494. $path = $request->getPathInfo();
  495. if ($qs = $request->getQueryString()) {
  496. $path .= '?'.$qs;
  497. }
  498. $this->traces[$request->getMethod().' '.$path][] = $event;
  499. }
  500. }