updated-packages

This commit is contained in:
RafficMohammed
2023-01-08 00:13:22 +05:30
parent 3ff7df7487
commit da241bacb6
12659 changed files with 563377 additions and 510538 deletions

View File

@@ -24,16 +24,16 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
abstract class AbstractSurrogate implements SurrogateInterface
{
protected $contentTypes;
protected $phpEscapeMap = array(
array('<?', '<%', '<s', '<S'),
array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
);
protected $phpEscapeMap = [
['<?', '<%', '<s', '<S'],
['<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'],
];
/**
* @param array $contentTypes An array of content-type that should be parsed for Surrogate information
* (default: text/html, text/xml, application/xhtml+xml, and application/xml)
*/
public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
public function __construct(array $contentTypes = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'])
{
$this->contentTypes = $contentTypes;
}
@@ -57,7 +57,7 @@ abstract class AbstractSurrogate implements SurrogateInterface
return false;
}
return false !== strpos($value, sprintf('%s/1.0', strtoupper($this->getName())));
return str_contains($value, sprintf('%s/1.0', strtoupper($this->getName())));
}
/**
@@ -90,13 +90,13 @@ abstract class AbstractSurrogate implements SurrogateInterface
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
{
$subRequest = Request::create($uri, Request::METHOD_GET, array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
$subRequest = Request::create($uri, Request::METHOD_GET, [], $cache->getRequest()->cookies->all(), [], $cache->getRequest()->server->all());
try {
$response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
if (!$response->isSuccessful()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
if (!$response->isSuccessful() && Response::HTTP_NOT_MODIFIED !== $response->getStatusCode()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %d).', $subRequest->getUri(), $response->getStatusCode()));
}
return $response->getContent();
@@ -109,6 +109,8 @@ abstract class AbstractSurrogate implements SurrogateInterface
throw $e;
}
}
return '';
}
/**

View File

@@ -37,7 +37,7 @@ class Esi extends AbstractSurrogate
*/
public function addSurrogateControl(Response $response)
{
if (false !== strpos($response->getContent(), '<esi:include')) {
if (str_contains($response->getContent(), '<esi:include')) {
$response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
}
}
@@ -80,13 +80,13 @@ class Esi extends AbstractSurrogate
$content = preg_replace('#<esi\:remove>.*?</esi\:remove>#s', '', $content);
$content = preg_replace('#<esi\:comment[^>]+>#s', '', $content);
$chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
$chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
$chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
$i = 1;
while (isset($chunks[$i])) {
$options = array();
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
$options = [];
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
}
@@ -97,7 +97,7 @@ class Esi extends AbstractSurrogate
$chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
var_export($options['src'], true),
var_export(isset($options['alt']) ? $options['alt'] : '', true),
var_export($options['alt'] ?? '', true),
isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false'
);
++$i;
@@ -111,5 +111,7 @@ class Esi extends AbstractSurrogate
// remove ESI/1.0 from the Surrogate-Control header
$this->removeFromControl($response);
return $response;
}
}

View File

