Move into nested docroot

This commit is contained in:
Rob Davies 2017-02-13 15:31:17 +00:00
parent 83a0d3a149
commit c8b70abde9
13405 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,6 @@
name: Internal Page Cache
type: module
description: 'Caches pages for anonymous users. Use when an external page cache is not available.'
package: Core
version: VERSION
core: 8.x

View file

@ -0,0 +1,31 @@
<?php
/**
* @file
* Caches responses for anonymous users, request and response policies allowing.
*/
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
/**
* Implements hook_help().
*/
function page_cache_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.page_cache':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Internal Page Cache module caches pages for anonymous users in the database. For more information, see the <a href=":pagecache-documentation">online documentation for the Internal Page Cache module</a>.', array(':pagecache-documentation' => 'https://www.drupal.org/documentation/modules/internal_page_cache')) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Speeding up your site') . '</dt>';
$output .= '<dd>' . t('Pages requested by anonymous users are stored the first time they are requested and then are reused. Depending on your site configuration and the amount of your web traffic tied to anonymous visitors, the caching system may significantly increase the speed of your site.') . '</dd>';
$output .= '<dd>' . t('Pages are usually identical for all anonymous users, while they can be personalized for each authenticated user. This is why entire pages can be cached for anonymous users, whereas they will have to be rebuilt for every authenticated user.') . '</dd>';
$output .= '<dd>' . t('To speed up your site for authenticated users, see the <a href=":dynamic_page_cache-help">Dynamic Page Cache module</a>.', [':dynamic_page_cache-help' => (\Drupal::moduleHandler()->moduleExists('dynamic_page_cache')) ? Url::fromRoute('help.page', ['name' => 'dynamic_page_cache'])->toString() : '#']) . '</p>';
$output .= '<dt>' . t('Configuring the internal page cache') . '</dt>';
$output .= '<dd>' . t('On the <a href=":cache-settings">Performance page</a>, you can configure how long browsers and proxies may cache pages; that setting is also respected by the Internal Page Cache module. There is no other configuration.', array(':cache-settings' => \Drupal::url('system.performance_settings'))) . '</dd>';
$output .= '</dl>';
return $output;
}
}

View file

@ -0,0 +1,6 @@
services:
http_middleware.page_cache:
class: Drupal\page_cache\StackMiddleware\PageCache
arguments: ['@cache.render', '@page_cache_request_policy', '@page_cache_response_policy']
tags:
- { name: http_middleware, priority: 200, responder: true }

View file

