Commit 1a0cdcd3 authored by effulgentsia's avatar effulgentsia

Issue #2525910 by dawehner, effulgentsia, Berdir, lauriii, larowlan,...

Issue #2525910 by dawehner, effulgentsia, Berdir, lauriii, larowlan, timmillwood, Wim Leers, chx, arlinsandbulte, Fabianx, Gábor Hojtsy, Dave Reid, alexpott, catch: Ensure token replacements have cacheability + attachments metadata and that it is bubbled in any case
parent 4f60dd53
......@@ -1185,7 +1185,7 @@ services:
- { name: service_collector, tag: breadcrumb_builder, call: addBuilder }
token:
class: Drupal\Core\Utility\Token
arguments: ['@module_handler', '@cache.discovery', '@language_manager', '@cache_tags.invalidator']
arguments: ['@module_handler', '@cache.discovery', '@language_manager', '@cache_tags.invalidator', '@renderer']
batch.storage:
class: Drupal\Core\Batch\BatchStorage
arguments: ['@database', '@session', '@csrf_token']
......
......@@ -132,6 +132,35 @@ public function setCacheMaxAge($max_age) {
return $this;
}
/**
* Adds a dependency on an object: merges its cacheability metadata.
*
* @param \Drupal\Core\Cache\CacheableDependencyInterface|mixed $other_object
* The dependency. If the object implements CacheableDependencyInterface,
* then its cacheability metadata will be used. Otherwise, the passed in
* object must be assumed to be uncacheable, so max-age 0 is set.
*
* @return $this
*/
public function addCacheableDependency($other_object) {
if ($other_object instanceof CacheableDependencyInterface) {
$this->addCacheTags($other_object->getCacheTags());
$this->addCacheContexts($other_object->getCacheContexts());
if ($this->maxAge === Cache::PERMANENT) {
$this->maxAge = $other_object->getCacheMaxAge();
}
elseif (($max_age = $other_object->getCacheMaxAge()) && $max_age !== Cache::PERMANENT) {
$this->maxAge = Cache::mergeMaxAges($this->maxAge, $max_age);
}
}
else {
// Not a cacheable dependency, this can not be cached.
$this->maxAge = 0;
}
return $this;
}
/**
* Merges the values of another CacheableMetadata object with this one.
*
......
......@@ -94,6 +94,19 @@ public static function createFromObject($object) {
return $meta;
}
/**
* {@inheritdoc}
*/
public function addCacheableDependency($other_object) {
parent::addCacheableDependency($other_object);
if ($other_object instanceof AttachmentsInterface) {
$this->addAttachments($other_object->getAttachments());
}
return $this;
}
/**
* Merges two attachments arrays (which live under the '#attached' key).
*
......
......@@ -8,11 +8,15 @@
namespace Drupal\Core\Utility;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Render\AttachmentsInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Render\RendererInterface;
/**
* Drupal placeholder/token replacement system.
......@@ -104,6 +108,13 @@ class Token {
*/
protected $cacheTagsInvalidator;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Constructs a new class instance.
*
......@@ -115,12 +126,15 @@ class Token {
* The language manager.
* @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
* The cache tags invalidator.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
*/
public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator) {
public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator, RendererInterface $renderer) {
$this->cache = $cache;
$this->languageManager = $language_manager;
$this->moduleHandler = $module_handler;
$this->cacheTagsInvalidator = $cache_tags_invalidator;
$this->renderer = $renderer;
}
/**
......@@ -152,19 +166,39 @@ public function __construct(ModuleHandlerInterface $module_handler, CacheBackend
* \Drupal\Component\Utility\Xss::filter(),
* \Drupal\Component\Utility\SafeMarkup::checkPlain() or other appropriate
* scrubbing functions before displaying data to users.
* @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata|null
* (optional) An object to which static::generate() and the hooks and
* functions that it invokes will add their required bubbleable metadata.
*
* To ensure that the metadata associated with the token replacements gets
* attached to the same render array that contains the token-replaced text,
* callers of this method are encouraged to pass in a BubbleableMetadata
* object and apply it to the corresponding render array. For example:
* @code
* $bubbleable_metadata = new BubbleableMetadata();
* $build['#markup'] = $token_service->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
* $bubbleable_metadata->applyTo($build);
* @endcode
*
* When the caller does not pass in a BubbleableMetadata object, this
* method creates a local one, and applies the collected metadata to the
* Renderer's currently active render context.
*
* @return string
* Text with tokens replaced.
*/
public function replace($text, array $data = array(), array $options = array()) {
public function replace($text, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata = NULL) {
$text_tokens = $this->scan($text);
if (empty($text_tokens)) {
return $text;
}
$bubbleable_metadata_is_passed_in = (bool) $bubbleable_metadata;
$bubbleable_metadata = $bubbleable_metadata ?: new BubbleableMetadata();
$replacements = array();
foreach ($text_tokens as $type => $tokens) {
$replacements += $this->generate($type, $tokens, $data, $options);
$replacements += $this->generate($type, $tokens, $data, $options, $bubbleable_metadata);
if (!empty($options['clear'])) {
$replacements += array_fill_keys($tokens, '');
}
......@@ -173,12 +207,20 @@ public function replace($text, array $data = array(), array $options = array())
// Optionally alter the list of replacement values.
if (!empty($options['callback'])) {
$function = $options['callback'];
$function($replacements, $data, $options);
$function($replacements, $data, $options, $bubbleable_metadata);
}
$tokens = array_keys($replacements);
$values = array_values($replacements);
// If a local $bubbleable_metadata object was created, apply the metadata
// it collected to the renderer's currently active render context.
if (!$bubbleable_metadata_is_passed_in && $this->renderer->hasRenderContext()) {
$build = [];
$bubbleable_metadata->applyTo($build);
$this->renderer->render($build);
}
return str_replace($tokens, $values, $text);
}
......@@ -226,14 +268,14 @@ public function scan($text) {
* An array of tokens to be replaced, keyed by the literal text of the token
* as it appeared in the source text.
* @param array $data
* (optional) An array of keyed objects. For simple replacement scenarios
* 'node', 'user', and others are common keys, with an accompanying node or
* user object being the value. Some token types, like 'site', do not require
* An array of keyed objects. For simple replacement scenarios: 'node',
* 'user', and others are common keys, with an accompanying node or user
* object being the value. Some token types, like 'site', do not require
* any explicit information from $data and can be replaced even if it is
* empty.
* @param array $options
* (optional) A keyed array of settings and flags to control the token
* replacement process. Supported options are:
* A keyed array of settings and flags to control the token replacement
* process. Supported options are:
* - langcode: A language code to be used when generating locale-sensitive
* tokens.
* - callback: A callback function that will be used to post-process the
......@@ -245,6 +287,9 @@ public function scan($text) {
* responsibility for running \Drupal\Component\Utility\Xss::filter(),
* \Drupal\Component\Utility\SafeMarkup::checkPlain() or other appropriate
* scrubbing functions before displaying data to users.
* @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
* The bubbleable metadata. This is passed to the token replacement
* implementations so that they can attach their metadata.
*
* @return array
* An associative array of replacement values, keyed by the original 'raw'
......@@ -254,9 +299,16 @@ public function scan($text) {
* @see hook_tokens()
* @see hook_tokens_alter()
*/
public function generate($type, array $tokens, array $data = array(), array $options = array()) {
public function generate($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$options += array('sanitize' => TRUE);
$replacements = $this->moduleHandler->invokeAll('tokens', array($type, $tokens, $data, $options));
foreach ($data as $object) {
if ($object instanceof CacheableDependencyInterface || $object instanceof AttachmentsInterface) {
$bubbleable_metadata->addCacheableDependency($object);
}
}
$replacements = $this->moduleHandler->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata]);
// Allow other modules to alter the replacements.
$context = array(
......@@ -265,7 +317,7 @@ public function generate($type, array $tokens, array $data = array(), array $opt
'data' => $data,
'options' => $options,
);
$this->moduleHandler->alter('tokens', $replacements, $context);
$this->moduleHandler->alter('tokens', $replacements, $context, $bubbleable_metadata);
return $replacements;
}
......
......@@ -34,22 +34,43 @@
* An array of tokens to be replaced. The keys are the machine-readable token
* names, and the values are the raw [type:token] strings that appeared in the
* original text.
* @param $data
* (optional) An associative array of data objects to be used when generating
* replacement values, as supplied in the $data parameter to
* \Drupal\Core\Utility\Token::replace().
* @param $options
* (optional) An associative array of options for token replacement; see
* @param array $data
* An associative array of data objects to be used when generating replacement
* values, as supplied in the $data parameter to
* \Drupal\Core\Utility\Token::replace().
* @param array $options
* An associative array of options for token replacement; see
* \Drupal\Core\Utility\Token::replace() for possible values.
* @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
* The bubbleable metadata. Prior to invoking this hook,
* \Drupal\Core\Utility\Token::generate() collects metadata for all of the
* data objects in $data. For any data sources not in $data, but that are
* used by the token replacement logic, such as global configuration (e.g.,
* 'system.site') and related objects (e.g., $node->getOwner()),
* implementations of this hook must add the corresponding metadata.
* For example:
* @code
* $bubbleable_metadata->addCacheableDependency(\Drupal::config('system.site'));
* $bubbleable_metadata->addCacheableDependency($node->getOwner());
* @endcode
*
* @return
* Additionally, implementations of this hook, must forward
* $bubbleable_metadata to the chained tokens that they invoke.
* For example:
* @code
* if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
* $replacements = $token_service->generate('date', $created_tokens, array('date' => $node->getCreatedTime()), $options, $bubbleable_metadata);
* }
* @endcode
*
* @return array
* An associative array of replacement values, keyed by the raw [type:token]
* strings from the original text.
*
* @see hook_token_info()
* @see hook_tokens_alter()
*/
function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
function hook_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
$token_service = \Drupal::token();
$url_options = array('absolute' => TRUE);
......@@ -87,6 +108,7 @@ function hook_tokens($type, $tokens, array $data = array(), array $options = arr
case 'author':
$account = $node->getOwner() ? $node->getOwner() : User::load(0);
$replacements[$original] = $sanitize ? SafeMarkup::checkPlain($account->label()) : $account->label();
$bubbleable_metadata->addCacheableDependency($account);
break;
case 'created':
......@@ -96,11 +118,11 @@ function hook_tokens($type, $tokens, array $data = array(), array $options = arr
}
if ($author_tokens = $token_service->findWithPrefix($tokens, 'author')) {
$replacements = $token_service->generate('user', $author_tokens, array('user' => $node->getOwner()), $options);
$replacements = $token_service->generate('user', $author_tokens, array('user' => $node->getOwner()), $options, $bubbleable_metadata);
}
if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
$replacements = $token_service->generate('date', $created_tokens, array('date' => $node->getCreatedTime()), $options);
$replacements = $token_service->generate('date', $created_tokens, array('date' => $node->getCreatedTime()), $options, $bubbleable_metadata);
}
}
......@@ -120,10 +142,14 @@ function hook_tokens($type, $tokens, array $data = array(), array $options = arr
* - 'tokens'
* - 'data'
* - 'options'
* @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
* The bubbleable metadata. In case you alter an existing token based upon
* a data source that isn't in $context['data'], you must add that
* dependency to $bubbleable_metadata.
*
* @see hook_tokens()
*/
function hook_tokens_alter(array &$replacements, array $context) {
function hook_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
$options = $context['options'];
if (isset($options['langcode'])) {
......
......@@ -7,6 +7,8 @@
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Datetime\Entity\DateFormat;
use Drupal\Core\Render\BubbleableMetadata;
/**
* Implements hook_token_info().
......@@ -105,7 +107,7 @@ function comment_token_info() {
/**
* Implements hook_tokens().
*/
function comment_tokens($type, $tokens, array $data = array(), array $options = array()) {
function comment_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$token_service = \Drupal::token();
$url_options = array('absolute' => TRUE);
......@@ -138,6 +140,11 @@ function comment_tokens($type, $tokens, array $data = array(), array $options =
case 'mail':
$mail = $comment->getAuthorEmail();
// Add the user cacheability metadata in case the author of the comment
// is not the anonymous user.
if ($comment->getOwnerId()) {
$bubbleable_metadata->addCacheableDependency($comment->getOwner());
}
$replacements[$original] = $sanitize ? SafeMarkup::checkPlain($mail) : $mail;
break;
......@@ -170,26 +177,37 @@ function comment_tokens($type, $tokens, array $data = array(), array $options =
case 'author':
$name = $comment->getAuthorName();
// Add the user cacheability metadata in case the author of the comment
// is not the anonymous user.
if ($comment->getOwnerId()) {
$bubbleable_metadata->addCacheableDependency($comment->getOwner());
}
$replacements[$original] = $sanitize ? Xss::filter($name) : $name;
break;
case 'parent':
if ($comment->hasParentComment()) {
$parent = $comment->getParentComment();
$bubbleable_metadata->addCacheableDependency($parent);
$replacements[$original] = $sanitize ? Xss::filter($parent->getSubject()) : $parent->getSubject();
}
break;
case 'created':
$date_format = DateFormat::load('medium');
$bubbleable_metadata->addCacheableDependency($date_format);
$replacements[$original] = format_date($comment->getCreatedTime(), 'medium', '', NULL, $langcode);
break;
case 'changed':
$date_format = DateFormat::load('medium');
$bubbleable_metadata->addCacheableDependency($date_format);
$replacements[$original] = format_date($comment->getChangedTime(), 'medium', '', NULL, $langcode);
break;
case 'entity':
$entity = $comment->getCommentedEntity();
$bubbleable_metadata->addCacheableDependency($entity);
$title = $entity->label();
$replacements[$original] = $sanitize ? Xss::filter($title) : $title;
break;
......@@ -199,23 +217,23 @@ function comment_tokens($type, $tokens, array $data = array(), array $options =
// Chained token relationships.
if ($entity_tokens = $token_service->findwithPrefix($tokens, 'entity')) {
$entity = $comment->getCommentedEntity();
$replacements += $token_service->generate($comment->getCommentedEntityTypeId(), $entity_tokens, array($comment->getCommentedEntityTypeId() => $entity), $options);
$replacements += $token_service->generate($comment->getCommentedEntityTypeId(), $entity_tokens, array($comment->getCommentedEntityTypeId() => $entity), $options, $bubbleable_metadata);
}
if ($date_tokens = $token_service->findwithPrefix($tokens, 'created')) {
$replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getCreatedTime()), $options);
$replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getCreatedTime()), $options, $bubbleable_metadata);
}
if ($date_tokens = $token_service->findwithPrefix($tokens, 'changed')) {
$replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getChangedTime()), $options);
$replacements += $token_service->generate('date', $date_tokens, array('date' => $comment->getChangedTime()), $options, $bubbleable_metadata);
}
if (($parent_tokens = $token_service->findwithPrefix($tokens, 'parent')) && $parent = $comment->getParentComment()) {
$replacements += $token_service->generate('comment', $parent_tokens, array('comment' => $parent), $options);
$replacements += $token_service->generate('comment', $parent_tokens, array('comment' => $parent), $options, $bubbleable_metadata);
}
if (($author_tokens = $token_service->findwithPrefix($tokens, 'author')) && $account = $comment->getOwner()) {
$replacements += $token_service->generate('user', $author_tokens, array('user' => $account), $options);
$replacements += $token_service->generate('user', $author_tokens, array('user' => $account), $options, $bubbleable_metadata);
}
}
elseif ($type == 'entity' & !empty($data['entity'])) {
......
......@@ -10,6 +10,7 @@
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Xss;
use Drupal\comment\Entity\Comment;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\node\Entity\Node;
/**
......@@ -60,6 +61,7 @@ function testCommentTokenReplacement() {
$tests['[comment:langcode]'] = SafeMarkup::checkPlain($comment->language()->getId());
$tests['[comment:url]'] = $comment->url('canonical', $url_options + array('fragment' => 'comment-' . $comment->id()));
$tests['[comment:edit-url]'] = $comment->url('edit-form', $url_options);
$tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', array('langcode' => $language_interface->getId()));
$tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime(), array('langcode' => $language_interface->getId()));
$tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations(), array('langcode' => $language_interface->getId()));
$tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL;
......@@ -71,12 +73,48 @@ function testCommentTokenReplacement() {
$tests['[comment:author:uid]'] = $comment->getOwnerId();
$tests['[comment:author:name]'] = SafeMarkup::checkPlain($this->adminUser->getUsername());
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($comment);
$metadata_tests = [];
$metadata_tests['[comment:cid]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:hostname]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$bubbleable_metadata->addCacheableDependency($this->adminUser);
$metadata_tests['[comment:author]'] = $bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$bubbleable_metadata->addCacheableDependency($this->adminUser);
$metadata_tests['[comment:mail]'] = $bubbleable_metadata;
$metadata_tests['[comment:homepage]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:title]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:body]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:langcode]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:url]'] = $base_bubbleable_metadata;
$metadata_tests['[comment:edit-url]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:created]'] = $bubbleable_metadata->addCacheTags(['rendered']);
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:created:since]'] = $bubbleable_metadata->setCacheMaxAge(0);
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:changed:since]'] = $bubbleable_metadata->setCacheMaxAge(0);
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:parent:cid]'] = $bubbleable_metadata->addCacheTags(['comment:1']);
$metadata_tests['[comment:parent:title]'] = $bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:entity]'] = $bubbleable_metadata->addCacheTags(['node:2']);
// Test node specific tokens.
$metadata_tests['[comment:entity:nid]'] = $bubbleable_metadata;
$metadata_tests['[comment:entity:title]'] = $bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[comment:author:uid]'] = $bubbleable_metadata->addCacheTags(['user:2']);
$metadata_tests['[comment:author:name]'] = $bubbleable_metadata;
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('comment' => $comment), array('langcode' => $language_interface->getId()));
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_service->replace($input, array('comment' => $comment), array('langcode' => $language_interface->getId()), $bubbleable_metadata);
$this->assertEqual($output, $expected, format_string('Sanitized comment token %token replaced.', array('%token' => $input)));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
// Generate and test unsanitized tokens.
......
......@@ -6,8 +6,10 @@
*/
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Datetime\Entity\DateFormat;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
......@@ -938,7 +940,7 @@ function file_file_predelete(File $file) {
/**
* Implements hook_tokens().
*/
function file_tokens($type, $tokens, array $data = array(), array $options = array()) {
function file_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$token_service = \Drupal::token();
$url_options = array('absolute' => TRUE);
......@@ -987,30 +989,36 @@ function file_tokens($type, $tokens, array $data = array(), array $options = arr
// These tokens are default variations on the chained tokens handled below.
case 'created':
$date_format = DateFormat::load('medium');
$bubbleable_metadata->addCacheableDependency($date_format);
$replacements[$original] = format_date($file->getCreatedTime(), 'medium', '', NULL, $langcode);
break;
case 'changed':
$date_format = DateFormat::load('medium');
$bubbleable_metadata = $bubbleable_metadata->addCacheableDependency($date_format);
$replacements[$original] = format_date($file->getChangedTime(), 'medium', '', NULL, $langcode);
break;
case 'owner':
$name = $file->getOwner()->label();
$owner = $file->getOwner();
$bubbleable_metadata->addCacheableDependency($owner);
$name = $owner->label();
$replacements[$original] = $sanitize ? SafeMarkup::checkPlain($name) : $name;
break;
}
}
if ($date_tokens = $token_service->findWithPrefix($tokens, 'created')) {
$replacements += $token_service->generate('date', $date_tokens, array('date' => $file->getCreatedTime()), $options);
$replacements += $token_service->generate('date', $date_tokens, array('date' => $file->getCreatedTime()), $options, $bubbleable_metadata);
}
if ($date_tokens = $token_service->findWithPrefix($tokens, 'changed')) {
$replacements += $token_service->generate('date', $date_tokens, array('date' => $file->getChangedTime()), $options);
$replacements += $token_service->generate('date', $date_tokens, array('date' => $file->getChangedTime()), $options, $bubbleable_metadata);
}
if (($owner_tokens = $token_service->findWithPrefix($tokens, 'owner')) && $file->getOwner()) {
$replacements += $token_service->generate('user', $owner_tokens, array('user' => $file->getOwner()), $options);
$replacements += $token_service->generate('user', $owner_tokens, array('user' => $file->getOwner()), $options, $bubbleable_metadata);
}
}
......
......@@ -8,6 +8,7 @@
namespace Drupal\file\Tests;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\file\Entity\File;
/**
......@@ -58,12 +59,31 @@ function testFileTokenReplacement() {
$tests['[file:owner]'] = SafeMarkup::checkPlain(user_format_name($this->adminUser));
$tests['[file:owner:uid]'] = $file->getOwnerId();
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($file);
$metadata_tests = [];
$metadata_tests['[file:fid]'] = $base_bubbleable_metadata;
$metadata_tests['[file:name]'] = $base_bubbleable_metadata;
$metadata_tests['[file:path]'] = $base_bubbleable_metadata;
$metadata_tests['[file:mime]'] = $base_bubbleable_metadata;
$metadata_tests['[file:size]'] = $base_bubbleable_metadata;
$metadata_tests['[file:url]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[file:created]'] = $bubbleable_metadata->addCacheTags(['rendered']);
$metadata_tests['[file:created:short]'] = $bubbleable_metadata;
$metadata_tests['[file:changed]'] = $bubbleable_metadata;
$metadata_tests['[file:changed:short]'] = $bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[file:owner]'] = $bubbleable_metadata->addCacheTags(['user:2']);
$metadata_tests['[file:owner:uid]'] = $bubbleable_metadata;
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId()));
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId()), $bubbleable_metadata);
$this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
// Generate and test unsanitized tokens.
......
......@@ -6,7 +6,9 @@
*/
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Datetime\Entity\DateFormat;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\user\Entity\User;
/**
......@@ -83,7 +85,7 @@ function node_token_info() {
/**
* Implements hook_tokens().
*/
function node_tokens($type, $tokens, array $data = array(), array $options = array()) {
function node_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$token_service = \Drupal::token();
$url_options = array('absolute' => TRUE);
......@@ -176,29 +178,34 @@ function node_tokens($type, $tokens, array $data = array(), array $options = arr
// Default values for the chained tokens handled below.
case 'author':
$account = $node->getOwner() ? $node->getOwner() : User::load(0);
$bubbleable_metadata->addCacheableDependency($account);
$replacements[$original] = $sanitize ? SafeMarkup::checkPlain($account->label()) : $account->label();
break;
case 'created':
$date_format = DateFormat::load('medium');
$bubbleable_metadata->addCacheableDependency($date_format);
$replacements[$original] = format_date($node->getCreatedTime(), 'medium', '', NULL, $langcode);
break;
case 'changed':
$date_format = DateFormat::load('medium');
$bubbleable_metadata->addCacheableDependency($date_format);
$replacements[$original] = format_date($node->getChangedTime(), 'medium', '', NULL, $langcode);
break;
}
}
if ($author_tokens = $token_service->findWithPrefix($tokens, 'author')) {
$replacements += $token_service->generate('user', $author_tokens, array('user' => $node->getOwner()), $options);
$replacements += $token_service->generate('user', $author_tokens, array('user' => $node->getOwner()), $options, $bubbleable_metadata);
}
if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
$replacements += $token_service->generate('date', $created_tokens, array('date' => $node->getCreatedTime()), $options);
$replacements += $token_service->generate('date', $created_tokens, array('date' => $node->getCreatedTime()), $options, $bubbleable_metadata);
}
if ($changed_tokens = $token_service->findWithPrefix($tokens, 'changed')) {
$replacements += $token_service->generate('date', $changed_tokens, array('date' => $node->getChangedTime()), $options);
$replacements += $token_service->generate('date', $changed_tokens, array('date' => $node->getChangedTime()), $options, $bubbleable_metadata);
}
}
......
......@@ -7,6 +7,7 @@
namespace Drupal\node\Tests;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\system\Tests\System\TokenReplaceUnitTestBase;
use Drupal\Component\Utility\SafeMarkup;
......@@ -76,12 +77,35 @@ function testNodeTokenReplacement() {
$tests['[node:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getCreatedTime(), array('langcode' => $this->interfaceLanguage->getId()));
$tests['[node:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getChangedTime(), array('langcode' => $this->interfaceLanguage->getId()));
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($node);
$metadata_tests = [];
$metadata_tests['[node:nid]'] = $base_bubbleable_metadata;
$metadata_tests['[node:vid]'] = $base_bubbleable_metadata;
$metadata_tests['[node:type]'] = $base_bubbleable_metadata;
$metadata_tests['[node:type-name]'] = $base_bubbleable_metadata;
$metadata_tests['[node:title]'] = $base_bubbleable_metadata;
$metadata_tests['[node:body]'] = $base_bubbleable_metadata;
$metadata_tests['[node:summary]'] = $base_bubbleable_metadata;
$metadata_tests['[node:langcode]'] = $base_bubbleable_metadata;
$metadata_tests['[node:url]'] = $base_bubbleable_metadata;
$metadata_tests['[node:edit-url]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[node:author]'] = $bubbleable_metadata->addCacheTags(['user:1']);
$metadata_tests['[node:author:uid]'] = $bubbleable_metadata;
$metadata_tests['[node:author:name]'] = $bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[node:created:since]'] = $bubbleable_metadata->setCacheMaxAge(0);
$metadata_tests['[node:changed:since]'] = $bubbleable_metadata;
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId()));
$bubbleable_metadata = new BubbleableMetadata();
$output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId()), $bubbleable_metadata);
$this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced.', array('%token' => $input)));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
// Generate and test unsanitized tokens.
......
......@@ -260,14 +260,17 @@ protected function doTestFrontPageViewCacheTags($do_assert_views_caches) {
'config:views.view.frontpage',
'node_list',
];