@@ -5,12 +5,14 @@
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* This code is partially based on the Rack-Cache library by Ryan Tomayko,
* which is released under the MIT license.
* (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\HttpCache;
@@ -32,15 +34,22 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
private $request;
private $surrogate;
private $surrogateCacheStrategy;
private $options = array();
private $traces = array();
private $options = [];
private $traces = [];
/**
* Constructor.
*
* The available options are:
*
* * debug: If true, the traces are added as a HTTP header to ease debugging
* * debug If true, exceptions are thrown when things go wrong. Otherwise, the cache
* will try to carry on and deliver a meaningful response.
*
* * trace_level May be one of 'none', 'short' and 'full'. For 'short', a concise trace of the
* master request will be added as an HTTP header. 'full' will add traces for all
* requests (including ESI subrequests). (default: 'full' if in debug; 'none' otherwise)
*
* * trace_header Header name to use for traces. (default: X-Symfony-Cache)
*
* * default_ttl The number of seconds that a cache entry should be considered
* fresh when no explicit freshness information is provided in
@@ -70,24 +79,30 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* This setting is overridden by the stale-if-error HTTP Cache-Control extension
* (see RFC 5861).
*/
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = [])
{
$this->store = $store;
$this->kernel = $kernel;
$this->surrogate = $surrogate;
// needed in case there is a fatal error because the backend is too slow to respond
register_shutdown_function(array($this->store, 'cleanup'));
register_shutdown_function([$this->store, 'cleanup']);
$this->options = array_merge(array(
$this->options = array_merge([
'debug' => false,
'default_ttl' => 0,
'private_headers' => array('Authorization', 'Cookie'),
'private_headers' => ['Authorization', 'Cookie'],
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
), $options);
'trace_level' => 'none',
'trace_header' => 'X-Symfony-Cache',
], $options);
if (!isset($options['trace_level'])) {
$this->options['trace_level'] = $this->options['debug'] ? 'full' : 'none';
}
}
/**
@@ -110,6 +125,23 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
return $this->traces;
}
private function addTraces(Response $response)
{
$traceString = null;
if ('full' === $this->options['trace_level']) {
$traceString = $this->getLog();
}
if ('short' === $this->options['trace_level'] && $masterId = array_key_first($this->traces)) {
$traceString = implode('/', $this->traces[$masterId]);
}
if (null !== $traceString) {
$response->headers->add([$this->options['trace_header'] => $traceString]);
}
}
/**
* Returns a log message for the events of the last request processing.
*
@@ -117,7 +149,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
*/
public function getLog()
{
$log = array();
$log = [];
foreach ($this->traces as $request => $traces) {
$log[] = sprintf('%s: %s', $request, implode(', ', $traces));
}
@@ -164,7 +196,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
{
// FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->traces = array();
$this->traces = [];
// Keep a clone of the original request for surrogates so they can access it.
// We must clone here to get a separate instance because the application will modify the request during
// the application flow (we know it always does because we do ourselves by setting REMOTE_ADDR to 127.0.0.1
@@ -175,9 +207,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
}
$this->traces[$this->getTraceKey($request)] = array();
$this->traces[$this->getTraceKey($request)] = [];
if (!$request->isMethodSafe(false)) {
if (!$request->isMethodSafe()) {
$response = $this->invalidate($request, $catch);
} elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
$response = $this->pass($request, $catch);
@@ -194,8 +226,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$this->restoreResponseBody($request, $response);
if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
$response->headers->set('X-Symfony-Cache', $this->getLog());
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->addTraces($response);
}
if (null !== $this->surrogate) {
@@ -226,8 +258,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Forwards the Request to the backend without storing the Response in the cache.
*
* @param Request $request A Request instance
* @param bool $catch Whether to process exceptions
* @param bool $catch Whether to process exceptions
*
* @return Response A Response instance
*/
@@ -241,8 +272,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Invalidates non-safe methods (like POST, PUT, and DELETE).
*
* @param Request $request A Request instance
* @param bool $catch Whether to process exceptions
* @param bool $catch Whether to process exceptions
*
* @return Response A Response instance
*
@@ -260,9 +290,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$this->store->invalidate($request);
// As per the RFC, invalidate Location and Content-Location URLs if present
foreach (array('Location', 'Content-Location') as $header) {
foreach (['Location', 'Content-Location'] as $header) {
if ($uri = $response->headers->get($header)) {
$subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
$subRequest = Request::create($uri, 'get', [], [], [], $request->server->all());
$this->store->invalidate($subRequest);
}
@@ -290,8 +320,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* the backend using conditional GET. When no matching cache entry is found,
* it triggers "miss" processing.
*
* @param Request $request A Request instance
* @param bool $catch Whether to process exceptions
* @param bool $catch Whether to process exceptions
*
* @return Response A Response instance
*
@@ -323,6 +352,10 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
return $this->validate($request, $entry, $catch);
}
if ($entry->headers->hasCacheControlDirective('no-cache')) {
return $this->validate($request, $entry, $catch);
}
$this->record($request, 'fresh');
$entry->headers->set('Age', $entry->getAge());
@@ -336,9 +369,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* The original request is used as a template for a conditional
* GET request with the backend.
*
* @param Request $request A Request instance
* @param Response $entry A Response instance to validate
* @param bool $catch Whether to process exceptions
* @param bool $catch Whether to process exceptions
*
* @return Response A Response instance
*/
@@ -352,15 +383,17 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
// add our cached last-modified validator
$subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
if ($entry->headers->has('Last-Modified')) {
$subRequest->headers->set('If-Modified-Since', $entry->headers->get('Last-Modified'));
}
// Add our cached etag validator to the environment.
// We keep the etags from the client to handle the case when the client
// has a different private valid entry which is not cached here.
$cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
$cachedEtags = $entry->getEtag() ? [$entry->getEtag()] : [];
$requestEtags = $request->getETags();
if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
$subRequest->headers->set('if_none_match', implode(', ', $etags));
$subRequest->headers->set('If-None-Match', implode(', ', $etags));
}
$response = $this->forward($subRequest, $catch, $entry);
@@ -377,7 +410,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$entry = clone $entry;
$entry->headers->remove('Date');
foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
foreach (['Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'] as $name) {
if ($response->headers->has($name)) {
$entry->headers->set($name, $response->headers->get($name));
}
@@ -399,8 +432,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* Unconditionally fetches a fresh response from the backend and
* stores it in the cache if is cacheable.
*
* @param Request $request A Request instance
* @param bool $catch Whether to process exceptions
* @param bool $catch Whether to process exceptions
*
* @return Response A Response instance
*/
@@ -414,8 +446,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
// avoid that the backend sends no content
$subRequest->headers->remove('if_modified_since');
$subRequest->headers->remove('if_none_match');
$subRequest->headers->remove('If-Modified-Since');
$subRequest->headers->remove('If-None-Match');
$response = $this->forward($subRequest, $catch);
@@ -432,9 +464,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* All backend requests (cache passes, fetches, cache validations)
* run through this method.
*
* @param Request $request A Request instance
* @param bool $catch Whether to catch exceptions or not
* @param Response $entry A Response instance (the stale entry if present, null otherwise)
* @param bool $catch Whether to catch exceptions or not
* @param Response|null $entry A Response instance (the stale entry if present, null otherwise)
*
* @return Response A Response instance
*/
@@ -447,13 +478,37 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
// always a "master" request (as the real master request can be in cache)
$response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $catch);
// we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
if (null !== $entry && \in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
/*
* Support stale-if-error given on Responses or as a config option.
* RFC 7234 summarizes in Section 4.2.4 (but also mentions with the individual
* Cache-Control directives) that
*
* A cache MUST NOT generate a stale response if it is prohibited by an
* explicit in-protocol directive (e.g., by a "no-store" or "no-cache"
* cache directive, a "must-revalidate" cache-response-directive, or an
* applicable "s-maxage" or "proxy-revalidate" cache-response-directive;
* see Section 5.2.2).
*
* https://tools.ietf.org/html/rfc7234#section-4.2.4
*
* We deviate from this in one detail, namely that we *do* serve entries in the
* stale-if-error case even if they have a `s-maxage` Cache-Control directive.
*/
if (null !== $entry
&& \in_array($response->getStatusCode(), [500, 502, 503, 504])
&& !$entry->headers->hasCacheControlDirective('no-cache')
&& !$entry->mustRevalidate()
) {
if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
$age = $this->options['stale_if_error'];
}
if (abs($entry->getTtl()) < $age) {
/*
* stale-if-error gives the (extra) time that the Response may be used *after* it has become stale.
* So we compare the time the $entry has been sitting in the cache already with the
* time it was fresh plus the allowed grace period.
*/
if ($entry->getAge() <= $entry->getMaxAge() + $age) {
$this->record($request, 'stale-if-error');
return $entry;
@@ -612,10 +667,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Checks if the Request includes authorization or other sensitive information
* that should cause the Response to be considered private by default.
*
* @return bool true if the Request is private, false otherwise
*/
private function isPrivateRequest(Request $request)
private function isPrivateRequest(Request $request): bool
{
foreach ($this->options['private_headers'] as $key) {
$key = strtolower(str_replace('HTTP_', '', $key));
@@ -665,7 +718,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$timeout = $this->options['stale_while_revalidate'];
}
return abs($entry->getTtl()) < $timeout;
return abs($entry->getTtl() ?? 0) < $timeout;
}
/**

View File

@@ -5,10 +5,6 @@
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* This code is partially based on the Rack-Cache library by Ryan Tomayko,
* which is released under the MIT license.
* (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@@ -28,30 +24,72 @@ use Symfony\Component\HttpFoundation\Response;
*/
class ResponseCacheStrategy implements ResponseCacheStrategyInterface
{
private $cacheable = true;
/**
* Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
*/
private const OVERRIDE_DIRECTIVES = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate'];
/**
* Cache-Control headers that are sent to the final response if they appear in ALL of the responses.
*/
private const INHERIT_DIRECTIVES = ['public', 'immutable'];
private $embeddedResponses = 0;
private $ttls = array();
private $maxAges = array();
private $isNotCacheableResponseEmbedded = false;
private $age = 0;
private $flagDirectives = [
'no-cache' => null,
'no-store' => null,
'no-transform' => null,
'must-revalidate' => null,
'proxy-revalidate' => null,
'public' => null,
'private' => null,
'immutable' => null,
];
private $ageDirectives = [
'max-age' => null,
's-maxage' => null,
'expires' => null,
];
/**
* {@inheritdoc}
*/
public function add(Response $response)
{
if (!$response->isFresh() || !$response->isCacheable()) {
$this->cacheable = false;
} else {
$maxAge = $response->getMaxAge();
$this->ttls[] = $response->getTtl();
$this->maxAges[] = $maxAge;
++$this->embeddedResponses;
if (null === $maxAge) {
$this->isNotCacheableResponseEmbedded = true;
foreach (self::OVERRIDE_DIRECTIVES as $directive) {
if ($response->headers->hasCacheControlDirective($directive)) {
$this->flagDirectives[$directive] = true;
}
}
++$this->embeddedResponses;
foreach (self::INHERIT_DIRECTIVES as $directive) {
if (false !== $this->flagDirectives[$directive]) {
$this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
}
}
$age = $response->getAge();
$this->age = max($this->age, $age);
if ($this->willMakeFinalResponseUncacheable($response)) {
$this->isNotCacheableResponseEmbedded = true;
return;
}
$isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public');
$maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null;
$this->storeRelativeAgeDirective('max-age', $maxAge, $age, $isHeuristicallyCacheable);
$sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge;
$this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge, $age, $isHeuristicallyCacheable);
$expires = $response->getExpires();
$expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0, $isHeuristicallyCacheable);
}
/**
@@ -64,33 +102,133 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
return;
}
// Remove validation related headers in order to avoid browsers using
// their own cache, because some of the response content comes from
// at least one embedded response (which likely has a different caching strategy).
if ($response->isValidateable()) {
$response->setEtag(null);
$response->setLastModified(null);
}
// Remove validation related headers of the master response,
// because some of the response content comes from at least
// one embedded response (which likely has a different caching strategy).
$response->setEtag(null);
$response->setLastModified(null);
if (!$response->isFresh() || !$response->isCacheable()) {
$this->cacheable = false;
}
$this->add($response);
if (!$this->cacheable) {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
$response->headers->set('Age', $this->age);
if ($this->isNotCacheableResponseEmbedded) {
if ($this->flagDirectives['no-store']) {
$response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
} else {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
}
return;
}
$this->ttls[] = $response->getTtl();
$this->maxAges[] = $response->getMaxAge();
$flags = array_filter($this->flagDirectives);
if ($this->isNotCacheableResponseEmbedded) {
$response->headers->removeCacheControlDirective('s-maxage');
} elseif (null !== $maxAge = min($this->maxAges)) {
$response->setSharedMaxAge($maxAge);
$response->headers->set('Age', $maxAge - min($this->ttls));
if (isset($flags['must-revalidate'])) {
$flags['no-cache'] = true;
}
$response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
$maxAge = null;
if (is_numeric($this->ageDirectives['max-age'])) {
$maxAge = $this->ageDirectives['max-age'] + $this->age;
$response->headers->addCacheControlDirective('max-age', $maxAge);
}
if (is_numeric($this->ageDirectives['s-maxage'])) {
$sMaxage = $this->ageDirectives['s-maxage'] + $this->age;
if ($maxAge !== $sMaxage) {
$response->headers->addCacheControlDirective('s-maxage', $sMaxage);
}
}
if (is_numeric($this->ageDirectives['expires'])) {
$date = clone $response->getDate();
$date->modify('+'.($this->ageDirectives['expires'] + $this->age).' seconds');
$response->setExpires($date);
}
}
/**
* RFC2616, Section 13.4.
*
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
*/
private function willMakeFinalResponseUncacheable(Response $response): bool
{
// RFC2616: A response received with a status code of 200, 203, 300, 301 or 410
// MAY be stored by a cache […] unless a cache-control directive prohibits caching.
if ($response->headers->hasCacheControlDirective('no-cache')
|| $response->headers->getCacheControlDirective('no-store')
) {
return true;
}
// Last-Modified and Etag headers cannot be merged, they render the response uncacheable
// by default (except if the response also has max-age etc.).
if (\in_array($response->getStatusCode(), [200, 203, 300, 301, 410])
&& null === $response->getLastModified()
&& null === $response->getEtag()
) {
return false;
}
// RFC2616: A response received with any other status code (e.g. status codes 302 and 307)
// MUST NOT be returned in a reply to a subsequent request unless there are
// cache-control directives or another header(s) that explicitly allow it.
$cacheControl = ['max-age', 's-maxage', 'must-revalidate', 'proxy-revalidate', 'public', 'private'];
foreach ($cacheControl as $key) {
if ($response->headers->hasCacheControlDirective($key)) {
return false;
}
}
if ($response->headers->has('Expires')) {
return false;
}
return true;
}
/**
* Store lowest max-age/s-maxage/expires for the final response.
*
* The response might have been stored in cache a while ago. To keep things comparable,
* we have to subtract the age so that the value is normalized for an age of 0.
*
* If the value is lower than the currently stored value, we update the value, to keep a rolling
* minimal value of each instruction.
*
* If the value is NULL and the isHeuristicallyCacheable parameter is false, the directive will
* not be set on the final response. In this case, not all responses had the directive set and no
* value can be found that satisfies the requirements of all responses. The directive will be dropped
* from the final response.
*
* If the isHeuristicallyCacheable parameter is true, however, the current response has been marked
* as cacheable in a public (shared) cache, but did not provide an explicit lifetime that would serve
* as an upper bound. In this case, we can proceed and possibly keep the directive on the final response.
*/
private function storeRelativeAgeDirective(string $directive, ?int $value, int $age, bool $isHeuristicallyCacheable)
{
if (null === $value) {
if ($isHeuristicallyCacheable) {
/*
* See https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
* This particular response does not require maximum lifetime; heuristics might be applied.
* Other responses, however, might have more stringent requirements on maximum lifetime.
* So, return early here so that the final response can have the more limiting value set.
*/
return;
}
$this->ageDirectives[$directive] = false;
}
if (false !== $this->ageDirectives[$directive]) {
$value -= $age;
$this->ageDirectives[$directive] = null !== $this->ageDirectives[$directive] ? min($this->ageDirectives[$directive], $value) : $value;
}
$response->setMaxAge(0);
}
}

View File

@@ -34,7 +34,7 @@ class Ssi extends AbstractSurrogate
*/
public function addSurrogateControl(Response $response)
{
if (false !== strpos($response->getContent(), '<!--#include')) {
if (str_contains($response->getContent(), '<!--#include')) {
$response->headers->set('Surrogate-Control', 'content="SSI/1.0"');
}
}
@@ -65,13 +65,13 @@ class Ssi extends AbstractSurrogate
// we don't use a proper XML parser here as we can have SSI tags in a plain text response
$content = $response->getContent();
$chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
$chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
$chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
$i = 1;
while (isset($chunks[$i])) {
$options = array();
preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
$options = [];
preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
}
@@ -94,5 +94,7 @@ class Ssi extends AbstractSurrogate
// remove SSI/1.0 from the Surrogate-Control header
$this->removeFromControl($response);
return $response;
}
}

View File

@@ -38,7 +38,7 @@ class Store implements StoreInterface
throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
}
$this->keyCache = new \SplObjectStorage();
$this->locks = array();
$this->locks = [];
}
/**
@@ -48,11 +48,11 @@ class Store implements StoreInterface
{
// unlock everything
foreach ($this->locks as $lock) {
flock($lock, LOCK_UN);
flock($lock, \LOCK_UN);
fclose($lock);
}
$this->locks = array();
$this->locks = [];
}
/**
@@ -69,8 +69,8 @@ class Store implements StoreInterface
if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
return $path;
}
$h = fopen($path, 'cb');
if (!flock($h, LOCK_EX | LOCK_NB)) {
$h = fopen($path, 'c');
if (!flock($h, \LOCK_EX | \LOCK_NB)) {
fclose($h);
return $path;
@@ -92,7 +92,7 @@ class Store implements StoreInterface
$key = $this->getCacheKey($request);
if (isset($this->locks[$key])) {
flock($this->locks[$key], LOCK_UN);
flock($this->locks[$key], \LOCK_UN);
fclose($this->locks[$key]);
unset($this->locks[$key]);
@@ -114,9 +114,9 @@ class Store implements StoreInterface
return false;
}
$h = fopen($path, 'rb');
flock($h, LOCK_EX | LOCK_NB, $wouldBlock);
flock($h, LOCK_UN); // release the lock we just acquired
$h = fopen($path, 'r');
flock($h, \LOCK_EX | \LOCK_NB, $wouldBlock);
flock($h, \LOCK_UN); // release the lock we just acquired
fclose($h);
return (bool) $wouldBlock;
@@ -132,7 +132,7 @@ class Store implements StoreInterface
$key = $this->getCacheKey($request);
if (!$entries = $this->getMetadata($key)) {
return;
return null;
}
// find a cached entry that matches the request.
@@ -146,17 +146,18 @@ class Store implements StoreInterface
}
if (null === $match) {
return;
return null;
}
$headers = $match[1];
if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
return $this->restoreResponse($headers, $body);
if (file_exists($path = $this->getPath($headers['x-content-digest'][0]))) {
return $this->restoreResponse($headers, $path);
}
// TODO the metaStore referenced an entity that doesn't exist in
// the entityStore. We definitely want to return nil but we should
// also purge the entry from the meta-store when this is detected.
return null;
}
/**
@@ -174,27 +175,36 @@ class Store implements StoreInterface
$key = $this->getCacheKey($request);
$storedEnv = $this->persistRequest($request);
// write the response body to the entity store if this is the original response
if (!$response->headers->has('X-Content-Digest')) {
$digest = $this->generateContentDigest($response);
if (false === $this->save($digest, $response->getContent())) {
throw new \RuntimeException('Unable to store the entity.');
if ($response->headers->has('X-Body-File')) {
// Assume the response came from disk, but at least perform some safeguard checks
if (!$response->headers->has('X-Content-Digest')) {
throw new \RuntimeException('A restored response must have the X-Content-Digest header.');
}
$digest = $response->headers->get('X-Content-Digest');
if ($this->getPath($digest) !== $response->headers->get('X-Body-File')) {
throw new \RuntimeException('X-Body-File and X-Content-Digest do not match.');
}
// Everything seems ok, omit writing content to disk
} else {
$digest = $this->generateContentDigest($response);
$response->headers->set('X-Content-Digest', $digest);
if (!$this->save($digest, $response->getContent(), false)) {
throw new \RuntimeException('Unable to store the entity.');
}
if (!$response->headers->has('Transfer-Encoding')) {
$response->headers->set('Content-Length', \strlen($response->getContent()));
}
}
// read existing cache entries, remove non-varying, and add this one to the list
$entries = array();
$entries = [];
$vary = $response->headers->get('vary');
foreach ($this->getMetadata($key) as $entry) {
if (!isset($entry[1]['vary'][0])) {
$entry[1]['vary'] = array('');
$entry[1]['vary'] = [''];
}
if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
@@ -205,9 +215,9 @@ class Store implements StoreInterface
$headers = $this->persistResponse($response);
unset($headers['age']);
array_unshift($entries, array($storedEnv, $headers));
array_unshift($entries, [$storedEnv, $headers]);
if (false === $this->save($key, serialize($entries))) {
if (!$this->save($key, serialize($entries))) {
throw new \RuntimeException('Unable to store the metadata.');
}
@@ -234,19 +244,19 @@ class Store implements StoreInterface
$modified = false;
$key = $this->getCacheKey($request);
$entries = array();
$entries = [];
foreach ($this->getMetadata($key) as $entry) {
$response = $this->restoreResponse($entry[1]);
if ($response->isFresh()) {
$response->expire();
$modified = true;
$entries[] = array($entry[0], $this->persistResponse($response));
$entries[] = [$entry[0], $this->persistResponse($response)];
} else {
$entries[] = $entry;
}
}
if ($modified && false === $this->save($key, serialize($entries))) {
if ($modified && !$this->save($key, serialize($entries))) {
throw new \RuntimeException('Unable to store the metadata.');
}
}
@@ -258,10 +268,8 @@ class Store implements StoreInterface
* @param string $vary A Response vary header
* @param array $env1 A Request HTTP header array
* @param array $env2 A Request HTTP header array
*
* @return bool true if the two environments match, false otherwise
*/
private function requestsMatch($vary, $env1, $env2)
private function requestsMatch(?string $vary, array $env1, array $env2): bool
{
if (empty($vary)) {
return true;
@@ -269,8 +277,8 @@ class Store implements StoreInterface
foreach (preg_split('/[\s,]+/', $vary) as $header) {
$key = str_replace('_', '-', strtolower($header));
$v1 = isset($env1[$key]) ? $env1[$key] : null;
$v2 = isset($env2[$key]) ? $env2[$key] : null;
$v1 = $env1[$key] ?? null;
$v2 = $env2[$key] ?? null;
if ($v1 !== $v2) {
return false;
}
@@ -283,18 +291,14 @@ class Store implements StoreInterface
* Gets all data associated with the given key.
*
* Use this method only if you know what you are doing.
*
* @param string $key The store key
*
* @return array An array of data associated with the key
*/
private function getMetadata($key)
private function getMetadata(string $key): array
{
if (!$entries = $this->load($key)) {
return array();
return [];
}
return unserialize($entries);
return unserialize($entries) ?: [];
}
/**
@@ -319,16 +323,12 @@ class Store implements StoreInterface
/**
* Purges data for the given URL.
*
* @param string $url A URL
*
* @return bool true if the URL exists and has been purged, false otherwise
*/
private function doPurge($url)
private function doPurge(string $url): bool
{
$key = $this->getCacheKey(Request::create($url));
if (isset($this->locks[$key])) {
flock($this->locks[$key], LOCK_UN);
flock($this->locks[$key], \LOCK_UN);
fclose($this->locks[$key]);
unset($this->locks[$key]);
}
@@ -344,30 +344,25 @@ class Store implements StoreInterface
/**
* Loads data for the given key.
*
* @param string $key The store key
*
* @return string The data associated with the key
*/
private function load($key)
private function load(string $key): ?string
{
$path = $this->getPath($key);
return file_exists($path) ? file_get_contents($path) : false;
return file_exists($path) && false !== ($contents = @file_get_contents($path)) ? $contents : null;
}
/**
* Save data for the given key.
*
* @param string $key The store key
* @param string $data The data to store
*
* @return bool
*/
private function save($key, $data)
private function save(string $key, string $data, bool $overwrite = true): bool
{
$path = $this->getPath($key);
if (!$overwrite && file_exists($path)) {
return true;
}
if (isset($this->locks[$key])) {
$fp = $this->locks[$key];
@ftruncate($fp, 0);
@@ -384,7 +379,7 @@ class Store implements StoreInterface
}
$tmpFile = tempnam(\dirname($path), basename($path));
if (false === $fp = @fopen($tmpFile, 'wb')) {
if (false === $fp = @fopen($tmpFile, 'w')) {
@unlink($tmpFile);
return false;
@@ -406,6 +401,8 @@ class Store implements StoreInterface
}
@chmod($path, 0666 & ~umask());
return true;
}
public function getPath($key)
@@ -432,10 +429,8 @@ class Store implements StoreInterface
/**
* Returns a cache key for the given Request.
*
* @return string A key for the given Request
*/
private function getCacheKey(Request $request)
private function getCacheKey(Request $request): string
{
if (isset($this->keyCache[$request])) {
return $this->keyCache[$request];
@@ -446,44 +441,35 @@ class Store implements StoreInterface
/**
* Persists the Request HTTP headers.
*
* @return array An array of HTTP headers
*/
private function persistRequest(Request $request)
private function persistRequest(Request $request): array
{
return $request->headers->all();
}
/**
* Persists the Response HTTP headers.
*
* @return array An array of HTTP headers
*/
private function persistResponse(Response $response)
private function persistResponse(Response $response): array
{
$headers = $response->headers->all();
$headers['X-Status'] = array($response->getStatusCode());
$headers['X-Status'] = [$response->getStatusCode()];
return $headers;
}
/**
* Restores a Response from the HTTP headers and body.
*
* @param array $headers An array of HTTP headers for the Response
* @param string $body The Response body
*
* @return Response
*/
private function restoreResponse($headers, $body = null)
private function restoreResponse(array $headers, string $path = null): Response
{
$status = $headers['X-Status'][0];
unset($headers['X-Status']);
if (null !== $body) {
$headers['X-Body-File'] = array($body);
if (null !== $path) {
$headers['X-Body-File'] = [$path];
}
return new Response($body, $status, $headers);
return new Response($path, $status, $headers);
}
}

View File

@@ -32,13 +32,13 @@ class SubRequestHandler
// remove untrusted values
$remoteAddr = $request->server->get('REMOTE_ADDR');
if (!IpUtils::checkIp($remoteAddr, $trustedProxies)) {
$trustedHeaders = array(
$trustedHeaders = [
'FORWARDED' => $trustedHeaderSet & Request::HEADER_FORWARDED,
'X_FORWARDED_FOR' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_FOR,
'X_FORWARDED_HOST' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_HOST,
'X_FORWARDED_PROTO' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PROTO,
'X_FORWARDED_PORT' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PORT,
);
];
foreach (array_filter($trustedHeaders) as $name => $key) {
$request->headers->remove($name);
$request->server->remove('HTTP_'.$name);
@@ -46,8 +46,8 @@ class SubRequestHandler
}
// compute trusted values, taking any trusted proxies into account
$trustedIps = array();
$trustedValues = array();
$trustedIps = [];
$trustedValues = [];
foreach (array_reverse($request->getClientIps()) as $ip) {
$trustedIps[] = $ip;
$trustedValues[] = sprintf('for="%s"', $ip);
@@ -78,7 +78,7 @@ class SubRequestHandler
// ensure 127.0.0.1 is set as trusted proxy
if (!IpUtils::checkIp('127.0.0.1', $trustedProxies)) {
Request::setTrustedProxies(array_merge($trustedProxies, array('127.0.0.1')), Request::getTrustedHeaderSet());
Request::setTrustedProxies(array_merge($trustedProxies, ['127.0.0.1']), Request::getTrustedHeaderSet());
}
try {

View File

@@ -78,10 +78,9 @@ interface SurrogateInterface
/**
* Handles a Surrogate from the cache.
*
* @param HttpCache $cache An HttpCache instance
* @param string $uri The main URI
* @param string $alt An alternative URI
* @param bool $ignoreErrors Whether to ignore errors or not
* @param string $uri The main URI
* @param string $alt An alternative URI
* @param bool $ignoreErrors Whether to ignore errors or not
*
* @return string
*