@ -0,0 +1,350 @@
<?php
namespace Drupal\page_cache\StackMiddleware;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\PageCache\RequestPolicyInterface;
use Drupal\Core\PageCache\ResponsePolicyInterface;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* Executes the page caching before the main kernel takes over the request.
*/
class PageCache implements HttpKernelInterface {
/**
* The wrapped HTTP kernel.
*
* @var \Symfony\Component\HttpKernel\HttpKernelInterface
*/
protected $httpKernel;
/**
* The cache bin.
*
* @var \Drupal\Core\Cache\CacheBackendInterface.
*/
protected $cache;
/**
* A policy rule determining the cacheability of a request.
*
* @var \Drupal\Core\PageCache\RequestPolicyInterface
*/
protected $requestPolicy;
/**
* A policy rule determining the cacheability of the response.
*
* @var \Drupal\Core\PageCache\ResponsePolicyInterface
*/
protected $responsePolicy;
/**
* Constructs a PageCache object.
*
* @param \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel
* The decorated kernel.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
* The cache bin.
* @param \Drupal\Core\PageCache\RequestPolicyInterface $request_policy
* A policy rule determining the cacheability of a request.
* @param \Drupal\Core\PageCache\ResponsePolicyInterface $response_policy
* A policy rule determining the cacheability of the response.
*/
public function __construct(HttpKernelInterface $http_kernel, CacheBackendInterface $cache, RequestPolicyInterface $request_policy, ResponsePolicyInterface $response_policy) {
$this->httpKernel = $http_kernel;
$this->cache = $cache;
$this->requestPolicy = $request_policy;
$this->responsePolicy = $response_policy;
}
/**
* {@inheritdoc}
*/
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
// Only allow page caching on master request.
if ($type === static::MASTER_REQUEST && $this->requestPolicy->check($request) === RequestPolicyInterface::ALLOW) {
$response = $this->lookup($request, $type, $catch);
}
else {
$response = $this->pass($request, $type, $catch);
}
return $response;
}
/**
* Sidesteps the page cache and directly forwards a request to the backend.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
* @param int $type
* The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
* HttpKernelInterface::SUB_REQUEST)
* @param bool $catch
* Whether to catch exceptions or not
*
* @returns \Symfony\Component\HttpFoundation\Response $response
* A response object.
*/
protected function pass(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
return $this->httpKernel->handle($request, $type, $catch);
}
/**
* Retrieves a response from the cache or fetches it from the backend.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
* @param int $type
* The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
* HttpKernelInterface::SUB_REQUEST)
* @param bool $catch
* Whether to catch exceptions or not
*
* @returns \Symfony\Component\HttpFoundation\Response $response
* A response object.
*/
protected function lookup(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
if ($response = $this->get($request)) {
$response->headers->set('X-Drupal-Cache', 'HIT');
}
else {
$response = $this->fetch($request, $type, $catch);
}
// Only allow caching in the browser and prevent that the response is stored
// by an external proxy server when the following conditions apply:
// 1. There is a session cookie on the request.
// 2. The Vary: Cookie header is on the response.
// 3. The Cache-Control header does not contain the no-cache directive.
if ($request->cookies->has(session_name()) &&
in_array('Cookie', $response->getVary()) &&
!$response->headers->hasCacheControlDirective('no-cache')) {
$response->setPrivate();
}
// Negotiate whether to use compression.
if (extension_loaded('zlib') && $response->headers->get('Content-Encoding') === 'gzip') {
if (strpos($request->headers->get('Accept-Encoding'), 'gzip') !== FALSE) {
// The response content is already gzip'ed, so make sure
// zlib.output_compression does not compress it once more.
ini_set('zlib.output_compression', '0');
}
else {
// The client does not support compression. Decompress the content and
// remove the Content-Encoding header.
$content = $response->getContent();
$content = gzinflate(substr(substr($content, 10), 0, -8));
$response->setContent($content);
$response->headers->remove('Content-Encoding');
}
}
// Perform HTTP revalidation.
// @todo Use Response::isNotModified() as
// per https://www.drupal.org/node/2259489.
$last_modified = $response->getLastModified();
if ($last_modified) {
// See if the client has provided the required HTTP headers.
$if_modified_since = $request->server->has('HTTP_IF_MODIFIED_SINCE') ? strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE')) : FALSE;
$if_none_match = $request->server->has('HTTP_IF_NONE_MATCH') ? stripslashes($request->server->get('HTTP_IF_NONE_MATCH')) : FALSE;
if ($if_modified_since && $if_none_match
&& $if_none_match == $response->getEtag() // etag must match
&& $if_modified_since == $last_modified->getTimestamp()) { // if-modified-since must match
$response->setStatusCode(304);
$response->setContent(NULL);
// In the case of a 304 response, certain headers must be sent, and the
// remaining may not (see RFC 2616, section 10.3.5).
foreach (array_keys($response->headers->all()) as $name) {
if (!in_array($name, array('content-location', 'expires', 'cache-control', 'vary'))) {
$response->headers->remove($name);
}
}
}
}
return $response;
}
/**
* Fetches a response from the backend and stores it in the cache.
*
* If page_compression is enabled, a gzipped version of the page is stored in
* the cache to avoid compressing the output on each request. The cache entry
* is unzipped in the relatively rare event that the page is requested by a
* client without gzip support.
*
* Page compression requires the PHP zlib extension
* (http://php.net/manual/ref.zlib.php).
*
* @see drupal_page_header()
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
* @param int $type
* The type of the request (one of HttpKernelInterface::MASTER_REQUEST or
* HttpKernelInterface::SUB_REQUEST)
* @param bool $catch
* Whether to catch exceptions or not
*
* @returns \Symfony\Component\HttpFoundation\Response $response
* A response object.
*/
protected function fetch(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
/** @var \Symfony\Component\HttpFoundation\Response $response */
$response = $this->httpKernel->handle($request, $type, $catch);
// Drupal's primary cache invalidation architecture is cache tags: any
// response that varies by a configuration value or data in a content
// entity should have cache tags, to allow for instant cache invalidation
// when that data is updated. However, HTTP does not standardize how to
// encode cache tags in a response. Different CDNs implement their own
// approaches, and configurable reverse proxies (e.g., Varnish) allow for
// custom implementations. To keep Drupal's internal page cache simple, we
// only cache CacheableResponseInterface responses, since those provide a
// defined API for retrieving cache tags. For responses that do not
// implement CacheableResponseInterface, there's no easy way to distinguish
// responses that truly don't depend on any site data from responses that
// contain invalidation information customized to a particular proxy or
// CDN.
// - Drupal modules are encouraged to use CacheableResponseInterface
// responses where possible and to leave the encoding of that information
// into response headers to the corresponding proxy/CDN integration
// modules.
// - Custom applications that wish to provide internal page cache support
// for responses that do not implement CacheableResponseInterface may do
// so by replacing/extending this middleware service or adding another
// one.
if (!$response instanceof CacheableResponseInterface) {
return $response;
}
// Currently it is not possible to cache binary file or streamed responses:
// https://github.com/symfony/symfony/issues/9128#issuecomment-25088678.
// Therefore exclude them, even for subclasses that implement
// CacheableResponseInterface.
if ($response instanceof BinaryFileResponse || $response instanceof StreamedResponse) {
return $response;
}
// Allow policy rules to further restrict which responses to cache.
if ($this->responsePolicy->check($response, $request) === ResponsePolicyInterface::DENY) {
return $response;
}
$request_time = $request->server->get('REQUEST_TIME');
// The response passes all of the above checks, so cache it. Page cache
// entries default to Cache::PERMANENT since they will be expired via cache
// tags locally. Because of this, page cache ignores max age.
// - Get the tags from CacheableResponseInterface per the earlier comments.
// - Get the time expiration from the Expires header, rather than the
// interface, but see https://www.drupal.org/node/2352009 about possibly
// changing that.
$expire = 0;
// 403 and 404 responses can fill non-LRU cache backends and generally are
// likely to have a low cache hit rate. So do not cache them permanently.
if ($response->isClientError()) {
// Cache for an hour by default. If the 'cache_ttl_4xx' setting is
// set to 0 then do not cache the response.
$cache_ttl_4xx = Settings::get('cache_ttl_4xx', 3600);
if ($cache_ttl_4xx > 0) {
$expire = $request_time + $cache_ttl_4xx;
}
}
else {
$date = $response->getExpires()->getTimestamp();
$expire = ($date > $request_time) ? $date : Cache::PERMANENT;
}
if ($expire === Cache::PERMANENT || $expire > $request_time) {
$tags = $response->getCacheableMetadata()->getCacheTags();
$this->set($request, $response, $expire, $tags);
}
// Mark response as a cache miss.
$response->headers->set('X-Drupal-Cache', 'MISS');
return $response;
}
/**
* Returns a response object from the page cache.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
* @param bool $allow_invalid
* (optional) If TRUE, a cache item may be returned even if it is expired or
* has been invalidated. Such items may sometimes be preferred, if the
* alternative is recalculating the value stored in the cache, especially
* if another concurrent request is already recalculating the same value.
* The "valid" property of the returned object indicates whether the item is
* valid or not. Defaults to FALSE.
*
* @return \Symfony\Component\HttpFoundation\Response|false
* The cached response or FALSE on failure.
*/
protected function get(Request $request, $allow_invalid = FALSE) {
$cid = $this->getCacheId($request);
if ($cache = $this->cache->get($cid, $allow_invalid)) {
return $cache->data;
}
return FALSE;
}
/**
* Stores a response object in the page cache.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
* @param \Symfony\Component\HttpFoundation\Response $response
* The response to store in the cache.
* @param int $expire
* One of the following values:
* - CacheBackendInterface::CACHE_PERMANENT: Indicates that the item should
* not be removed unless it is deleted explicitly.
* - A Unix timestamp: Indicates that the item will be considered invalid
* after this time, i.e. it will not be returned by get() unless
* $allow_invalid has been set to TRUE. When the item has expired, it may
* be permanently deleted by the garbage collector at any time.
* @param array $tags
* An array of tags to be stored with the cache item. These should normally
* identify objects used to build the cache item, which should trigger
* cache invalidation when updated. For example if a cached item represents
* a node, both the node ID and the author's user ID might be passed in as
* tags. For example array('node' => array(123), 'user' => array(92)).
*/
protected function set(Request $request, Response $response, $expire, array $tags) {
$cid = $this->getCacheId($request);
$this->cache->set($cid, $response, $expire, $tags);
}
/**
* Gets the page cache ID for this request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
*
* @return string
* The cache ID for this request.
*/
protected function getCacheId(Request $request) {
$cid_parts = array(
$request->getUri(),
$request->getRequestFormat(),
);
return implode(':', $cid_parts);
}
}

