token.module 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. <?php
  2. /**
  3. * @file
  4. * Enhances the token API in core: adds a browseable UI, missing tokens, etc.
  5. */
  6. use Drupal\Component\Render\PlainTextOutput;
  7. use Drupal\Core\Block\BlockPluginInterface;
  8. use Drupal\Core\Form\FormStateInterface;
  9. use Drupal\Core\Menu\MenuLinkInterface;
  10. use Drupal\Core\Render\BubbleableMetadata;
  11. use Drupal\Core\Render\Element;
  12. use Drupal\Core\Routing\RouteMatchInterface;
  13. use Drupal\Core\Entity\EntityTypeInterface;
  14. use Drupal\Core\Field\BaseFieldDefinition;
  15. use Drupal\Core\TypedData\TranslatableInterface;
  16. use Drupal\menu_link_content\Entity\MenuLinkContent;
  17. use Drupal\menu_link_content\MenuLinkContentInterface;
  18. use Drupal\node\Entity\Node;
  19. use Drupal\node\NodeInterface;
  20. /**
  21. * Implements hook_help().
  22. */
  23. function token_help($route_name, RouteMatchInterface $route_match) {
  24. if ($route_name == 'help.page.token') {
  25. $token_tree = \Drupal::service('token.tree_builder')->buildAllRenderable([
  26. 'click_insert' => FALSE,
  27. 'show_restricted' => TRUE,
  28. 'show_nested' => FALSE,
  29. ]);
  30. $output = '<h3>' . t('About') . '</h3>';
  31. $output .= '<p>' . t('The <a href=":project">Token</a> module provides a user interface for the site token system. It also adds some additional tokens that are used extensively during site development. Tokens are specially formatted chunks of text that serve as placeholders for a dynamically generated value. For more information, covering both the token system and the additional tools provided by the Token module, see the <a href=":online">online documentation</a>.', [':online' => 'https://www.drupal.org/documentation/modules/token', ':project' => 'https://www.drupal.org/project/token']) . '</p>';
  32. $output .= '<h3>' . t('Uses') . '</h3>';
  33. $output .= '<p>' . t('Your website uses a shared token system for exposing and using placeholder tokens and their appropriate replacement values. This allows for any module to provide placeholder tokens for strings without having to reinvent the wheel. It also ensures consistency in the syntax used for tokens, making the system as a whole easier for end users to use.') . '</p>';
  34. $output .= '<dl>';
  35. $output .= '<dt>' . t('The list of the currently available tokens on this site are shown below.') . '</dt>';
  36. $output .= '<dd>' . \Drupal::service('renderer')->render($token_tree) . '</dd>';
  37. $output .= '</dl>';
  38. return $output;
  39. }
  40. }
  41. /**
  42. * Return an array of the core modules supported by token.module.
  43. */
  44. function _token_core_supported_modules() {
  45. return ['book', 'field', 'menu_ui'];
  46. }
  47. /**
  48. * Implements hook_theme().
  49. */
  50. function token_theme() {
  51. $info['token_tree_link'] = [
  52. 'variables' => [
  53. 'token_types' => [],
  54. 'global_types' => TRUE,
  55. 'click_insert' => TRUE,
  56. 'show_restricted' => FALSE,
  57. 'show_nested' => FALSE,
  58. 'recursion_limit' => 3,
  59. 'text' => NULL,
  60. 'options' => [],
  61. ],
  62. 'file' => 'token.pages.inc',
  63. ];
  64. return $info;
  65. }
  66. /**
  67. * Implements hook_block_view_alter().
  68. */
  69. function token_block_view_alter(&$build, BlockPluginInterface $block) {
  70. if (isset($build['#configuration'])) {
  71. $label = $build['#configuration']['label'];
  72. if ($label != '<none>') {
  73. // The label is automatically escaped, avoid escaping it twice.
  74. // @todo https://www.drupal.org/node/2580723 will add a method or option
  75. // to the token API to do this, use that when available.
  76. $bubbleable_metadata = BubbleableMetadata::createFromRenderArray($build);
  77. $build['#configuration']['label'] = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($label, [], [], $bubbleable_metadata));
  78. $bubbleable_metadata->applyTo($build);
  79. }
  80. }
  81. }
  82. /**
  83. * Implements hook_form_FORM_ID_alter().
  84. */
  85. function token_form_block_form_alter(&$form, FormStateInterface $form_state) {
  86. $token_tree = [
  87. '#theme' => 'token_tree_link',
  88. '#token_types' => [],
  89. ];
  90. $rendered_token_tree = \Drupal::service('renderer')->render($token_tree);
  91. $form['settings']['label']['#description'] = t('This field supports tokens. @browse_tokens_link', [
  92. '@browse_tokens_link' => $rendered_token_tree,
  93. ]);
  94. $form['settings']['label']['#element_validate'][] = 'token_element_validate';
  95. $form['settings']['label'] += ['#token_types' => []];
  96. }
  97. /**
  98. * Implements hook_field_info_alter().
  99. */
  100. function token_field_info_alter(&$info) {
  101. $defaults = [
  102. 'taxonomy_term_reference' => 'taxonomy_term_reference_plain',
  103. 'number_integer' => 'number_unformatted',
  104. 'number_decimal' => 'number_unformatted',
  105. 'number_float' => 'number_unformatted',
  106. 'file' => 'file_url_plain',
  107. 'image' => 'file_url_plain',
  108. 'text' => 'text_default',
  109. 'text_long' => 'text_default',
  110. 'text_with_summary' => 'text_default',
  111. 'list_integer' => 'list_default',
  112. 'list_float' => 'list_default',
  113. 'list_string' => 'list_default',
  114. 'list_boolean' => 'list_default',
  115. ];
  116. foreach ($defaults as $field_type => $default_token_formatter) {
  117. if (isset($info[$field_type])) {
  118. $info[$field_type] += ['default_token_formatter' => $default_token_formatter];
  119. }
  120. }
  121. }
  122. /**
  123. * Implements hook_date_format_insert().
  124. */
  125. function token_date_format_insert() {
  126. token_clear_cache();
  127. }
  128. /**
  129. * Implements hook_date_format_delete().
  130. */
  131. function token_date_format_delete() {
  132. token_clear_cache();
  133. }
  134. /**
  135. * Implements hook_field_storage_config_presave().
  136. */
  137. function token_field_config_presave($instance) {
  138. token_clear_cache();
  139. }
  140. /**
  141. * Implements hook_field_storage_config_delete().
  142. */
  143. function token_field_config_delete($instance) {
  144. token_clear_cache();
  145. }
  146. /**
  147. * Clear token caches and static variables.
  148. */
  149. function token_clear_cache() {
  150. \Drupal::token()->resetInfo();
  151. \Drupal::service('token.entity_mapper')->resetInfo();
  152. drupal_static_reset('token_menu_link_load_all_parents');
  153. drupal_static_reset('token_book_link_load');
  154. }
  155. /**
  156. * Implements hook_entity_type_alter().
  157. *
  158. * Because some token types to do not match their entity type names, we have to
  159. * map them to the proper type. This is purely for other modules' benefit.
  160. *
  161. * @see \Drupal\token\TokenEntityMapperInterface::getEntityTypeMappings()
  162. * @see http://drupal.org/node/737726
  163. */
  164. function token_entity_type_alter(array &$entity_types) {
  165. $devel_exists = \Drupal::moduleHandler()->moduleExists('devel');
  166. /* @var $entity_types EntityTypeInterface[] */
  167. foreach ($entity_types as $entity_type_id => $entity_type) {
  168. if (!$entity_type->get('token_type')) {
  169. // Fill in default token types for entities.
  170. switch ($entity_type_id) {
  171. case 'taxonomy_term':
  172. case 'taxonomy_vocabulary':
  173. // Stupid taxonomy token types...
  174. $entity_type->set('token_type', str_replace('taxonomy_', '', $entity_type_id));
  175. break;
  176. default:
  177. // By default the token type is the same as the entity type.
  178. $entity_type->set('token_type', $entity_type_id);
  179. break;
  180. }
  181. }
  182. if ($devel_exists
  183. && $entity_type->hasViewBuilderClass()
  184. && ($canonical = $entity_type->getLinkTemplate('canonical'))
  185. && !$entity_type->hasLinkTemplate('token-devel')) {
  186. $entity_type->setLinkTemplate('token-devel', $canonical . '/devel/token');
  187. }
  188. }
  189. }
  190. /**
  191. * Implements hook_entity_view_modes_info().
  192. */
  193. /**
  194. * Implements hook_module_implements_alter().
  195. *
  196. * Adds missing token support for core modules.
  197. */
  198. function token_module_implements_alter(&$implementations, $hook) {
  199. \Drupal::moduleHandler()->loadInclude('token', 'inc', 'token.tokens');
  200. if ($hook == 'tokens' || $hook == 'token_info' || $hook == 'token_info_alter' || $hook == 'tokens_alter') {
  201. foreach (_token_core_supported_modules() as $module) {
  202. if (\Drupal::moduleHandler()->moduleExists($module) && function_exists($module . '_' . $hook)) {
  203. $implementations[$module] = TRUE;
  204. }
  205. }
  206. // Move token.module to get included first since it is responsible for
  207. // other modules.
  208. if (isset($implementations['token'])) {
  209. unset($implementations['token']);
  210. $implementations = array_merge(['token' => 'tokens'], $implementations);
  211. }
  212. }
  213. }
  214. /**
  215. * Return the module responsible for a token.
  216. *
  217. * @param string $type
  218. * The token type.
  219. * @param string $name
  220. * The token name.
  221. *
  222. * @return mixed
  223. * The value of $info['tokens'][$type][$name]['module'] from token info, or
  224. * NULL if the value does not exist.
  225. */
  226. function _token_module($type, $name) {
  227. $token_info = \Drupal::token()->getTokenInfo($type, $name);
  228. return isset($token_info['module']) ? $token_info['module'] : NULL;
  229. }
  230. /**
  231. * Validate a form element that should have tokens in it.
  232. *
  233. * Form elements that want to add this validation should have the #token_types
  234. * parameter defined.
  235. *
  236. * For example:
  237. * @code
  238. * $form['my_node_text_element'] = [
  239. * '#type' => 'textfield',
  240. * '#title' => t('Some text to token-ize that has a node context.'),
  241. * '#default_value' => 'The title of this node is [node:title].',
  242. * '#element_validate' => ['token_element_validate'],
  243. * '#token_types' => ['node'],
  244. * '#min_tokens' => 1,
  245. * '#max_tokens' => 10,
  246. * ];
  247. * @endcode
  248. */
  249. function token_element_validate($element, FormStateInterface $form_state) {
  250. $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
  251. if (!mb_strlen($value)) {
  252. // Empty value needs no further validation since the element should depend
  253. // on using the '#required' FAPI property.
  254. return $element;
  255. }
  256. $tokens = \Drupal::token()->scan($value);
  257. $title = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
  258. // Validate if an element must have a minimum number of tokens.
  259. if (isset($element['#min_tokens']) && count($tokens) < $element['#min_tokens']) {
  260. $error = \Drupal::translation()->formatPlural($element['#min_tokens'], '%name must contain at least one token.', '%name must contain at least @count tokens.', ['%name' => $title]);
  261. $form_state->setError($element, $error);
  262. }
  263. // Validate if an element must have a maximum number of tokens.
  264. if (isset($element['#max_tokens']) && count($tokens) > $element['#max_tokens']) {
  265. $error = \Drupal::translation()->formatPlural($element['#max_tokens'], '%name must contain at most one token.', '%name must contain at most @count tokens.', ['%name' => $title]);
  266. $form_state->setError($element, $error);
  267. }
  268. // Check if the field defines specific token types.
  269. if (isset($element['#token_types'])) {
  270. $invalid_tokens = \Drupal::token()->getInvalidTokensByContext($tokens, $element['#token_types']);
  271. if ($invalid_tokens) {
  272. $form_state->setError($element, t('%name is using the following invalid tokens: @invalid-tokens.', ['%name' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens)]));
  273. }
  274. }
  275. return $element;
  276. }
  277. /**
  278. * Implements hook_form_FORM_ID_alter().
  279. */
  280. function token_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state) {
  281. $field_config = $form_state->getFormObject()->getEntity();
  282. $field_storage = $field_config->getFieldStorageDefinition();
  283. if ($field_storage->isLocked()) {
  284. return;
  285. }
  286. $field_type = $field_storage->getType();
  287. if (($field_type == 'file' || $field_type == 'image') && isset($form['settings']['file_directory'])) {
  288. // GAH! We can only support global tokens in the upload file directory path.
  289. $form['settings']['file_directory']['#element_validate'][] = 'token_element_validate';
  290. // Date support needs to be implicitly added, as while technically it's not
  291. // a global token, it is a not only used but is the default value.
  292. // https://www.drupal.org/node/2642160
  293. $form['settings']['file_directory'] += ['#token_types' => ['date']];
  294. $form['settings']['file_directory']['#description'] .= ' ' . t('This field supports tokens.');
  295. }
  296. // Note that the description is tokenized via token_field_widget_form_alter().
  297. $form['description']['#element_validate'][] = 'token_element_validate';
  298. $form['description'] += ['#token_types' => []];
  299. $form['token_tree'] = [
  300. '#theme' => 'token_tree_link',
  301. '#token_types' => [],
  302. '#weight' => $form['description']['#weight'] + 0.5,
  303. ];
  304. }
  305. /**
  306. * Implements hook_form_BASE_FORM_ID_alter().
  307. *
  308. * Alters the configure action form to add token context validation and
  309. * adds the token tree for a better token UI and selection.
  310. */
  311. function token_form_action_form_alter(&$form, $form_state) {
  312. if (isset($form['plugin'])) {
  313. switch ($form['plugin']['#value']) {
  314. case 'action_message_action':
  315. case 'action_send_email_action':
  316. case 'action_goto_action':
  317. $form['token_tree'] = [
  318. '#theme' => 'token_tree_link',
  319. '#token_types' => 'all',
  320. '#weight' => 100,
  321. ];
  322. $form['actions']['#weight'] = 101;
  323. // @todo Add token validation to the action fields that can use tokens.
  324. break;
  325. }
  326. }
  327. }
  328. /**
  329. * Implements hook_form_FORM_ID_alter().
  330. *
  331. * Alters the user e-mail fields to add token context validation and
  332. * adds the token tree for a better token UI and selection.
  333. */
  334. function token_form_user_admin_settings_alter(&$form, FormStateInterface $form_state) {
  335. $email_token_help = t('Available variables are: [site:name], [site:url], [user:display-name], [user:account-name], [user:mail], [site:login-url], [site:url-brief], [user:edit-url], [user:one-time-login-url], [user:cancel-url].');
  336. foreach (Element::children($form) as $key) {
  337. $element = &$form[$key];
  338. // Remove the crummy default token help text.
  339. if (!empty($element['#description'])) {
  340. $element['#description'] = trim(str_replace($email_token_help, t('The list of available tokens that can be used in e-mails is provided below.'), $element['#description']));
  341. }
  342. switch ($key) {
  343. case 'email_admin_created':
  344. case 'email_pending_approval':
  345. case 'email_no_approval_required':
  346. case 'email_password_reset':
  347. case 'email_cancel_confirm':
  348. // Do nothing, but allow execution to continue.
  349. break;
  350. case 'email_activated':
  351. case 'email_blocked':
  352. case 'email_canceled':
  353. // These fieldsets have their e-mail elements inside a 'settings'
  354. // sub-element, so switch to that element instead.
  355. $element = &$form[$key]['settings'];
  356. break;
  357. default:
  358. continue 2;
  359. }
  360. foreach (Element::children($element) as $sub_key) {
  361. if (!isset($element[$sub_key]['#type'])) {
  362. continue;
  363. }
  364. elseif ($element[$sub_key]['#type'] == 'textfield' && substr($sub_key, -8) === '_subject') {
  365. // Add validation to subject textfields.
  366. $element[$sub_key]['#element_validate'][] = 'token_element_validate';
  367. $element[$sub_key] += ['#token_types' => ['user']];
  368. }
  369. elseif ($element[$sub_key]['#type'] == 'textarea' && substr($sub_key, -5) === '_body') {
  370. // Add validation to body textareas.
  371. $element[$sub_key]['#element_validate'][] = 'token_element_validate';
  372. $element[$sub_key] += ['#token_types' => ['user']];
  373. }
  374. }
  375. }
  376. // Add the token tree UI.
  377. $form['email']['token_tree'] = [
  378. '#theme' => 'token_tree_link',
  379. '#token_types' => ['user'],
  380. '#show_restricted' => TRUE,
  381. '#show_nested' => FALSE,
  382. '#weight' => 90,
  383. ];
  384. }
  385. /**
  386. * Prepare a string for use as a valid token name.
  387. *
  388. * @param $name
  389. * The token name to clean.
  390. * @return
  391. * The cleaned token name.
  392. */
  393. function token_clean_token_name($name) {
  394. static $names = [];
  395. if (!isset($names[$name])) {
  396. $cleaned_name = strtr($name, [' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '']);
  397. $cleaned_name = preg_replace('/[^\w\-]/i', '', $cleaned_name);
  398. $cleaned_name = trim($cleaned_name, '-');
  399. $names[$name] = $cleaned_name;
  400. }
  401. return $names[$name];
  402. }
  403. /**
  404. * Do not use this function yet. Its API has not been finalized.
  405. */
  406. function token_render_array(array $array, array $options = []) {
  407. $rendered = [];
  408. /** @var \Drupal\Core\Render\RendererInterface $renderer */
  409. $renderer = \Drupal::service('renderer');
  410. foreach (token_element_children($array) as $key) {
  411. $value = $array[$key];
  412. $rendered[] = is_array($value) ? $renderer->renderPlain($value) : (string) $value;
  413. }
  414. $join = isset($options['join']) ? $options['join'] : ', ';
  415. return implode($join, $rendered);
  416. }
  417. /**
  418. * Do not use this function yet. Its API has not been finalized.
  419. */
  420. function token_render_array_value($value, array $options = []) {
  421. /** @var \Drupal\Core\Render\RendererInterface $renderer */
  422. $renderer = \Drupal::service('renderer');
  423. $rendered = is_array($value) ? $renderer->renderPlain($value) : (string) $value;
  424. return $rendered;
  425. }
  426. /**
  427. * Copy of drupal_render_cache_get() that does not care about request method.
  428. */
  429. function token_render_cache_get($elements) {
  430. if (!$cid = drupal_render_cid_create($elements)) {
  431. return FALSE;
  432. }
  433. $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'render';
  434. if (!empty($cid) && $cache = \Drupal::cache($bin)->get($cid)) {
  435. // Add additional libraries, JavaScript, CSS and other data attached
  436. // to this element.
  437. if (isset($cache->data['#attached'])) {
  438. drupal_process_attached($cache->data);
  439. }
  440. // Return the rendered output.
  441. return $cache->data['#markup'];
  442. }
  443. return FALSE;
  444. }
  445. /**
  446. * Coyp of drupal_render_cache_set() that does not care about request method.
  447. */
  448. function token_render_cache_set(&$markup, $elements) {
  449. // This should only run of drupal_render_cache_set() did not.
  450. if (in_array(\Drupal::request()->server->get('REQUEST_METHOD'), ['GET', 'HEAD'])) {
  451. return FALSE;
  452. }
  453. $original_method = \Drupal::request()->server->get('REQUEST_METHOD');
  454. \Drupal::request()->server->set('REQUEST_METHOD', 'GET');
  455. drupal_render_cache_set($markup, $elements);
  456. \Drupal::request()->server->set('REQUEST_METHOD', $original_method);
  457. }
  458. /**
  459. * Loads menu link titles for all purents of a menu link plugin ID.
  460. *
  461. * @param string $plugin_id
  462. * The menu link plugin ID.
  463. * @param string $langcode
  464. * The language code.
  465. *
  466. * @return string[]
  467. * List of menu link parent titles.
  468. */
  469. function token_menu_link_load_all_parents($plugin_id, $langcode) {
  470. $cache = &drupal_static(__FUNCTION__, []);
  471. if (!isset($cache[$plugin_id][$langcode])) {
  472. $cache[$plugin_id][$langcode] = [];
  473. /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  474. $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  475. $parent_ids = $menu_link_manager->getParentIds($plugin_id);
  476. // Remove the current plugin ID from the parents.
  477. unset($parent_ids[$plugin_id]);
  478. foreach ($parent_ids as $parent_id) {
  479. $parent = $menu_link_manager->createInstance($parent_id);
  480. $cache[$plugin_id][$langcode] = [$parent_id => token_menu_link_translated_title($parent, $langcode)] + $cache[$plugin_id][$langcode];
  481. }
  482. }
  483. return $cache[$plugin_id][$langcode];
  484. }
  485. /**
  486. * Returns the translated link of a menu title.
  487. *
  488. * If the underlying entity is a content menu item, load it to get the
  489. * translated menu item title.
  490. *
  491. * @todo Remove this when there is a better way to get a translated menu
  492. * item title in core: https://www.drupal.org/node/2795143
  493. *
  494. * @param \Drupal\Core\Menu\MenuLinkInterface $menu_link
  495. * The menu link.
  496. * @param string|null $langcode
  497. * (optional) The langcode, defaults to the current language.
  498. *
  499. * @return string
  500. * The menu link title.
  501. */
  502. function token_menu_link_translated_title(MenuLinkInterface $menu_link, $langcode = NULL) {
  503. $metadata = $menu_link->getMetaData();
  504. if (isset($metadata['entity_id']) && $menu_link->getProvider() == 'menu_link_content') {
  505. /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
  506. $entity = \Drupal::entityTypeManager()->getStorage('menu_link_content')->load($metadata['entity_id']);
  507. $entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity, $langcode);
  508. return $entity->getTitle();
  509. }
  510. return $menu_link->getTitle();
  511. }
  512. /**
  513. * Loads all the parents of the term in the specified language.
  514. *
  515. * @param int $tid
  516. * The term id.
  517. * @param string $langcode
  518. * The language code.
  519. *
  520. * @return string[]
  521. * The term parents collection.
  522. */
  523. function token_taxonomy_term_load_all_parents($tid, $langcode) {
  524. $cache = &drupal_static(__FUNCTION__, []);
  525. if (!is_numeric($tid)) {
  526. return [];
  527. }
  528. if (!isset($cache[$langcode][$tid])) {
  529. $cache[$langcode][$tid] = [];
  530. /** @var \Drupal\taxonomy\TermStorageInterface $term_storage */
  531. $term_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
  532. $parents = $term_storage->loadAllParents($tid);
  533. // Remove this term from the array.
  534. array_shift($parents);
  535. $parents = array_reverse($parents);
  536. foreach ($parents as $term) {
  537. $translation = \Drupal::service('entity.repository')->getTranslationFromContext($term, $langcode);
  538. $cache[$langcode][$tid][$term->id()] = $translation->label();
  539. }
  540. }
  541. return $cache[$langcode][$tid];
  542. }
  543. function token_element_children(&$elements, $sort = FALSE) {
  544. // Do not attempt to sort elements which have already been sorted.
  545. $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
  546. // Filter out properties from the element, leaving only children.
  547. $children = [];
  548. $sortable = FALSE;
  549. foreach ($elements as $key => $value) {
  550. if ($key === '' || $key[0] !== '#') {
  551. $children[$key] = $value;
  552. if (is_array($value) && isset($value['#weight'])) {
  553. $sortable = TRUE;
  554. }
  555. }
  556. }
  557. // Sort the children if necessary.
  558. if ($sort && $sortable) {
  559. uasort($children, 'Drupal\Component\Utility\SortArray::sortByWeightProperty');
  560. // Put the sorted children back into $elements in the correct order, to
  561. // preserve sorting if the same element is passed through
  562. // element_children() twice.
  563. foreach ($children as $key => $child) {
  564. unset($elements[$key]);
  565. $elements[$key] = $child;
  566. }
  567. $elements['#sorted'] = TRUE;
  568. }
  569. return array_keys($children);
  570. }
  571. /**
  572. * Loads all the parents of the book page.
  573. *
  574. * @param array $book
  575. * The book data. The 'nid' key points to the current page of the book.
  576. * The 'p1' ... 'p9' keys point to parents of the page, if they exist, with 'p1'
  577. * pointing to the book itself and the last defined pX to the current page.
  578. *
  579. * @return string[]
  580. * List of node titles of the book parents.
  581. */
  582. function token_book_load_all_parents(array $book) {
  583. $cache = &drupal_static(__FUNCTION__, []);
  584. if (empty($book['nid'])) {
  585. return [];
  586. }
  587. $nid = $book['nid'];
  588. if (!isset($cache[$nid])) {
  589. $cache[$nid] = [];
  590. $i = 1;
  591. while ($book["p$i"] != $nid) {
  592. $cache[$nid][] = Node::load($book["p$i"])->getTitle();
  593. $i++;
  594. }
  595. }
  596. return $cache[$nid];
  597. }
  598. /**
  599. * Implements hook_entity_base_field_info().
  600. */
  601. function token_entity_base_field_info(EntityTypeInterface $entity_type) {
  602. // We add a pseudo entity-reference field to track the menu entry created
  603. // from the node add/edit form so that tokens generated at that time that
  604. // reference the menu link can access the yet to be saved menu link.
  605. // @todo Revisit when https://www.drupal.org/node/2315773 is resolved.
  606. if ($entity_type->id() === 'node' && \Drupal::moduleHandler()->moduleExists('menu_ui')) {
  607. $fields['menu_link'] = BaseFieldDefinition::create('entity_reference')
  608. ->setLabel(t('Menu link'))
  609. ->setDescription(t('Computed menu link for the node (only available during node saving).'))
  610. ->setRevisionable(TRUE)
  611. ->setSetting('target_type', 'menu_link_content')
  612. ->setTranslatable(TRUE)
  613. ->setDisplayOptions('view', [
  614. 'label' => 'hidden',
  615. 'region' => 'hidden',
  616. ])
  617. ->setComputed(TRUE)
  618. ->setDisplayOptions('form', [
  619. 'region' => 'hidden',
  620. ]);
  621. return $fields;
  622. }
  623. return [];
  624. }
  625. /**
  626. * Implements hook_form_BASE_FORM_ID_alter() for node_form.
  627. *
  628. * Populates menu_link field on nodes from the menu item on unsaved nodes.
  629. *
  630. * @see menu_ui_form_node_form_submit()
  631. * @see token_entity_base_field_info()
  632. */
  633. function token_form_node_form_alter(&$form, FormStateInterface $form_state) {
  634. if (!\Drupal::moduleHandler()->moduleExists('menu_ui')) {
  635. return;
  636. }
  637. /** @var \Drupal\node\NodeForm $form_object */
  638. if (!\Drupal::currentUser()->hasPermission('administer menu')) {
  639. // We're only interested in when the node is unsaved and the editor has
  640. // permission to create new menu links.
  641. return;
  642. }
  643. $form['#entity_builders'][] = 'token_node_menu_link_submit';
  644. }
  645. /**
  646. * Entity builder.
  647. */
  648. function token_node_menu_link_submit($entity_type, NodeInterface $node, &$form, FormStateInterface $form_state) {
  649. // Entity builders run twice, once during validation and again during
  650. // submission, so we only run this code after validation has been performed.
  651. if (!$form_state->isValueEmpty('menu') && $form_state->getTemporaryValue('entity_validated')) {
  652. $values = $form_state->getValue('menu');
  653. if (!empty($values['enabled']) && trim($values['title'])) {
  654. if (!empty($values['menu_parent'])) {
  655. list($menu_name, $parent) = explode(':', $values['menu_parent'], 2);
  656. $values['menu_name'] = $menu_name;
  657. $values['parent'] = $parent;
  658. }
  659. // Construct an unsaved entity.
  660. if ($entity_id = $form_state->getValue(['menu', 'entity_id'])) {
  661. // Use the existing menu_link_content entity.
  662. $entity = MenuLinkContent::load($entity_id);
  663. // If the loaded MenuLinkContent doesn't have a translation for the
  664. // Node's active langcode, create a new translation.
  665. if ($entity->isTranslatable()) {
  666. if (!$entity->hasTranslation($node->language()->getId())) {
  667. $entity = $entity->addTranslation($node->language()->getId(), $entity->toArray());
  668. }
  669. else {
  670. $entity = $entity->getTranslation($node->language()->getId());
  671. }
  672. }
  673. }
  674. else {
  675. if ($node->isNew()) {
  676. // Create a new menu_link_content entity.
  677. $entity = MenuLinkContent::create([
  678. // Lets just reference the UUID for now, the link is not important for
  679. // token generation.
  680. 'link' => ['uri' => 'internal:/node/' . $node->uuid()],
  681. 'langcode' => $node->language()->getId(),
  682. ]);
  683. }
  684. else {
  685. // Create a new menu_link_content entity.
  686. $entity = MenuLinkContent::create([
  687. 'link' => ['uri' => 'entity:node/' . $node->id()],
  688. 'langcode' => $node->language()->getId(),
  689. ]);
  690. }
  691. }
  692. $entity->title->value = trim($values['title']);
  693. $entity->description->value = trim($values['description']);
  694. $entity->menu_name->value = $values['menu_name'];
  695. $entity->parent->value = $values['parent'];
  696. $entity->weight->value = isset($values['weight']) ? $values['weight'] : 0;
  697. $entity->save();
  698. $node->menu_link = $entity;
  699. // Leave this for _menu_ui_node_save() to pick up so we don't end up with
  700. // duplicate menu-links.
  701. $form_state->setValue(['menu', 'entity_id'], $entity->id());
  702. }
  703. }
  704. }
  705. /**
  706. * Implements hook_ENTITY_TYPE_insert for node entities.
  707. */
  708. function token_node_insert(NodeInterface $node) {
  709. if ($node->hasField('menu_link') && $menu_link = $node->menu_link->entity) {
  710. // Update the menu-link to point to the now saved node.
  711. $menu_link->link = 'entity:node/' . $node->id();
  712. $menu_link->save();
  713. }
  714. }
  715. /**
  716. * Implements hook_ENTITY_TYPE_presave() for menu_link_content.
  717. */
  718. function token_menu_link_content_presave(MenuLinkContentInterface $menu_link_content) {
  719. drupal_static_reset('token_menu_link_load_all_parents');
  720. }