annotate core/modules/page_cache/src/StackMiddleware/PageCache.php @ 2:92f882872392

Trusted hosts, + remove migration modules
author Chris Cannam
date Tue, 05 Dec 2017 09:26:43 +0000
parents 4c8ae668cc8c
children 129ea1e6d783
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\page_cache\StackMiddleware;
Chris@0 4
Chris@0 5 use Drupal\Core\Cache\Cache;
Chris@0 6 use Drupal\Core\Cache\CacheableResponseInterface;
Chris@0 7 use Drupal\Core\Cache\CacheBackendInterface;
Chris@0 8 use Drupal\Core\PageCache\RequestPolicyInterface;
Chris@0 9 use Drupal\Core\PageCache\ResponsePolicyInterface;
Chris@0 10 use Drupal\Core\Site\Settings;
Chris@0 11 use Symfony\Component\HttpFoundation\BinaryFileResponse;
Chris@0 12 use Symfony\Component\HttpFoundation\Request;
Chris@0 13 use Symfony\Component\HttpFoundation\Response;
Chris@0 14 use Symfony\Component\HttpFoundation\StreamedResponse;
Chris@0 15 use Symfony\Component\HttpKernel\HttpKernelInterface;
Chris@0 16
Chris@0 17 /**
Chris@0 18 * Executes the page caching before the main kernel takes over the request.
Chris@0 19 */
Chris@0 20 class PageCache implements HttpKernelInterface {
Chris@0 21
Chris@0 22 /**
Chris@0 23 * The wrapped HTTP kernel.
Chris@0 24 *
Chris@0 25 * @var \Symfony\Component\HttpKernel\HttpKernelInterface
Chris@0 26 */
Chris@0 27 protected $httpKernel;
Chris@0 28
Chris@0 29 /**
Chris@0 30 * The cache bin.
Chris@0 31 *
Chris@0 32 * @var \Drupal\Core\Cache\CacheBackendInterface.
Chris@0 33 */
Chris@0 34 protected $cache;
Chris@0 35
Chris@0 36 /**
Chris@0 37 * A policy rule determining the cacheability of a request.
Chris@0 38 *
Chris@0 39 * @var \Drupal\Core\PageCache\RequestPolicyInterface
Chris@0 40 */
Chris@0 41 protected $requestPolicy;
Chris@0 42
Chris@0 43 /**
Chris@0 44 * A policy rule determining the cacheability of the response.
Chris@0 45 *
Chris@0 46 * @var \Drupal\Core\PageCache\ResponsePolicyInterface
Chris@0 47 */
Chris@0 48 protected $responsePolicy;
Chris@0 49
Chris@0 50 /**
Chris@0 51 * Constructs a PageCache object.
Chris@0 52 *
Chris@0 53 * @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
Chris@0 54 * The decorated kernel.
Chris@0 55 * @param \Drupal\Core\Cache\CacheBackendInterface $cache
Chris@0 56 * The cache bin.
Chris@0 57 * @param \Drupal\Core\PageCache\RequestPolicyInterface $request_policy
Chris@0 58 * A policy rule determining the cacheability of a request.
Chris@0 59 * @param \Drupal\Core\PageCache\ResponsePolicyInterface $response_policy
Chris@0 60 * A policy rule determining the cacheability of the response.
Chris@0 61 */
Chris@0 62 public function __construct(HttpKernelInterface $http_kernel, CacheBackendInterface $cache, RequestPolicyInterface $request_policy, ResponsePolicyInterface $response_policy) {
Chris@0 63 $this->httpKernel = $http_kernel;
Chris@0 64 $this->cache = $cache;
Chris@0 65 $this->requestPolicy = $request_policy;
Chris@0 66 $this->responsePolicy = $response_policy;
Chris@0 67 }
Chris@0 68
Chris@0 69 /**
Chris@0 70 * {@inheritdoc}
Chris@0 71 */
Chris@0 72 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
Chris@0 73 // Only allow page caching on master request.
Chris@0 74 if ($type === static::MASTER_REQUEST && $this->requestPolicy->check($request) === RequestPolicyInterface::ALLOW) {
Chris@0 75 $response = $this->lookup($request, $type, $catch);
Chris@0 76 }
Chris@0 77 else {
Chris@0 78 $response = $this->pass($request, $type, $catch);
Chris@0 79 }
Chris@0 80
Chris@0 81 return $response;
Chris@0 82 }
Chris@0 83
Chris@0 84 /**
Chris@0 85 * Sidesteps the page cache and directly forwards a request to the backend.
Chris@0 86 *
Chris@0 87 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 88 * A request object.
Chris@0 89 * @param int $type
Chris@0 90 * The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
Chris@0 91 * HttpKernelInterface::SUB_REQUEST)
Chris@0 92 * @param bool $catch
Chris@0 93 * Whether to catch exceptions or not
Chris@0 94 *
Chris@0 95 * @returns \Symfony\Component\HttpFoundation\Response $response
Chris@0 96 * A response object.
Chris@0 97 */
Chris@0 98 protected function pass(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
Chris@0 99 return $this->httpKernel->handle($request, $type, $catch);
Chris@0 100 }
Chris@0 101
Chris@0 102 /**
Chris@0 103 * Retrieves a response from the cache or fetches it from the backend.
Chris@0 104 *
Chris@0 105 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 106 * A request object.
Chris@0 107 * @param int $type
Chris@0 108 * The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
Chris@0 109 * HttpKernelInterface::SUB_REQUEST)
Chris@0 110 * @param bool $catch
Chris@0 111 * Whether to catch exceptions or not
Chris@0 112 *
Chris@0 113 * @returns \Symfony\Component\HttpFoundation\Response $response
Chris@0 114 * A response object.
Chris@0 115 */
Chris@0 116 protected function lookup(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
Chris@0 117 if ($response = $this->get($request)) {
Chris@0 118 $response->headers->set('X-Drupal-Cache', 'HIT');
Chris@0 119 }
Chris@0 120 else {
Chris@0 121 $response = $this->fetch($request, $type, $catch);
Chris@0 122 }
Chris@0 123
Chris@0 124 // Only allow caching in the browser and prevent that the response is stored
Chris@0 125 // by an external proxy server when the following conditions apply:
Chris@0 126 // 1. There is a session cookie on the request.
Chris@0 127 // 2. The Vary: Cookie header is on the response.
Chris@0 128 // 3. The Cache-Control header does not contain the no-cache directive.
Chris@0 129 if ($request->cookies->has(session_name()) &&
Chris@0 130 in_array('Cookie', $response->getVary()) &&
Chris@0 131 !$response->headers->hasCacheControlDirective('no-cache')) {
Chris@0 132
Chris@0 133 $response->setPrivate();
Chris@0 134 }
Chris@0 135
Chris@0 136 // Perform HTTP revalidation.
Chris@0 137 // @todo Use Response::isNotModified() as
Chris@0 138 // per https://www.drupal.org/node/2259489.
Chris@0 139 $last_modified = $response->getLastModified();
Chris@0 140 if ($last_modified) {
Chris@0 141 // See if the client has provided the required HTTP headers.
Chris@0 142 $if_modified_since = $request->server->has('HTTP_IF_MODIFIED_SINCE') ? strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE')) : FALSE;
Chris@0 143 $if_none_match = $request->server->has('HTTP_IF_NONE_MATCH') ? stripslashes($request->server->get('HTTP_IF_NONE_MATCH')) : FALSE;
Chris@0 144
Chris@0 145 if ($if_modified_since && $if_none_match
Chris@0 146 // etag must match.
Chris@0 147 && $if_none_match == $response->getEtag()
Chris@0 148 // if-modified-since must match.
Chris@0 149 && $if_modified_since == $last_modified->getTimestamp()) {
Chris@0 150 $response->setStatusCode(304);
Chris@0 151 $response->setContent(NULL);
Chris@0 152
Chris@0 153 // In the case of a 304 response, certain headers must be sent, and the
Chris@0 154 // remaining may not (see RFC 2616, section 10.3.5).
Chris@0 155 foreach (array_keys($response->headers->all()) as $name) {
Chris@0 156 if (!in_array($name, ['content-location', 'expires', 'cache-control', 'vary'])) {
Chris@0 157 $response->headers->remove($name);
Chris@0 158 }
Chris@0 159 }
Chris@0 160 }
Chris@0 161 }
Chris@0 162
Chris@0 163 return $response;
Chris@0 164 }
Chris@0 165
Chris@0 166 /**
Chris@0 167 * Fetches a response from the backend and stores it in the cache.
Chris@0 168 *
Chris@0 169 * @see drupal_page_header()
Chris@0 170 *
Chris@0 171 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 172 * A request object.
Chris@0 173 * @param int $type
Chris@0 174 * The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
Chris@0 175 * HttpKernelInterface::SUB_REQUEST)
Chris@0 176 * @param bool $catch
Chris@0 177 * Whether to catch exceptions or not
Chris@0 178 *
Chris@0 179 * @returns \Symfony\Component\HttpFoundation\Response $response
Chris@0 180 * A response object.
Chris@0 181 */
Chris@0 182 protected function fetch(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
Chris@0 183 /** @var \Symfony\Component\HttpFoundation\Response $response */
Chris@0 184 $response = $this->httpKernel->handle($request, $type, $catch);
Chris@0 185
Chris@0 186 // Only set the 'X-Drupal-Cache' header if caching is allowed for this
Chris@0 187 // response.
Chris@0 188 if ($this->storeResponse($request, $response)) {
Chris@0 189 $response->headers->set('X-Drupal-Cache', 'MISS');
Chris@0 190 }
Chris@0 191
Chris@0 192 return $response;
Chris@0 193 }
Chris@0 194
Chris@0 195 /**
Chris@0 196 * Stores a response in the page cache.
Chris@0 197 *
Chris@0 198 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 199 * A request object.
Chris@0 200 * @param \Symfony\Component\HttpFoundation\Response $response
Chris@0 201 * A response object that should be stored in the page cache.
Chris@0 202 *
Chris@0 203 * @returns bool
Chris@0 204 */
Chris@0 205 protected function storeResponse(Request $request, Response $response) {
Chris@0 206 // Drupal's primary cache invalidation architecture is cache tags: any
Chris@0 207 // response that varies by a configuration value or data in a content
Chris@0 208 // entity should have cache tags, to allow for instant cache invalidation
Chris@0 209 // when that data is updated. However, HTTP does not standardize how to
Chris@0 210 // encode cache tags in a response. Different CDNs implement their own
Chris@0 211 // approaches, and configurable reverse proxies (e.g., Varnish) allow for
Chris@0 212 // custom implementations. To keep Drupal's internal page cache simple, we
Chris@0 213 // only cache CacheableResponseInterface responses, since those provide a
Chris@0 214 // defined API for retrieving cache tags. For responses that do not
Chris@0 215 // implement CacheableResponseInterface, there's no easy way to distinguish
Chris@0 216 // responses that truly don't depend on any site data from responses that
Chris@0 217 // contain invalidation information customized to a particular proxy or
Chris@0 218 // CDN.
Chris@0 219 // - Drupal modules are encouraged to use CacheableResponseInterface
Chris@0 220 // responses where possible and to leave the encoding of that information
Chris@0 221 // into response headers to the corresponding proxy/CDN integration
Chris@0 222 // modules.
Chris@0 223 // - Custom applications that wish to provide internal page cache support
Chris@0 224 // for responses that do not implement CacheableResponseInterface may do
Chris@0 225 // so by replacing/extending this middleware service or adding another
Chris@0 226 // one.
Chris@0 227 if (!$response instanceof CacheableResponseInterface) {
Chris@0 228 return FALSE;
Chris@0 229 }
Chris@0 230
Chris@0 231 // Currently it is not possible to cache binary file or streamed responses:
Chris@0 232 // https://github.com/symfony/symfony/issues/9128#issuecomment-25088678.
Chris@0 233 // Therefore exclude them, even for subclasses that implement
Chris@0 234 // CacheableResponseInterface.
Chris@0 235 if ($response instanceof BinaryFileResponse || $response instanceof StreamedResponse) {
Chris@0 236 return FALSE;
Chris@0 237 }
Chris@0 238
Chris@0 239 // Allow policy rules to further restrict which responses to cache.
Chris@0 240 if ($this->responsePolicy->check($response, $request) === ResponsePolicyInterface::DENY) {
Chris@0 241 return FALSE;
Chris@0 242 }
Chris@0 243
Chris@0 244 $request_time = $request->server->get('REQUEST_TIME');
Chris@0 245 // The response passes all of the above checks, so cache it. Page cache
Chris@0 246 // entries default to Cache::PERMANENT since they will be expired via cache
Chris@0 247 // tags locally. Because of this, page cache ignores max age.
Chris@0 248 // - Get the tags from CacheableResponseInterface per the earlier comments.
Chris@0 249 // - Get the time expiration from the Expires header, rather than the
Chris@0 250 // interface, but see https://www.drupal.org/node/2352009 about possibly
Chris@0 251 // changing that.
Chris@0 252 $expire = 0;
Chris@0 253 // 403 and 404 responses can fill non-LRU cache backends and generally are
Chris@0 254 // likely to have a low cache hit rate. So do not cache them permanently.
Chris@0 255 if ($response->isClientError()) {
Chris@0 256 // Cache for an hour by default. If the 'cache_ttl_4xx' setting is
Chris@0 257 // set to 0 then do not cache the response.
Chris@0 258 $cache_ttl_4xx = Settings::get('cache_ttl_4xx', 3600);
Chris@0 259 if ($cache_ttl_4xx > 0) {
Chris@0 260 $expire = $request_time + $cache_ttl_4xx;
Chris@0 261 }
Chris@0 262 }
Chris@0 263 // The getExpires method could return NULL if Expires header is not set, so
Chris@0 264 // the returned value needs to be checked before calling getTimestamp.
Chris@0 265 elseif ($expires = $response->getExpires()) {
Chris@0 266 $date = $expires->getTimestamp();
Chris@0 267 $expire = ($date > $request_time) ? $date : Cache::PERMANENT;
Chris@0 268 }
Chris@0 269 else {
Chris@0 270 $expire = Cache::PERMANENT;
Chris@0 271 }
Chris@0 272
Chris@0 273 if ($expire === Cache::PERMANENT || $expire > $request_time) {
Chris@0 274 $tags = $response->getCacheableMetadata()->getCacheTags();
Chris@0 275 $this->set($request, $response, $expire, $tags);
Chris@0 276 }
Chris@0 277
Chris@0 278 return TRUE;
Chris@0 279 }
Chris@0 280
Chris@0 281 /**
Chris@0 282 * Returns a response object from the page cache.
Chris@0 283 *
Chris@0 284 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 285 * A request object.
Chris@0 286 * @param bool $allow_invalid
Chris@0 287 * (optional) If TRUE, a cache item may be returned even if it is expired or
Chris@0 288 * has been invalidated. Such items may sometimes be preferred, if the
Chris@0 289 * alternative is recalculating the value stored in the cache, especially
Chris@0 290 * if another concurrent request is already recalculating the same value.
Chris@0 291 * The "valid" property of the returned object indicates whether the item is
Chris@0 292 * valid or not. Defaults to FALSE.
Chris@0 293 *
Chris@0 294 * @return \Symfony\Component\HttpFoundation\Response|false
Chris@0 295 * The cached response or FALSE on failure.
Chris@0 296 */
Chris@0 297 protected function get(Request $request, $allow_invalid = FALSE) {
Chris@0 298 $cid = $this->getCacheId($request);
Chris@0 299 if ($cache = $this->cache->get($cid, $allow_invalid)) {
Chris@0 300 return $cache->data;
Chris@0 301 }
Chris@0 302 return FALSE;
Chris@0 303 }
Chris@0 304
Chris@0 305 /**
Chris@0 306 * Stores a response object in the page cache.
Chris@0 307 *
Chris@0 308 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 309 * A request object.
Chris@0 310 * @param \Symfony\Component\HttpFoundation\Response $response
Chris@0 311 * The response to store in the cache.
Chris@0 312 * @param int $expire
Chris@0 313 * One of the following values:
Chris@0 314 * - CacheBackendInterface::CACHE_PERMANENT: Indicates that the item should
Chris@0 315 * not be removed unless it is deleted explicitly.
Chris@0 316 * - A Unix timestamp: Indicates that the item will be considered invalid
Chris@0 317 * after this time, i.e. it will not be returned by get() unless
Chris@0 318 * $allow_invalid has been set to TRUE. When the item has expired, it may
Chris@0 319 * be permanently deleted by the garbage collector at any time.
Chris@0 320 * @param array $tags
Chris@0 321 * An array of tags to be stored with the cache item. These should normally
Chris@0 322 * identify objects used to build the cache item, which should trigger
Chris@0 323 * cache invalidation when updated. For example if a cached item represents
Chris@0 324 * a node, both the node ID and the author's user ID might be passed in as
Chris@0 325 * tags. For example array('node' => array(123), 'user' => array(92)).
Chris@0 326 */
Chris@0 327 protected function set(Request $request, Response $response, $expire, array $tags) {
Chris@0 328 $cid = $this->getCacheId($request);
Chris@0 329 $this->cache->set($cid, $response, $expire, $tags);
Chris@0 330 }
Chris@0 331
Chris@0 332 /**
Chris@0 333 * Gets the page cache ID for this request.
Chris@0 334 *
Chris@0 335 * @param \Symfony\Component\HttpFoundation\Request $request
Chris@0 336 * A request object.
Chris@0 337 *
Chris@0 338 * @return string
Chris@0 339 * The cache ID for this request.
Chris@0 340 */
Chris@0 341 protected function getCacheId(Request $request) {
Chris@0 342 $cid_parts = [
Chris@0 343 $request->getSchemeAndHttpHost() . $request->getRequestUri(),
Chris@0 344 $request->getRequestFormat(),
Chris@0 345 ];
Chris@0 346 return implode(':', $cid_parts);
Chris@0 347 }
Chris@0 348
Chris@0 349 }