View file

@ -0,0 +1,161 @@
<?php
namespace Drupal\page_cache\Tests;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Core\Language\LanguageInterface;
use Drupal\simpletest\WebTestBase;
use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
/**
* Enables the page cache and tests its cache tags in various scenarios.
*
* @group Cache
* @see \Drupal\page_cache\Tests\PageCacheTest
* @see \Drupal\node\Tests\NodePageCacheTest
* @see \Drupal\menu_ui\Tests\MenuTest::testMenuBlockPageCacheTags()
*/
class PageCacheTagsIntegrationTest extends WebTestBase {
use AssertPageCacheContextsAndTagsTrait;
protected $profile = 'standard';
protected $dumpHeaders = TRUE;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->enablePageCaching();
}
/**
* Test that cache tags are properly bubbled up to the page level.
*/
function testPageCacheTags() {
// Create two nodes.
$author_1 = $this->drupalCreateUser();
$node_1 = $this->drupalCreateNode(array(
'uid' => $author_1->id(),
'title' => 'Node 1',
'body' => array(
0 => array('value' => 'Body 1', 'format' => 'basic_html'),
),
'promote' => NODE_PROMOTED,
));
$author_2 = $this->drupalCreateUser();
$node_2 = $this->drupalCreateNode(array(
'uid' => $author_2->id(),
'title' => 'Node 2',
'body' => array(
0 => array('value' => 'Body 2', 'format' => 'full_html'),
),
'promote' => NODE_PROMOTED,
));
// Place a block, but only make it visible on full node page 2.
$block = $this->drupalPlaceBlock('views_block:comments_recent-block_1', array(
'visibility' => array(
'request_path' => array(
'pages' => '/node/' . $node_2->id(),
),
),
));
$cache_contexts = [
'languages:' . LanguageInterface::TYPE_INTERFACE,
'route',
'theme',
'timezone',
'user',
// The placed block is only visible on certain URLs through a visibility
// condition.
'url.path',
'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT,
];
// Full node page 1.
$this->assertPageCacheContextsAndTags($node_1->urlInfo(), $cache_contexts, array(
'rendered',
'block_view',
'config:block_list',
'config:block.block.bartik_branding',
'config:block.block.bartik_breadcrumbs',
'config:block.block.bartik_content',
'config:block.block.bartik_tools',
'config:block.block.bartik_footer',
'config:block.block.bartik_help',
'config:block.block.bartik_search',
'config:block.block.' . $block->id(),
'config:block.block.bartik_powered',
'config:block.block.bartik_main_menu',
'config:block.block.bartik_account_menu',
'config:block.block.bartik_messages',
'config:block.block.bartik_local_actions',
'config:block.block.bartik_local_tasks',
'config:block.block.bartik_page_title',
'node_view',
'node:' . $node_1->id(),
'user:0',
'user:' . $author_1->id(),
'config:filter.format.basic_html',
'config:color.theme.bartik',
'config:search.settings',
'config:system.menu.account',
'config:system.menu.tools',
'config:system.menu.footer',
'config:system.menu.main',
'config:system.site',
// FinishResponseSubscriber adds this cache tag to responses that have the
// 'user.permissions' cache context for anonymous users.
'config:user.role.anonymous',
));
// Render the view block adds the languages cache context.
$cache_contexts[] = 'languages:' . LanguageInterface::TYPE_CONTENT;
// Full node page 2.
$this->assertPageCacheContextsAndTags($node_2->urlInfo(), $cache_contexts, array(
'rendered',
'block_view',
'config:block_list',
'config:block.block.bartik_branding',
'config:block.block.bartik_breadcrumbs',
'config:block.block.bartik_content',
'config:block.block.bartik_tools',
'config:block.block.bartik_help',
'config:block.block.bartik_search',
'config:block.block.' . $block->id(),
'config:block.block.bartik_footer',
'config:block.block.bartik_powered',
'config:block.block.bartik_main_menu',
'config:block.block.bartik_account_menu',
'config:block.block.bartik_messages',
'config:block.block.bartik_local_actions',
'config:block.block.bartik_local_tasks',
'config:block.block.bartik_page_title',
'node_view',
'node:' . $node_2->id(),
'user:' . $author_2->id(),
'config:color.theme.bartik',
'config:filter.format.full_html',
'config:search.settings',
'config:system.menu.account',
'config:system.menu.tools',
'config:system.menu.footer',
'config:system.menu.main',
'config:system.site',
'comment_list',
'node_list',
'config:views.view.comments_recent',
// FinishResponseSubscriber adds this cache tag to responses that have the
// 'user.permissions' cache context for anonymous users.
'config:user.role.anonymous',
'user:0',
));
}
}

