token.module 27 KB

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