Token.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. <?php
  2. namespace Drupal\Core\Utility;
  3. use Drupal\Component\Render\HtmlEscapedText;
  4. use Drupal\Component\Render\MarkupInterface;
  5. use Drupal\Core\Cache\CacheableDependencyInterface;
  6. use Drupal\Core\Cache\CacheBackendInterface;
  7. use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
  8. use Drupal\Core\Extension\ModuleHandlerInterface;
  9. use Drupal\Core\Language\LanguageInterface;
  10. use Drupal\Core\Language\LanguageManagerInterface;
  11. use Drupal\Core\Render\AttachmentsInterface;
  12. use Drupal\Core\Render\BubbleableMetadata;
  13. use Drupal\Core\Render\RendererInterface;
  14. /**
  15. * Drupal placeholder/token replacement system.
  16. *
  17. * API functions for replacing placeholders in text with meaningful values.
  18. *
  19. * For example: When configuring automated emails, an administrator enters
  20. * standard text for the email. Variables like the title of a node and the date
  21. * the email was sent can be entered as placeholders like [node:title] and
  22. * [date:short]. When a Drupal module prepares to send the email, it can call
  23. * the Token::replace() function, passing in the text. The token system will
  24. * scan the text for placeholder tokens, give other modules an opportunity to
  25. * replace them with meaningful text, then return the final product to the
  26. * original module.
  27. *
  28. * Tokens follow the form: [$type:$name], where $type is a general class of
  29. * tokens like 'node', 'user', or 'comment' and $name is the name of a given
  30. * placeholder. For example, [node:title] or [node:created:since].
  31. *
  32. * In addition to raw text containing placeholders, modules may pass in an array
  33. * of objects to be used when performing the replacement. The objects should be
  34. * keyed by the token type they correspond to. For example:
  35. *
  36. * @code
  37. * // Load a node and a user, then replace tokens in the text.
  38. * $text = 'On [date:short], [user:name] read [node:title].';
  39. * $node = Node::load(1);
  40. * $user = User::load(1);
  41. *
  42. * // [date:...] tokens use the current date automatically.
  43. * $data = array('node' => $node, 'user' => $user);
  44. * return Token::replace($text, $data);
  45. * @endcode
  46. *
  47. * Some tokens may be chained in the form of [$type:$pointer:$name], where $type
  48. * is a normal token type, $pointer is a reference to another token type, and
  49. * $name is the name of a given placeholder. For example, [node:author:mail]. In
  50. * that example, 'author' is a pointer to the 'user' account that created the
  51. * node, and 'mail' is a placeholder available for any 'user'.
  52. *
  53. * @see Token::replace()
  54. * @see hook_tokens()
  55. * @see hook_token_info()
  56. */
  57. class Token {
  58. /**
  59. * The tag to cache token info with.
  60. */
  61. const TOKEN_INFO_CACHE_TAG = 'token_info';
  62. /**
  63. * The token cache.
  64. *
  65. * @var \Drupal\Core\Cache\CacheBackendInterface
  66. */
  67. protected $cache;
  68. /**
  69. * The language manager.
  70. *
  71. * @var \Drupal\Core\Language\LanguageManagerInterface
  72. */
  73. protected $languageManager;
  74. /**
  75. * Token definitions.
  76. *
  77. * @var array[]|null
  78. * An array of token definitions, or NULL when the definitions are not set.
  79. *
  80. * @see self::setInfo()
  81. * @see self::getInfo()
  82. * @see self::resetInfo()
  83. */
  84. protected $tokenInfo;
  85. /**
  86. * The module handler service.
  87. *
  88. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  89. */
  90. protected $moduleHandler;
  91. /**
  92. * The cache tags invalidator.
  93. *
  94. * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
  95. */
  96. protected $cacheTagsInvalidator;
  97. /**
  98. * The renderer.
  99. *
  100. * @var \Drupal\Core\Render\RendererInterface
  101. */
  102. protected $renderer;
  103. /**
  104. * Constructs a new class instance.
  105. *
  106. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  107. * The module handler.
  108. * @param \Drupal\Core\Cache\CacheBackendInterface $cache
  109. * The token cache.
  110. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
  111. * The language manager.
  112. * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator
  113. * The cache tags invalidator.
  114. * @param \Drupal\Core\Render\RendererInterface $renderer
  115. * The renderer.
  116. */
  117. public function __construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator, RendererInterface $renderer) {
  118. $this->cache = $cache;
  119. $this->languageManager = $language_manager;
  120. $this->moduleHandler = $module_handler;
  121. $this->cacheTagsInvalidator = $cache_tags_invalidator;
  122. $this->renderer = $renderer;
  123. }
  124. /**
  125. * Replaces all tokens in a given string with appropriate values.
  126. *
  127. * @param string $text
  128. * An HTML string containing replaceable tokens. The caller is responsible
  129. * for calling \Drupal\Component\Utility\Html::escape() in case the $text
  130. * was plain text.
  131. * @param array $data
  132. * (optional) An array of keyed objects. For simple replacement scenarios
  133. * 'node', 'user', and others are common keys, with an accompanying node or
  134. * user object being the value. Some token types, like 'site', do not require
  135. * any explicit information from $data and can be replaced even if it is
  136. * empty.
  137. * @param array $options
  138. * (optional) A keyed array of settings and flags to control the token
  139. * replacement process. Supported options are:
  140. * - langcode: A language code to be used when generating locale-sensitive
  141. * tokens.
  142. * - callback: A callback function that will be used to post-process the
  143. * array of token replacements after they are generated.
  144. * - clear: A boolean flag indicating that tokens should be removed from the
  145. * final text if no replacement value can be generated.
  146. * @param \Drupal\Core\Render\BubbleableMetadata|null $bubbleable_metadata
  147. * (optional) An object to which static::generate() and the hooks and
  148. * functions that it invokes will add their required bubbleable metadata.
  149. *
  150. * To ensure that the metadata associated with the token replacements gets
  151. * attached to the same render array that contains the token-replaced text,
  152. * callers of this method are encouraged to pass in a BubbleableMetadata
  153. * object and apply it to the corresponding render array. For example:
  154. * @code
  155. * $bubbleable_metadata = new BubbleableMetadata();
  156. * $build['#markup'] = $token_service->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
  157. * $bubbleable_metadata->applyTo($build);
  158. * @endcode
  159. *
  160. * When the caller does not pass in a BubbleableMetadata object, this
  161. * method creates a local one, and applies the collected metadata to the
  162. * Renderer's currently active render context.
  163. *
  164. * @return string
  165. * The token result is the entered HTML text with tokens replaced. The
  166. * caller is responsible for choosing the right escaping / sanitization. If
  167. * the result is intended to be used as plain text, using
  168. * PlainTextOutput::renderFromHtml() is recommended. If the result is just
  169. * printed as part of a template relying on Twig autoescaping is possible,
  170. * otherwise for example the result can be put into #markup, in which case
  171. * it would be sanitized by Xss::filterAdmin().
  172. */
  173. public function replace($text, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
  174. $text_tokens = $this->scan($text);
  175. if (empty($text_tokens)) {
  176. return $text;
  177. }
  178. $bubbleable_metadata_is_passed_in = (bool) $bubbleable_metadata;
  179. $bubbleable_metadata = $bubbleable_metadata ?: new BubbleableMetadata();
  180. $replacements = [];
  181. foreach ($text_tokens as $type => $tokens) {
  182. $replacements += $this->generate($type, $tokens, $data, $options, $bubbleable_metadata);
  183. if (!empty($options['clear'])) {
  184. $replacements += array_fill_keys($tokens, '');
  185. }
  186. }
  187. // Escape the tokens, unless they are explicitly markup.
  188. foreach ($replacements as $token => $value) {
  189. $replacements[$token] = $value instanceof MarkupInterface ? $value : new HtmlEscapedText($value);
  190. }
  191. // Optionally alter the list of replacement values.
  192. if (!empty($options['callback'])) {
  193. $function = $options['callback'];
  194. $function($replacements, $data, $options, $bubbleable_metadata);
  195. }
  196. $tokens = array_keys($replacements);
  197. $values = array_values($replacements);
  198. // If a local $bubbleable_metadata object was created, apply the metadata
  199. // it collected to the renderer's currently active render context.
  200. if (!$bubbleable_metadata_is_passed_in && $this->renderer->hasRenderContext()) {
  201. $build = [];
  202. $bubbleable_metadata->applyTo($build);
  203. $this->renderer->render($build);
  204. }
  205. return str_replace($tokens, $values, $text);
  206. }
  207. /**
  208. * Builds a list of all token-like patterns that appear in the text.
  209. *
  210. * @param string $text
  211. * The text to be scanned for possible tokens.
  212. *
  213. * @return array
  214. * An associative array of discovered tokens, grouped by type.
  215. */
  216. public function scan($text) {
  217. // Matches tokens with the following pattern: [$type:$name]
  218. // $type and $name may not contain [ ] characters.
  219. // $type may not contain : or whitespace characters, but $name may.
  220. preg_match_all('/
  221. \[ # [ - pattern start
  222. ([^\s\[\]:]+) # match $type not containing whitespace : [ or ]
  223. : # : - separator
  224. ([^\[\]]+) # match $name not containing [ or ]
  225. \] # ] - pattern end
  226. /x', $text, $matches);
  227. $types = $matches[1];
  228. $tokens = $matches[2];
  229. // Iterate through the matches, building an associative array containing
  230. // $tokens grouped by $types, pointing to the version of the token found in
  231. // the source text. For example, $results['node']['title'] = '[node:title]';
  232. $results = [];
  233. for ($i = 0; $i < count($tokens); $i++) {
  234. $results[$types[$i]][$tokens[$i]] = $matches[0][$i];
  235. }
  236. return $results;
  237. }
  238. /**
  239. * Generates replacement values for a list of tokens.
  240. *
  241. * @param string $type
  242. * The type of token being replaced. 'node', 'user', and 'date' are common.
  243. * @param array $tokens
  244. * An array of tokens to be replaced, keyed by the literal text of the token
  245. * as it appeared in the source text.
  246. * @param array $data
  247. * An array of keyed objects. For simple replacement scenarios: 'node',
  248. * 'user', and others are common keys, with an accompanying node or user
  249. * object being the value. Some token types, like 'site', do not require
  250. * any explicit information from $data and can be replaced even if it is
  251. * empty.
  252. * @param array $options
  253. * A keyed array of settings and flags to control the token replacement
  254. * process. Supported options are:
  255. * - langcode: A language code to be used when generating locale-sensitive
  256. * tokens.
  257. * - callback: A callback function that will be used to post-process the
  258. * array of token replacements after they are generated. Can be used when
  259. * modules require special formatting of token text, for example URL
  260. * encoding or truncation to a specific length.
  261. * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
  262. * The bubbleable metadata. This is passed to the token replacement
  263. * implementations so that they can attach their metadata.
  264. *
  265. * @return array
  266. * An associative array of replacement values, keyed by the original 'raw'
  267. * tokens that were found in the source text. For example:
  268. * $results['[node:title]'] = 'My new node';
  269. *
  270. * @see hook_tokens()
  271. * @see hook_tokens_alter()
  272. */
  273. public function generate($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  274. foreach ($data as $object) {
  275. if ($object instanceof CacheableDependencyInterface || $object instanceof AttachmentsInterface) {
  276. $bubbleable_metadata->addCacheableDependency($object);
  277. }
  278. }
  279. $replacements = $this->moduleHandler->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata]);
  280. // Allow other modules to alter the replacements.
  281. $context = [
  282. 'type' => $type,
  283. 'tokens' => $tokens,
  284. 'data' => $data,
  285. 'options' => $options,
  286. ];
  287. $this->moduleHandler->alter('tokens', $replacements, $context, $bubbleable_metadata);
  288. return $replacements;
  289. }
  290. /**
  291. * Returns a list of tokens that begin with a specific prefix.
  292. *
  293. * Used to extract a group of 'chained' tokens (such as [node:author:name])
  294. * from the full list of tokens found in text. For example:
  295. * @code
  296. * $data = array(
  297. * 'author:name' => '[node:author:name]',
  298. * 'title' => '[node:title]',
  299. * 'created' => '[node:created]',
  300. * );
  301. * $results = Token::findWithPrefix($data, 'author');
  302. * $results == array('name' => '[node:author:name]');
  303. * @endcode
  304. *
  305. * @param array $tokens
  306. * A keyed array of tokens, and their original raw form in the source text.
  307. * @param string $prefix
  308. * A textual string to be matched at the beginning of the token.
  309. * @param string $delimiter
  310. * (optional) A string containing the character that separates the prefix from
  311. * the rest of the token. Defaults to ':'.
  312. *
  313. * @return array
  314. * An associative array of discovered tokens, with the prefix and delimiter
  315. * stripped from the key.
  316. */
  317. public function findWithPrefix(array $tokens, $prefix, $delimiter = ':') {
  318. $results = [];
  319. foreach ($tokens as $token => $raw) {
  320. $parts = explode($delimiter, $token, 2);
  321. if (count($parts) == 2 && $parts[0] == $prefix) {
  322. $results[$parts[1]] = $raw;
  323. }
  324. }
  325. return $results;
  326. }
  327. /**
  328. * Returns metadata describing supported tokens.
  329. *
  330. * The metadata array contains token type, name, and description data as well
  331. * as an optional pointer indicating that the token chains to another set of
  332. * tokens.
  333. *
  334. * @return array
  335. * An associative array of token information, grouped by token type. The
  336. * array structure is identical to that of hook_token_info().
  337. *
  338. * @see hook_token_info()
  339. */
  340. public function getInfo() {
  341. if (is_null($this->tokenInfo)) {
  342. $cache_id = 'token_info:' . $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
  343. $cache = $this->cache->get($cache_id);
  344. if ($cache) {
  345. $this->tokenInfo = $cache->data;
  346. }
  347. else {
  348. $this->tokenInfo = $this->moduleHandler->invokeAll('token_info');
  349. $this->moduleHandler->alter('token_info', $this->tokenInfo);
  350. $this->cache->set($cache_id, $this->tokenInfo, CacheBackendInterface::CACHE_PERMANENT, [
  351. static::TOKEN_INFO_CACHE_TAG,
  352. ]);
  353. }
  354. }
  355. return $this->tokenInfo;
  356. }
  357. /**
  358. * Sets metadata describing supported tokens.
  359. *
  360. * @param array $tokens
  361. * Token metadata that has an identical structure to the return value of
  362. * hook_token_info().
  363. *
  364. * @see hook_token_info()
  365. */
  366. public function setInfo(array $tokens) {
  367. $this->tokenInfo = $tokens;
  368. }
  369. /**
  370. * Resets metadata describing supported tokens.
  371. */
  372. public function resetInfo() {
  373. $this->tokenInfo = NULL;
  374. $this->cacheTagsInvalidator->invalidateTags([static::TOKEN_INFO_CACHE_TAG]);
  375. }
  376. }