View file

@ -0,0 +1,540 @@
<?php
namespace Drupal\page_cache\Tests;
use Drupal\Component\Datetime\DateTimePlus;
use Drupal\Core\Site\Settings;
use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\simpletest\WebTestBase;
use Drupal\Core\Cache\Cache;
use Drupal\user\RoleInterface;
/**
* Enables the page cache and tests it with various HTTP requests.
*
* @group page_cache
*/
class PageCacheTest extends WebTestBase {
protected $dumpHeaders = TRUE;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('test_page_test', 'system_test', 'entity_test');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->config('system.site')
->set('name', 'Drupal')
->set('page.front', '/test-page')
->save();
}
/**
* Test that cache tags are properly persisted.
*
* Since tag based invalidation works, we know that our tag properly
* persisted.
*/
function testPageCacheTags() {
$config = $this->config('system.performance');
$config->set('cache.page.max_age', 300);
$config->save();
$path = 'system-test/cache_tags_page';
$tags = array('system_test_cache_tags_page');
$this->drupalGet($path);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
// Verify a cache hit, but also the presence of the correct cache tags.
$this->drupalGet($path);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$cid_parts = array(\Drupal::url('system_test.cache_tags_page', array(), array('absolute' => TRUE)), 'html');
$cid = implode(':', $cid_parts);
$cache_entry = \Drupal::cache('render')->get($cid);
sort($cache_entry->tags);
$expected_tags = array(
'config:user.role.anonymous',
'pre_render',
'rendered',
'system_test_cache_tags_page',
);
$this->assertIdentical($cache_entry->tags, $expected_tags);
Cache::invalidateTags($tags);
$this->drupalGet($path);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
}
/**
* Test that the page cache doesn't depend on cacheability headers.
*/
function testPageCacheTagsIndependentFromCacheabilityHeaders() {
$this->setHttpResponseDebugCacheabilityHeaders(FALSE);
$path = 'system-test/cache_tags_page';
$tags = array('system_test_cache_tags_page');
$this->drupalGet($path);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
// Verify a cache hit, but also the presence of the correct cache tags.
$this->drupalGet($path);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$cid_parts = array(\Drupal::url('system_test.cache_tags_page', array(), array('absolute' => TRUE)), 'html');
$cid = implode(':', $cid_parts);
$cache_entry = \Drupal::cache('render')->get($cid);
sort($cache_entry->tags);
$expected_tags = array(
'config:user.role.anonymous',
'pre_render',
'rendered',
'system_test_cache_tags_page',
);
$this->assertIdentical($cache_entry->tags, $expected_tags);
Cache::invalidateTags($tags);
$this->drupalGet($path);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
}
/**
* Tests support for different cache items with different request formats
* specified via a query parameter.
*/
function testQueryParameterFormatRequests() {
$config = $this->config('system.performance');
$config->set('cache.page.max_age', 300);
$config->save();
$accept_header_cache_url = Url::fromRoute('system_test.page_cache_accept_header');
$accept_header_cache_url_with_json = Url::fromRoute('system_test.page_cache_accept_header', ['_format' => 'json']);
$this->drupalGet($accept_header_cache_url);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'HTML page was not yet cached.');
$this->drupalGet($accept_header_cache_url);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'HTML page was cached.');
$this->assertRaw('<p>oh hai this is html.</p>', 'The correct HTML response was returned.');
$this->drupalGet($accept_header_cache_url_with_json);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Json response was not yet cached.');
$this->drupalGet($accept_header_cache_url_with_json);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Json response was cached.');
$this->assertRaw('{"content":"oh hai this is json"}', 'The correct Json response was returned.');
// Enable REST support for nodes and hal+json.
\Drupal::service('module_installer')->install(['node', 'rest', 'hal', 'basic_auth']);
$this->drupalCreateContentType(['type' => 'article']);
$node = $this->drupalCreateNode(['type' => 'article']);
$node_uri = $node->urlInfo();
$node_url_with_hal_json_format = $node->urlInfo('canonical')->setRouteParameter('_format', 'hal_json');
$this->drupalGet($node_uri);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
$this->drupalGet($node_uri);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
// Now request a HAL page, we expect that the first request is a cache miss
// and it serves HTML.
$this->drupalGet($node_url_with_hal_json_format);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
$this->drupalGet($node_url_with_hal_json_format);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
// Clear the page cache. After that request a HAL request, followed by an
// ordinary HTML one.
\Drupal::cache('render')->deleteAll();
$this->drupalGet($node_url_with_hal_json_format);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
$this->drupalGet($node_url_with_hal_json_format);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
$this->drupalGet($node_uri);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
$this->drupalGet($node_uri);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
}
/**
* Tests support of requests with If-Modified-Since and If-None-Match headers.
*/
function testConditionalRequests() {
$config = $this->config('system.performance');
$config->set('cache.page.max_age', 300);
$config->save();
// Fill the cache.
$this->drupalGet('');
// Verify the page is not printed twice when the cache is cold.
$this->assertNoPattern('#<html.*<html#');
$this->drupalHead('');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
$etag = $this->drupalGetHeader('ETag');
$last_modified = $this->drupalGetHeader('Last-Modified');
$this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified, 'If-None-Match: ' . $etag));
$this->assertResponse(304, 'Conditional request returned 304 Not Modified.');
$this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DATE_RFC822, strtotime($last_modified)), 'If-None-Match: ' . $etag));
$this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
$this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DATE_RFC850, strtotime($last_modified)), 'If-None-Match: ' . $etag));
$this->assertResponse(304, 'Conditional request with obsolete If-Modified-Since date returned 304 Not Modified.');
$this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified));
// Verify the page is not printed twice when the cache is warm.
$this->assertNoPattern('#<html.*<html#');
$this->assertResponse(200, 'Conditional request without If-None-Match returned 200 OK.');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
$this->drupalGet('', array(), array('If-Modified-Since: ' . gmdate(DateTimePlus::RFC7231, strtotime($last_modified) + 1), 'If-None-Match: ' . $etag));
$this->assertResponse(200, 'Conditional request with new a If-Modified-Since date newer than Last-Modified returned 200 OK.');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
$user = $this->drupalCreateUser();
$this->drupalLogin($user);
$this->drupalGet('', array(), array('If-Modified-Since: ' . $last_modified, 'If-None-Match: ' . $etag));
$this->assertResponse(200, 'Conditional request returned 200 OK for authenticated user.');
$this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Absence of Page was not cached.');
}
/**
* Tests cache headers.
*/
function testPageCache() {
$config = $this->config('system.performance');
$config->set('cache.page.max_age', 300);
$config->set('response.gzip', 1);
$config->save();
// Fill the cache.
$this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
$this->assertEqual(strtolower($this->drupalGetHeader('Vary')), 'cookie,accept-encoding', 'Vary header was sent.');
// Symfony's Response logic determines a specific order for the subvalues
// of the Cache-Control header, even if they are explicitly passed in to
// the response header bag in a different order.
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
$this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
$this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
// Check cache.
$this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
$this->assertEqual(strtolower($this->drupalGetHeader('Vary')), 'cookie,accept-encoding', 'Vary: Cookie header was sent.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
$this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
$this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
// Check replacing default headers.
$this->drupalGet('system-test/set-header', array('query' => array('name' => 'Expires', 'value' => 'Fri, 19 Nov 2008 05:00:00 GMT')));
$this->assertEqual($this->drupalGetHeader('Expires'), 'Fri, 19 Nov 2008 05:00:00 GMT', 'Default header was replaced.');
$this->drupalGet('system-test/set-header', array('query' => array('name' => 'Vary', 'value' => 'User-Agent')));
$this->assertEqual(strtolower($this->drupalGetHeader('Vary')), 'user-agent,accept-encoding', 'Default header was replaced.');
// Check that authenticated users bypass the cache.
$user = $this->drupalCreateUser();
$this->drupalLogin($user);
$this->drupalGet('system-test/set-header', array('query' => array('name' => 'Foo', 'value' => 'bar')));
$this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Caching was bypassed.');
$this->assertTrue(strpos(strtolower($this->drupalGetHeader('Vary')), 'cookie') === FALSE, 'Vary: Cookie header was not sent.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'must-revalidate, no-cache, private', 'Cache-Control header was sent.');
$this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
$this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
// Until bubbling of max-age up to the response is supported, verify that
// a custom #cache max-age set on an element does not affect page max-age.
$this->drupalLogout();
$this->drupalGet('system-test/cache_maxage_page');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public');
}
/**
* Tests the automatic presence of the anonymous role's cache tag.
*
* The 'user.permissions' cache context ensures that if the permissions for a
* role are modified, users are not served stale render cache content. But,
* when entire responses are cached in reverse proxies, the value for the
* cache context is never calculated, causing the stale response to not be
* invalidated. Therefore, when varying by permissions and the current user is
* the anonymous user, the cache tag for the 'anonymous' role must be added.
*
* This test verifies that, and it verifies that it does not happen for other
* roles.
*/
public function testPageCacheAnonymousRolePermissions() {
$config = $this->config('system.performance');
$config->set('cache.page.max_age', 300);
$config->save();
$content_url = Url::fromRoute('system_test.permission_dependent_content');
$route_access_url = Url::fromRoute('system_test.permission_dependent_route_access');
// 1. anonymous user, without permission.
$this->drupalGet($content_url);
$this->assertText('Permission to pet llamas: no!');
$this->assertCacheContext('user.permissions');
$this->assertCacheTag('config:user.role.anonymous');
$this->drupalGet($route_access_url);
$this->assertCacheContext('user.permissions');
$this->assertCacheTag('config:user.role.anonymous');
// 2. anonymous user, with permission.
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['pet llamas']);
$this->drupalGet($content_url);
$this->assertText('Permission to pet llamas: yes!');
$this->assertCacheContext('user.permissions');
$this->assertCacheTag('config:user.role.anonymous');
$this->drupalGet($route_access_url);
$this->assertCacheContext('user.permissions');
$this->assertCacheTag('config:user.role.anonymous');
// 3. authenticated user, without permission.
$auth_user = $this->drupalCreateUser();
$this->drupalLogin($auth_user);
$this->drupalGet($content_url);
$this->assertText('Permission to pet llamas: no!');
$this->assertCacheContext('user.permissions');
$this->assertNoCacheTag('config:user.role.authenticated');
$this->drupalGet($route_access_url);
$this->assertCacheContext('user.permissions');
$this->assertNoCacheTag('config:user.role.authenticated');
// 4. authenticated user, with permission.
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['pet llamas']);
$this->drupalGet($content_url);
$this->assertText('Permission to pet llamas: yes!');
$this->assertCacheContext('user.permissions');
$this->assertNoCacheTag('config:user.role.authenticated');
$this->drupalGet($route_access_url);
$this->assertCacheContext('user.permissions');
$this->assertNoCacheTag('config:user.role.authenticated');
}
/**
* Tests the 4xx-response cache tag is added and invalidated.
*/
function testPageCacheAnonymous403404() {
$admin_url = Url::fromRoute('system.admin');
$invalid_url = 'foo/does_not_exist';
$tests = [
403 => $admin_url,
404 => $invalid_url,
];
$cache_ttl_4xx = Settings::get('cache_ttl_4xx', 3600);
foreach ($tests as $code => $content_url) {
// Anonymous user, without permissions.
$this->drupalGet($content_url);
$this->assertResponse($code);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$this->assertCacheTag('4xx-response');
$this->drupalGet($content_url);
$this->assertResponse($code);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$entity_values = array(
'name' => $this->randomMachineName(),
'user_id' => 1,
'field_test_text' => array(
0 => array(
'value' => $this->randomString(),
'format' => 'plain_text',
)
),
);
$entity = EntityTest::create($entity_values);
$entity->save();
// Saving an entity clears 4xx cache tag.
$this->drupalGet($content_url);
$this->assertResponse($code);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$this->drupalGet($content_url);
$this->assertResponse($code);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
// Rebuilding the router should invalidate the 4xx cache tag.
$this->container->get('router.builder')->rebuild();
$this->drupalGet($content_url);
$this->assertResponse($code);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
// Ensure the 'expire' field on the cache entry uses cache_ttl_4xx.
$cache_item = \Drupal::service('cache.render')->get($this->getUrl() . ':html');
$difference = $cache_item->expire - (int) $cache_item->created;
// Given that a second might have passed we cannot be sure that
// $difference will exactly equal the default cache_ttl_4xx setting.
// Account for any timing difference or rounding errors by ensuring the
// value is within 5 seconds.
$this->assertTrue(
$difference > $cache_ttl_4xx - 5 &&
$difference < $cache_ttl_4xx + 5,
'The cache entry expiry time uses the cache_ttl_4xx setting.'
);
}
// Disable 403 and 404 caching.
$settings['settings']['cache_ttl_4xx'] = (object) array(
'value' => 0,
'required' => TRUE,
);
$this->writeSettings($settings);
\Drupal::service('cache.render')->deleteAll();
foreach ($tests as $code => $content_url) {
// Getting the 404 page twice should still result in a cache miss.
$this->drupalGet($content_url);
$this->drupalGet($content_url);
$this->assertResponse($code);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
}
}
/**
* Tests the omit_vary_cookie setting.
*/
public function testPageCacheWithoutVaryCookie() {
$config = $this->config('system.performance');
$config->set('cache.page.max_age', 300);
$config->save();
$settings['settings']['omit_vary_cookie'] = (object) array(
'value' => TRUE,
'required' => TRUE,
);
$this->writeSettings($settings);
// Fill the cache.
$this->drupalGet('');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
$this->assertTrue(strpos($this->drupalGetHeader('Vary'), 'Cookie') === FALSE, 'Vary: Cookie header was not sent.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
// Check cache.
$this->drupalGet('');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
$this->assertTrue(strpos($this->drupalGetHeader('Vary'), 'Cookie') === FALSE, 'Vary: Cookie header was not sent.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
}
/**
* Test the setting of forms to be immutable.
*/
public function testFormImmutability() {
// Install the module that provides the test form.
$this->container->get('module_installer')
->install(['page_cache_form_test']);
// Uninstall the page_cache module to verify that form is immutable
// regardless of the internal page cache module.
$this->container->get('module_installer')->uninstall(['page_cache']);
\Drupal::service('router.builder')->rebuild();
$this->drupalGet('page_cache_form_test_immutability');
$this->assertText("Immutable: TRUE", "Form is immutable.");
// The immutable flag is set unconditionally by system_form_alter(), set
// a flag to tell page_cache_form_test_module_implements_alter() to disable
// that implementation.
\Drupal::state()->set('page_cache_bypass_form_immutability', TRUE);
\Drupal::moduleHandler()->resetImplementations();
Cache::invalidateTags(['rendered']);
$this->drupalGet('page_cache_form_test_immutability');
$this->assertText("Immutable: FALSE", "Form is not immutable,");
}
/**
* Tests cacheability of a CacheableResponse.
*
* Tests the difference between having a controller return a plain Symfony
* Response object versus returning a Response object that implements the
* CacheableResponseInterface.
*/
public function testCacheableResponseResponses() {
$config = $this->config('system.performance');
$config->set('cache.page.max_age', 300);
$config->save();
// GET a URL, which would be marked as a cache miss if it were cacheable.
$this->drupalGet('/system-test/respond-reponse');
$this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'must-revalidate, no-cache, private', 'Cache-Control header was sent');
// GET it again, verify it's still not cached.
$this->drupalGet('/system-test/respond-reponse');
$this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'must-revalidate, no-cache, private', 'Cache-Control header was sent');
// GET a URL, which would be marked as a cache miss if it were cacheable.
$this->drupalGet('/system-test/respond-public-response');
$this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=60, public', 'Cache-Control header was sent');
// GET it again, verify it's still not cached.
$this->drupalGet('/system-test/respond-public-response');
$this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=60, public', 'Cache-Control header was sent');
// GET a URL, which should be marked as a cache miss.
$this->drupalGet('/system-test/respond-cacheable-reponse');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
// GET it again, it should now be a cache hit.
$this->drupalGet('/system-test/respond-cacheable-reponse');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'max-age=300, public', 'Cache-Control header was sent.');
// Uninstall page cache. This should flush all caches so the next call to a
// previously cached page should be a miss now.
$this->container->get('module_installer')
->uninstall(['page_cache']);
// GET a URL that was cached by Page Cache before, it should not be now.
$this->drupalGet('/respond-cacheable-reponse');
$this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Drupal page cache header not found.');
}
/**
* Tests that HEAD requests are treated the same as GET requests.
*/
public function testHead() {
// GET, then HEAD.
$url_a = $this->buildUrl('system-test/set-header', ['query' => ['name' => 'Foo', 'value' => 'bar']]);
$response_body = $this->curlExec([CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $url_a, CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_NOBODY => FALSE]);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
$this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
$this->assertEqual('The following header was set: <em class="placeholder">Foo</em>: <em class="placeholder">bar</em>', $response_body);
$response_body = $this->curlExec([CURLOPT_HTTPGET => FALSE, CURLOPT_URL => $url_a, CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => FALSE]);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
$this->assertEqual($this->drupalGetHeader('Foo'), 'bar', 'Custom header was sent.');
$this->assertEqual('', $response_body);
// HEAD, then GET.
$url_b = $this->buildUrl('system-test/set-header', ['query' => ['name' => 'Foo', 'value' => 'baz']]);
$response_body = $this->curlExec([CURLOPT_HTTPGET => FALSE, CURLOPT_URL => $url_b, CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => FALSE]);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
$this->assertEqual($this->drupalGetHeader('Foo'), 'baz', 'Custom header was sent.');
$this->assertEqual('', $response_body);
$response_body = $this->curlExec([CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $url_b, CURLOPT_CUSTOMREQUEST => 'GET', CURLOPT_NOBODY => FALSE]);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
$this->assertEqual($this->drupalGetHeader('Foo'), 'baz', 'Custom header was sent.');
$this->assertEqual('The following header was set: <em class="placeholder">Foo</em>: <em class="placeholder">baz</em>', $response_body);
}
}

View file

@ -0,0 +1,6 @@
name: 'Page Cache Form Test'
type: module
description: 'Support module for the Page Cache module tests.'
core: 8.x
package: Testing
version: VERSION

View file

@ -0,0 +1,12 @@
<?php
/**
* @file
* Install hooks for page_cache_form_test.
*/
function page_cache_form_test_install() {
// Set an explicit module weight, to ensure that the form alter hook is
// always called after page_cache_form_alter().
module_set_weight('page_cache_form_test', 10);
}

View file

@ -0,0 +1,40 @@
<?php
/**
* @file
* Provides functionality for testing form caching.
*/
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_form_FORM_ID_alter().
*/
function page_cache_form_test_form_page_cache_form_test_alter(&$form, FormStateInterface $form_state, $form_id) {
// This runs earlier than system_form_alter() so we fore-go the immutability
// check to the process callback, by which time system_form_alter() has run.
$form['#process'][] = 'page_cache_form_test_form_page_cache_form_test_process';
}
/**
* Process callback to check immutability.
*/
function page_cache_form_test_form_page_cache_form_test_process($form, FormStateInterface $form_state) {
if (isset($form_state->getBuildInfo()['immutable']) && $form_state->getBuildInfo()['immutable']) {
$form['#suffix'] = 'Immutable: TRUE';
}
else {
$form['#suffix'] = 'Immutable: FALSE';
}
return $form;
}
/**
* Implements hook_module_implements_alter().
*/
function page_cache_form_test_module_implements_alter(&$implementations, $hook) {
if ($hook === 'form_alter' && \Drupal::state()->get('page_cache_bypass_form_immutability', FALSE)) {
// Disable system_form_alter
unset($implementations['system']);
}
}

View file

@ -0,0 +1,6 @@
page_cache_form_test.test_immutability:
path: '/page_cache_form_test_immutability'
defaults:
_form: '\Drupal\page_cache_form_test\Form\TestForm'
requirements:
_access: 'TRUE'

View file

@ -0,0 +1,30 @@
<?php
namespace Drupal\page_cache_form_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class TestForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'page_cache_form_test';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['#prefix'] = '<p>Llamas are awesome, but kittens are pretty cool too!</p>';
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) { }
}