token.module 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. <?php
  2. /**
  3. * @file
  4. * Enhances the token API in core: adds a browseable UI, missing tokens, etc.
  5. */
  6. /**
  7. * The maximum depth for token tree recursion.
  8. */
  9. define('TOKEN_MAX_DEPTH', 9);
  10. /**
  11. * Implements hook_help().
  12. */
  13. function token_help($path, $arg) {
  14. if ($path == 'admin/help#token') {
  15. if (current_path() != 'admin/help/token') {
  16. // Because system_modules() executes hook_help() for each module to 'test'
  17. // if they will return anything, but not actually display it, we want to
  18. // return a TRUE value if this is not actually the help page.
  19. return TRUE;
  20. }
  21. $output = '<dl>';
  22. $output .= '<dt>' . t('List of the currently available tokens on this site') . '</dt>';
  23. $output .= '<dd>' . theme('token_tree', array('token_types' => 'all', 'click_insert' => FALSE, 'show_restricted' => TRUE)) . '</dd>';
  24. $output .= '</dl>';
  25. return $output;
  26. }
  27. }
  28. /**
  29. * Implements hook_system_info_alter().
  30. *
  31. * Prevent the token_actions module from being enabled since updates may have
  32. * left the old module files still in the directory.
  33. */
  34. function token_system_info_alter(&$info, $file, $type) {
  35. if ($type == 'module' && $file->name == 'token_actions') {
  36. $info['hidden'] = TRUE;
  37. }
  38. }
  39. /**
  40. * Return an array of the core modules supported by token.module.
  41. */
  42. function _token_core_supported_modules() {
  43. return array('book', 'field', 'menu', 'profile');
  44. }
  45. /**
  46. * Implements hook_menu().
  47. */
  48. function token_menu() {
  49. /*$items['token/autocomplete/all/%menu_tail'] = array(
  50. 'page callback' => 'token_autocomplete',
  51. 'access callback' => TRUE,
  52. 'type' => MENU_CALLBACK,
  53. 'file' => 'token.pages.inc',
  54. );*/
  55. $items['token/autocomplete/%token_type'] = array(
  56. 'page callback' => 'token_autocomplete_token',
  57. 'page arguments' => array(2),
  58. 'access callback' => TRUE,
  59. 'type' => MENU_CALLBACK,
  60. 'file' => 'token.pages.inc',
  61. );
  62. /*$items['token/autocomplete/%token_type/%menu_tail'] = array(
  63. 'page callback' => 'token_autocomplete_token',
  64. 'page arguments' => array(2, 3),
  65. 'access callback' => TRUE,
  66. 'type' => MENU_CALLBACK,
  67. 'file' => 'token.pages.inc',
  68. );*/
  69. $items['token/tree'] = array(
  70. 'page callback' => 'token_page_output_tree',
  71. 'access callback' => TRUE,
  72. 'type' => MENU_CALLBACK,
  73. 'file' => 'token.pages.inc',
  74. );
  75. // Devel token pages.
  76. if (module_exists('devel')) {
  77. $items['node/%node/devel/token'] = array(
  78. 'title' => 'Tokens',
  79. 'page callback' => 'token_devel_token_object',
  80. 'page arguments' => array('node', 1),
  81. 'access arguments' => array('access devel information'),
  82. 'type' => MENU_LOCAL_TASK,
  83. 'file' => 'token.pages.inc',
  84. 'weight' => 5,
  85. );
  86. $items['comment/%comment/devel/token'] = array(
  87. 'title' => 'Tokens',
  88. 'page callback' => 'token_devel_token_object',
  89. 'page arguments' => array('comment', 1),
  90. 'access arguments' => array('access devel information'),
  91. 'type' => MENU_LOCAL_TASK,
  92. 'file' => 'token.pages.inc',
  93. 'weight' => 5,
  94. );
  95. $items['taxonomy/term/%taxonomy_term/devel/token'] = array(
  96. 'title' => 'Tokens',
  97. 'page callback' => 'token_devel_token_object',
  98. 'page arguments' => array('taxonomy_term', 2),
  99. 'access arguments' => array('access devel information'),
  100. 'type' => MENU_LOCAL_TASK,
  101. 'file' => 'token.pages.inc',
  102. 'weight' => 5,
  103. );
  104. $items['user/%user/devel/token'] = array(
  105. 'title' => 'Tokens',
  106. 'page callback' => 'token_devel_token_object',
  107. 'page arguments' => array('user', 1),
  108. 'access arguments' => array('access devel information'),
  109. 'type' => MENU_LOCAL_TASK,
  110. 'file' => 'token.pages.inc',
  111. 'weight' => 5,
  112. );
  113. }
  114. // Admin menu callback to clear token caches.
  115. $items['token/flush-cache'] = array(
  116. 'page callback' => 'token_flush_cache_callback',
  117. 'access arguments' => array('flush caches'),
  118. 'type' => MENU_CALLBACK,
  119. 'file' => 'token.pages.inc',
  120. );
  121. return $items;
  122. }
  123. /**
  124. * Implements hook_admin_menu_output_alter().
  125. */
  126. function token_admin_menu_output_alter(&$content) {
  127. $content['icon']['icon']['flush-cache']['token'] = array(
  128. '#title' => t('Token registry'),
  129. '#href' => 'token/flush-cache',
  130. '#options' => array(
  131. 'query' => drupal_get_destination() + array('token' => drupal_get_token('token/flush-cache')),
  132. ),
  133. );
  134. }
  135. function token_type_load($token_type) {
  136. $info = token_get_info();
  137. return isset($info['types'][$token_type]) ? $info['types'][$token_type] : FALSE;
  138. }
  139. /**
  140. * Implements hook_theme().
  141. */
  142. function token_theme() {
  143. $info['tree_table'] = array(
  144. 'variables' => array(
  145. 'header' => array(),
  146. 'rows' => array(),
  147. 'attributes' => array(),
  148. 'empty' => '',
  149. 'caption' => '',
  150. ),
  151. 'file' => 'token.pages.inc',
  152. );
  153. $info['token_tree'] = array(
  154. 'variables' => array(
  155. 'token_types' => array(),
  156. 'global_types' => TRUE,
  157. 'click_insert' => TRUE,
  158. 'show_restricted' => FALSE,
  159. 'recursion_limit' => 3,
  160. 'dialog' => FALSE,
  161. ),
  162. 'file' => 'token.pages.inc',
  163. );
  164. $info['token_tree_link'] = array(
  165. 'variables' => array(
  166. 'text' => NULL,
  167. 'options' => array(),
  168. 'dialog' => TRUE,
  169. ),
  170. 'file' => 'token.pages.inc',
  171. );
  172. return $info;
  173. }
  174. /**
  175. * Implements hook_library().
  176. */
  177. function token_library() {
  178. // jQuery treeTable plugin.
  179. $libraries['treeTable'] = array(
  180. 'title' => 'jQuery treeTable',
  181. 'website' => 'http://plugins.jquery.com/project/treetable',
  182. 'version' => '2.3.0',
  183. 'js' => array(
  184. drupal_get_path('module', 'token') . '/jquery.treeTable.js' => array(),
  185. ),
  186. 'css' => array(
  187. drupal_get_path('module', 'token') . '/jquery.treeTable.css' => array(),
  188. ),
  189. );
  190. $libraries['dialog'] = array(
  191. 'title' => 'Token dialog',
  192. 'version' => '1.0',
  193. 'js' => array(
  194. drupal_get_path('module', 'token') . '/token.js' => array(),
  195. ),
  196. 'dependencies' => array(
  197. array('system', 'ui.dialog'),
  198. ),
  199. );
  200. return $libraries;
  201. }
  202. /**
  203. * Implements hook_form_alter().
  204. *
  205. * Adds a submit handler to forms which could affect the tokens available on
  206. * the site.
  207. */
  208. function token_form_alter(&$form, $form_state, $form_id) {
  209. switch ($form_id) {
  210. // Profile field forms.
  211. case 'profile_field_form':
  212. case 'profile_field_delete':
  213. // User picture form.
  214. case 'user_admin_settings':
  215. // System date type form.
  216. // @todo Remove when http://drupal.org/node/1173706 is fixed.
  217. case 'system_add_date_format_type_form':
  218. case 'system_delete_date_format_type_form':
  219. $form += array('#submit' => array());
  220. array_unshift($form['#submit'], 'token_clear_cache');
  221. break;
  222. }
  223. }
  224. /**
  225. * Implements hook_block_view_alter().
  226. */
  227. function token_block_view_alter(&$data, $block) {
  228. if (!empty($block->title) && $block->title != '<none>') {
  229. // Perform unsanitized token replacement since _block_render_blocks() will
  230. // call check_plain() on $block->title.
  231. $block->title = token_replace($block->title, array(), array('sanitize' => FALSE));
  232. }
  233. }
  234. /**
  235. * Implements hook_form_FORM_ID_alter().
  236. */
  237. function token_form_block_add_block_form_alter(&$form, $form_state) {
  238. token_form_block_admin_configure_alter($form, $form_state);
  239. }
  240. /**
  241. * Implements hook_form_FORM_ID_alter().
  242. */
  243. function token_form_block_admin_configure_alter(&$form, $form_state) {
  244. $form['settings']['title']['#description'] .= ' ' . t('This field supports tokens.');
  245. // @todo Figure out why this token validation does not seem to be working here.
  246. $form['settings']['title']['#element_validate'][] = 'token_element_validate';
  247. $form['settings']['title']['#token_types'] = array();
  248. }
  249. /**
  250. * Implements hook_widget_form_alter().
  251. */
  252. function token_field_widget_form_alter(&$element, &$form_state, $context) {
  253. if (!empty($element['#description']) && is_string($element['#description'])) {
  254. $element['#description'] = filter_xss_admin(token_replace($element['#description']));
  255. }
  256. }
  257. /**
  258. * Implements hook_field_info_alter().
  259. */
  260. function token_field_info_alter(&$info) {
  261. $defaults = array(
  262. 'taxonomy_term_reference' => 'taxonomy_term_reference_plain',
  263. 'number_integer' => 'number_unformatted',
  264. 'number_decimal' => 'number_unformatted',
  265. 'number_float' => 'number_unformatted',
  266. 'file' => 'file_url_plain',
  267. 'image' => 'file_url_plain',
  268. 'text' => 'text_default',
  269. 'text_long' => 'text_default',
  270. 'text_with_summary' => 'text_default',
  271. 'list_integer' => 'list_default',
  272. 'list_float' => 'list_default',
  273. 'list_text' => 'list_default',
  274. 'list_boolean' => 'list_default',
  275. );
  276. foreach ($defaults as $field_type => $default_token_formatter) {
  277. if (isset($info[$field_type])) {
  278. $info[$field_type] += array('default_token_formatter' => $default_token_formatter);
  279. }
  280. }
  281. }
  282. /**
  283. * Implements hook_field_display_alter().
  284. */
  285. function token_field_display_alter(&$display, $context) {
  286. if ($context['view_mode'] == 'token') {
  287. $view_mode_settings = field_view_mode_settings($context['instance']['entity_type'], $context['instance']['bundle']);
  288. // If the token view mode fell back to the 'default' view mode, then
  289. // use the default token formatter.
  290. if (empty($view_mode_settings[$context['view_mode']]['custom_settings'])) {
  291. $field_type_info = field_info_field_types($context['field']['type']);
  292. // If the field has specified a specific formatter to be used by default
  293. // with tokens, use that, otherwise use the default formatter.
  294. $formatter = !empty($field_type_info['default_token_formatter']) ? $field_type_info['default_token_formatter'] : $field_type_info['default_formatter'];
  295. // Now that we have a formatter, fill in all the settings.
  296. $display['type'] = $formatter;
  297. $formatter_info = field_info_formatter_types($formatter);
  298. $display['settings'] = isset($formatter_info['settings']) ? $formatter_info['settings'] : array();
  299. $display['settings']['label'] = 'hidden';
  300. $display['module'] = $formatter_info['module'];
  301. }
  302. }
  303. }
  304. /**
  305. * Implements hook_field_create_instance().
  306. */
  307. function token_field_create_instance($instance) {
  308. token_clear_cache();
  309. }
  310. /**
  311. * Implements hook_field_update_instance().
  312. */
  313. function token_field_update_instance($instance) {
  314. token_clear_cache();
  315. }
  316. /**
  317. * Implements hook_field_delete_instance().
  318. */
  319. function token_field_delete_instance($instance) {
  320. token_clear_cache();
  321. }
  322. /**
  323. * Clear token caches and static variables.
  324. */
  325. function token_clear_cache() {
  326. if (db_table_exists('cache_token')) {
  327. cache_clear_all('*', 'cache_token', TRUE);
  328. }
  329. drupal_static_reset('token_get_info');
  330. drupal_static_reset('token_get_global_token_types');
  331. drupal_static_reset('token_get_entity_mapping');
  332. drupal_static_reset('token_build_tree');
  333. drupal_static_reset('_token_profile_fields');
  334. drupal_static_reset('token_menu_link_load');
  335. drupal_static_reset('token_book_link_load');
  336. drupal_static_reset('token_node_menu_link_load');
  337. drupal_static_reset('_token_field_info');
  338. }
  339. /**
  340. * Return an array of entity type to token type mappings.
  341. *
  342. * Why do we need this? Because when the token API was moved to core we did not
  343. * re-use the entity type as the base name for taxonomy terms and vocabulary
  344. * tokens.
  345. *
  346. * @see token_entity_info_alter()
  347. * @see http://drupal.org/node/737726
  348. */
  349. function token_get_entity_mapping($value_type = 'token', $value = NULL, $fallback = FALSE) {
  350. $mapping = &drupal_static(__FUNCTION__, array());
  351. if (empty($mapping)) {
  352. foreach (entity_get_info() as $entity_type => $info) {
  353. $mapping[$entity_type] = !empty($info['token type']) ? $info['token type'] : $entity_type;
  354. }
  355. // Allow modules to alter the mapping array.
  356. drupal_alter('token_entity_mapping', $mapping);
  357. }
  358. if (!isset($value)) {
  359. return $mapping;
  360. }
  361. elseif ($value_type == 'token') {
  362. $return = array_search($value, $mapping);
  363. return $return !== FALSE ? $return : ($fallback ? $value : FALSE);
  364. }
  365. elseif ($value_type == 'entity') {
  366. return isset($mapping[$value]) ? $mapping[$value] : ($fallback ? $value : FALSE);
  367. }
  368. }
  369. /**
  370. * Implements hook_entity_info_alter().
  371. *
  372. * Because some token types to do not match their entity type names, we have to
  373. * map them to the proper type. This is purely for other modules' benefit.
  374. *
  375. * @see token_get_entity_mapping()
  376. * @see http://drupal.org/node/737726
  377. */
  378. function token_entity_info_alter(&$info) {
  379. foreach (array_keys($info) as $entity_type) {
  380. // Add a token view mode if it does not already exist.
  381. if (!empty($info[$entity_type]['view modes']) && !isset($info[$entity_type]['view modes']['token'])) {
  382. $info[$entity_type]['view modes']['token'] = array(
  383. 'label' => t('Tokens'),
  384. 'custom settings' => FALSE,
  385. );
  386. }
  387. if (!empty($info[$entity_type]['token type'])) {
  388. // If the entity's token type is already defined, great!
  389. continue;
  390. }
  391. // Fill in default token types for entities.
  392. switch ($entity_type) {
  393. case 'taxonomy_term':
  394. case 'taxonomy_vocabulary':
  395. // Stupid taxonomy token types...
  396. $info[$entity_type]['token type'] = str_replace('taxonomy_', '', $entity_type);
  397. break;
  398. default:
  399. // By default the token type is the same as the entity type.
  400. $info[$entity_type]['token type'] = $entity_type;
  401. break;
  402. }
  403. }
  404. }
  405. /**
  406. * Implements hook_module_implements_alter().
  407. *
  408. * Adds missing token support for core modules.
  409. */
  410. function token_module_implements_alter(&$implementations, $hook) {
  411. module_load_include('inc', 'token', 'token.tokens');
  412. if ($hook == 'tokens' || $hook == 'token_info' || $hook == 'token_info_alter' || $hook == 'tokens_alter') {
  413. foreach (_token_core_supported_modules() as $module) {
  414. if (module_exists($module) && function_exists($module . '_' . $hook)) {
  415. $implementations[$module] = FALSE;
  416. }
  417. }
  418. // Move token.module to get included first since it is responsible for
  419. // other modules.
  420. unset($implementations['token']);
  421. $implementations = array_merge(array('token' => 'tokens'), $implementations);
  422. }
  423. }
  424. /**
  425. * Implements hook_flush_caches().
  426. */
  427. function token_flush_caches() {
  428. if (db_table_exists('cache_token')) {
  429. return array('cache_token');
  430. }
  431. }
  432. /**
  433. * Retrieve, sort, store token info from the cache.
  434. *
  435. * @param $token_type
  436. * The optional token type that if specified will return
  437. * $info['types'][$token_type].
  438. * @param $token
  439. * The optional token name if specified will return
  440. * $info['tokens'][$token_type][$token].
  441. *
  442. * @return
  443. * An array of all token information from hook_token_info(), or the array
  444. * of a token type or specific token.
  445. *
  446. * @see hook_token_info()
  447. * @see hook_token_info_alter()
  448. */
  449. function token_get_info($token_type = NULL, $token = NULL) {
  450. global $language;
  451. // Use the advanced drupal_static() pattern, since this is called very often.
  452. static $drupal_static_fast;
  453. if (!isset($drupal_static_fast)) {
  454. $drupal_static_fast['token_info'] = &drupal_static(__FUNCTION__);
  455. }
  456. $token_info = &$drupal_static_fast['token_info'];
  457. if (empty($token_info)) {
  458. $cid = "info:{$language->language}";
  459. if ($cache = cache_get($cid, 'cache_token')) {
  460. $token_info = $cache->data;
  461. }
  462. else {
  463. $token_info = token_info();
  464. foreach (array_keys($token_info['types']) as $type_key) {
  465. if (isset($token_info['types'][$type_key]['type'])) {
  466. $base_type = $token_info['types'][$type_key]['type'];
  467. // If this token type extends another token type, then merge in
  468. // the base token type's tokens.
  469. if (isset($token_info['tokens'][$base_type])) {
  470. $token_info['tokens'] += array($type_key => array());
  471. $token_info['tokens'][$type_key] += $token_info['tokens'][$base_type];
  472. }
  473. }
  474. else {
  475. // Add a 'type' value to each token type so we can properly use
  476. // token_type_load().
  477. $token_info['types'][$type_key]['type'] = $type_key;
  478. }
  479. }
  480. // Pre-sort tokens.
  481. uasort($token_info['types'], 'token_asort_tokens');
  482. foreach (array_keys($token_info['tokens']) as $type) {
  483. uasort($token_info['tokens'][$type], 'token_asort_tokens');
  484. }
  485. // Store info in cache for future use.
  486. cache_set($cid, $token_info, 'cache_token');
  487. }
  488. }
  489. if (isset($token_type) && isset($token)) {
  490. return isset($token_info['tokens'][$token_type][$token]) ? $token_info['tokens'][$token_type][$token] : NULL;
  491. }
  492. elseif (isset($token_type)) {
  493. return isset($token_info['types'][$token_type]) ? $token_info['types'][$token_type] : NULL;
  494. }
  495. else {
  496. return $token_info;
  497. }
  498. }
  499. /**
  500. * Return the module responsible for a token.
  501. *
  502. * @param string $type
  503. * The token type.
  504. * @param string $name
  505. * The token name.
  506. *
  507. * @return mixed
  508. * The value of $info['tokens'][$type][$name]['module'] from token_get_info(),
  509. * or NULL if the value does not exist.
  510. */
  511. function _token_module($type, $name) {
  512. $token_info = token_get_info($type, $name);
  513. return isset($token_info['module']) ? $token_info['module'] : NULL;
  514. }
  515. /**
  516. * uasort() callback to sort tokens by the 'name' property.
  517. */
  518. function token_asort_tokens($token_a, $token_b) {
  519. return strnatcmp($token_a['name'], $token_b['name']);
  520. }
  521. /**
  522. * Get a list of token types that can be used without any context (global).
  523. *
  524. * @return
  525. * An array of global token types.
  526. */
  527. function token_get_global_token_types() {
  528. $global_types = &drupal_static(__FUNCTION__, array());
  529. if (empty($global_types)) {
  530. $token_info = token_get_info();
  531. foreach ($token_info['types'] as $type => $type_info) {
  532. // If the token types has not specified that 'needs-data' => TRUE, then
  533. // it is a global token type that will always be replaced in any context.
  534. if (empty($type_info['needs-data'])) {
  535. $global_types[] = $type;
  536. }
  537. }
  538. }
  539. return $global_types;
  540. }
  541. /**
  542. * Validate an tokens in raw text based on possible contexts.
  543. *
  544. * @param $value
  545. * A string with the raw text containing the raw tokens, or an array of
  546. * tokens from token_scan().
  547. * @param $tokens
  548. * An array of token types that will be used when token replacement is
  549. * performed.
  550. * @return
  551. * An array with the invalid tokens in their original raw forms.
  552. */
  553. function token_get_invalid_tokens_by_context($value, $valid_types = array()) {
  554. if (in_array('all', $valid_types)) {
  555. $info = token_get_info();
  556. $valid_types = array_keys($info['types']);
  557. }
  558. else {
  559. // Add the token types that are always valid in global context.
  560. $valid_types = array_merge($valid_types, token_get_global_token_types());
  561. }
  562. $invalid_tokens = array();
  563. $value_tokens = is_string($value) ? token_scan($value) : $value;
  564. foreach ($value_tokens as $type => $tokens) {
  565. if (!in_array($type, $valid_types)) {
  566. // If the token type is not a valid context, its tokens are invalid.
  567. $invalid_tokens = array_merge($invalid_tokens, array_values($tokens));
  568. }
  569. else {
  570. // Check each individual token for validity.
  571. $invalid_tokens = array_merge($invalid_tokens, token_get_invalid_tokens($type, $tokens));
  572. }
  573. }
  574. array_unique($invalid_tokens);
  575. return $invalid_tokens;
  576. }
  577. /**
  578. * Validate an array of tokens based on their token type.
  579. *
  580. * @param $type
  581. * The type of tokens to validate (e.g. 'node', etc.)
  582. * @param $tokens
  583. * A keyed array of tokens, and their original raw form in the source text.
  584. * @return
  585. * An array with the invalid tokens in their original raw forms.
  586. */
  587. function token_get_invalid_tokens($type, $tokens) {
  588. $token_info = token_get_info();
  589. $invalid_tokens = array();
  590. foreach ($tokens as $token => $full_token) {
  591. // Split token up if it has chains.
  592. $parts = explode(':', $token, 2);
  593. if (!isset($token_info['tokens'][$type][$parts[0]])) {
  594. // This is an invalid token (not defined).
  595. $invalid_tokens[] = $full_token;
  596. }
  597. elseif (count($parts) == 2) {
  598. $sub_token_info = $token_info['tokens'][$type][$parts[0]];
  599. if (!empty($sub_token_info['dynamic'])) {
  600. // If this token has been flagged as a dynamic token, skip it.
  601. continue;
  602. }
  603. elseif (empty($sub_token_info['type'])) {
  604. // If the token has chains, but does not support it, it is invalid.
  605. $invalid_tokens[] = $full_token;
  606. }
  607. else {
  608. // Resursively check the chained tokens.
  609. $sub_tokens = token_find_with_prefix(array($token => $full_token), $parts[0]);
  610. $invalid_tokens = array_merge($invalid_tokens, token_get_invalid_tokens($sub_token_info['type'], $sub_tokens));
  611. }
  612. }
  613. }
  614. return $invalid_tokens;
  615. }
  616. /**
  617. * Validate a form element that should have tokens in it.
  618. *
  619. * Form elements that want to add this validation should have the #token_types
  620. * parameter defined.
  621. *
  622. * For example:
  623. * @code
  624. * $form['my_node_text_element'] = array(
  625. * '#type' => 'textfield',
  626. * '#title' => t('Some text to token-ize that has a node context.'),
  627. * '#default_value' => 'The title of this node is [node:title].',
  628. * '#element_validate' => array('token_element_validate'),
  629. * '#token_types' => array('node'),
  630. * '#min_tokens' => 1,
  631. * '#max_tokens' => 10,
  632. * );
  633. * @endcode
  634. */
  635. function token_element_validate(&$element, &$form_state) {
  636. $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
  637. if (!drupal_strlen($value)) {
  638. // Empty value needs no further validation since the element should depend
  639. // on using the '#required' FAPI property.
  640. return $element;
  641. }
  642. $tokens = token_scan($value);
  643. $title = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
  644. // @todo Find old Drupal 6 style tokens and add them to invalid tokens.
  645. // Validate if an element must have a minimum number of tokens.
  646. if (isset($element['#min_tokens']) && count($tokens) < $element['#min_tokens']) {
  647. // @todo Change this error message to include the minimum number.
  648. $error = format_plural($element['#min_tokens'], 'The %element-title cannot contain fewer than one token.', 'The %element-title must contain at least @count tokens.', array('%element-title' => $title));
  649. form_error($element, $error);
  650. }
  651. // Validate if an element must have a maximum number of tokens.
  652. if (isset($element['#max_tokens']) && count($tokens) > $element['#max_tokens']) {
  653. // @todo Change this error message to include the maximum number.
  654. $error = format_plural($element['#max_tokens'], 'The %element-title must contain as most one token.', 'The %element-title must contain at most @count tokens.', array('%element-title' => $title));
  655. form_error($element, $error);
  656. }
  657. // Check if the field defines specific token types.
  658. if (isset($element['#token_types'])) {
  659. $invalid_tokens = token_get_invalid_tokens_by_context($tokens, $element['#token_types']);
  660. if ($invalid_tokens) {
  661. form_error($element, t('The %element-title is using the following invalid tokens: @invalid-tokens.', array('%element-title' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens))));
  662. }
  663. }
  664. return $element;
  665. }
  666. /**
  667. * Deprecated. Use token_element_validate() instead.
  668. */
  669. function token_element_validate_token_context(&$element, &$form_state) {
  670. return token_element_validate($element, $form_state);
  671. }
  672. /**
  673. * Implements hook_form_FORM_ID_alter().
  674. */
  675. function token_form_field_ui_field_edit_form_alter(&$form, $form_state) {
  676. if (!isset($form['instance'])) {
  677. return;
  678. }
  679. if (($form['#field']['type'] == 'file' || $form['#field']['type'] == 'image') && isset($form['instance']['settings']['file_directory']) && !module_exists('filefield_paths')) {
  680. // GAH! We can only support global tokens in the upload file directory path.
  681. $form['instance']['settings']['file_directory']['#element_validate'][] = 'token_element_validate';
  682. $form['instance']['settings']['file_directory'] += array('#token_types' => array());
  683. $form['instance']['settings']['file_directory']['#description'] .= ' ' . t('This field supports tokens.');
  684. }
  685. // Note that the description is tokenized via token_field_widget_form_alter().
  686. $form['instance']['description']['#description'] .= '<br />' . t('This field supports tokens.');
  687. $form['instance']['description']['#element_validate'][] = 'token_element_validate';
  688. $form['instance']['description'] += array('#token_types' => array());
  689. $form['instance']['settings']['token_tree'] = array(
  690. '#theme' => 'token_tree',
  691. '#token_types' => array(),
  692. '#dialog' => TRUE,
  693. '#weight' => $form['instance']['description']['#weight'] + 0.5,
  694. );
  695. }
  696. /**
  697. * Implements hook_form_FORM_ID_alter().
  698. *
  699. * Alters the configure action form to add token context validation and
  700. * adds the token tree for a better token UI and selection.
  701. */
  702. function token_form_system_actions_configure_alter(&$form, $form_state) {
  703. $action = actions_function_lookup($form['actions_action']['#value']);
  704. switch ($action) {
  705. case 'system_message_action':
  706. case 'system_send_email_action':
  707. case 'system_goto_action':
  708. $form['token_tree'] = array(
  709. '#theme' => 'token_tree',
  710. '#token_types' => 'all',
  711. '#dialog' => TRUE,
  712. '#weight' => 100,
  713. );
  714. // @todo Add token validation to the action fields that can use tokens.
  715. break;
  716. }
  717. }
  718. /**
  719. * Implements hook_form_FORM_ID_alter().
  720. *
  721. * Alters the user e-mail fields to add token context validation and
  722. * adds the token tree for a better token UI and selection.
  723. */
  724. function token_form_user_admin_settings_alter(&$form, &$form_state) {
  725. $email_token_help = t('Available variables are: [site:name], [site:url], [user:name], [user:mail], [site:login-url], [site:url-brief], [user:edit-url], [user:one-time-login-url], [user:cancel-url].');
  726. foreach (element_children($form) as $key) {
  727. $element = &$form[$key];
  728. // Remove the crummy default token help text.
  729. if (!empty($element['#description'])) {
  730. $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']));
  731. }
  732. switch ($key) {
  733. case 'email_admin_created':
  734. case 'email_pending_approval':
  735. case 'email_no_approval_required':
  736. case 'email_password_reset':
  737. case 'email_cancel_confirm':
  738. // Do nothing, but allow execution to continue.
  739. break;
  740. case 'email_activated':
  741. case 'email_blocked':
  742. case 'email_canceled':
  743. // These fieldsets have their e-mail elements inside a 'settings'
  744. // sub-element, so switch to that element instead.
  745. $element = &$form[$key]['settings'];
  746. break;
  747. default:
  748. continue 2;
  749. }
  750. foreach (element_children($element) as $sub_key) {
  751. if (!isset($element[$sub_key]['#type'])) {
  752. continue;
  753. }
  754. elseif ($element[$sub_key]['#type'] == 'textfield' && substr($sub_key, -8) === '_subject') {
  755. // Add validation to subject textfields.
  756. $element[$sub_key]['#element_validate'][] = 'token_element_validate';
  757. $element[$sub_key] += array('#token_types' => array('user'));
  758. }
  759. elseif ($element[$sub_key]['#type'] == 'textarea' && substr($sub_key, -5) === '_body') {
  760. // Add validation to body textareas.
  761. $element[$sub_key]['#element_validate'][] = 'token_element_validate';
  762. $element[$sub_key] += array('#token_types' => array('user'));
  763. }
  764. }
  765. }
  766. // Add the token tree UI.
  767. $form['email']['token_tree'] = array(
  768. '#theme' => 'token_tree',
  769. '#token_types' => array('user'),
  770. '#show_restricted' => TRUE,
  771. '#dialog' => TRUE,
  772. '#weight' => 90,
  773. );
  774. }
  775. /**
  776. * Build a tree array of tokens used for themeing or information.
  777. *
  778. * @param $token_type
  779. * The token type.
  780. * @param $flat_tree
  781. * A boolean if TRUE will only make a flat array of tokens, otherwise
  782. * child tokens will be inside the 'children' parameter of a token.
  783. * @param $show_restricted
  784. * A boolean if TRUE will show restricted tokens. Otherwise they will be
  785. * hidden. Default is FALSE.
  786. * @param $recursion_limit
  787. * An integer with the maximum number of token levels to recurse.
  788. * @param $parents
  789. * An optional array with the current parents of the tokens.
  790. */
  791. function token_build_tree($token_type, array $options = array()) {
  792. global $language;
  793. // Static cache of already built token trees.
  794. $trees = &drupal_static(__FUNCTION__, array());
  795. $options += array(
  796. 'restricted' => FALSE,
  797. 'depth' => 4,
  798. 'data' => array(),
  799. 'values' => FALSE,
  800. 'flat' => FALSE,
  801. );
  802. // Do not allow past the maximum token information depth.
  803. $options['depth'] = min($options['depth'], TOKEN_MAX_DEPTH);
  804. // If $token_type is an entity, make sure we are using the actual token type.
  805. if ($entity_token_type = token_get_entity_mapping('entity', $token_type)) {
  806. $token_type = $entity_token_type;
  807. }
  808. $tree_cid = "tree:{$token_type}:{$language->language}:{$options['depth']}";
  809. // If we do not have this base tree in the static cache, check {cache_token}
  810. // otherwise generate and store it in the cache.
  811. if (!isset($trees[$tree_cid])) {
  812. if ($cache = cache_get($tree_cid, 'cache_token')) {
  813. $trees[$tree_cid] = $cache->data;
  814. }
  815. else {
  816. $options['parents'] = array();
  817. $trees[$tree_cid] = _token_build_tree($token_type, $options);
  818. cache_set($tree_cid, $trees[$tree_cid], 'cache_token');
  819. }
  820. }
  821. $tree = $trees[$tree_cid];
  822. // If the user has requested a flat tree, convert it.
  823. if (!empty($options['flat'])) {
  824. $tree = token_flatten_tree($tree);
  825. }
  826. // Fill in token values.
  827. if (!empty($options['values'])) {
  828. $token_values = array();
  829. foreach ($tree as $token => $token_info) {
  830. if (!empty($token_info['dynamic']) || !empty($token_info['restricted'])) {
  831. continue;
  832. }
  833. elseif (!isset($token_info['value'])) {
  834. $token_values[$token_info['token']] = $token;
  835. }
  836. }
  837. if (!empty($token_values)) {
  838. $token_values = token_generate($token_type, $token_values, $options['data']);
  839. foreach ($token_values as $token => $replacement) {
  840. $tree[$token]['value'] = $replacement;
  841. }
  842. }
  843. }
  844. return $tree;
  845. }
  846. /**
  847. * Flatten a token tree.
  848. */
  849. function token_flatten_tree($tree) {
  850. $result = array();
  851. foreach ($tree as $token => $token_info) {
  852. $result[$token] = $token_info;
  853. if (isset($token_info['children']) && is_array($token_info['children'])) {
  854. $result += token_flatten_tree($token_info['children']);
  855. // unset($result[$token]['children']);
  856. }
  857. }
  858. return $result;
  859. }
  860. /**
  861. * Generate a token tree.
  862. */
  863. function _token_build_tree($token_type, array $options) {
  864. $options += array(
  865. 'parents' => array(),
  866. );
  867. $info = token_get_info();
  868. if ($options['depth'] <= 0 || !isset($info['types'][$token_type]) || !isset($info['tokens'][$token_type])) {
  869. return array();
  870. }
  871. $tree = array();
  872. foreach ($info['tokens'][$token_type] as $token => $token_info) {
  873. // Build the raw token string.
  874. $token_parents = $options['parents'];
  875. if (empty($token_parents)) {
  876. // If the parents array is currently empty, assume the token type is its
  877. // parent.
  878. $token_parents[] = $token_type;
  879. }
  880. elseif (in_array($token, array_slice($token_parents, 1))) {
  881. // Prevent duplicate recursive tokens. For example, this will prevent
  882. // the tree from generating the following tokens or deeper:
  883. // [comment:parent:parent]
  884. // [comment:parent:root:parent]
  885. continue;
  886. }
  887. $token_parents[] = $token;
  888. if (!empty($token_info['dynamic'])) {
  889. $token_parents[] = '?';
  890. }
  891. $raw_token = '[' . implode(':', $token_parents) . ']';
  892. $tree[$raw_token] = $token_info;
  893. $tree[$raw_token]['raw token'] = $raw_token;
  894. // Add the token's real name (leave out the base token type).
  895. $tree[$raw_token]['token'] = implode(':', array_slice($token_parents, 1));
  896. // Add the token's parent as its raw token value.
  897. if (!empty($options['parents'])) {
  898. $tree[$raw_token]['parent'] = '[' . implode(':', $options['parents']) . ']';
  899. }
  900. // Fetch the child tokens.
  901. if (!empty($token_info['type'])) {
  902. $child_options = $options;
  903. $child_options['depth']--;
  904. $child_options['parents'] = $token_parents;
  905. $tree[$raw_token]['children'] = _token_build_tree($token_info['type'], $child_options);
  906. }
  907. }
  908. return $tree;
  909. }
  910. /**
  911. * Get a translated menu link by its mlid, without access checking.
  912. *
  913. * This function is a copy of menu_link_load() but with its own cache and a
  914. * simpler query to load the link. This also skips normal menu link access
  915. * checking by using _token_menu_link_translate().
  916. *
  917. * @param $mlid
  918. * The mlid of the menu item.
  919. *
  920. * @return
  921. * A menu link translated for rendering.
  922. *
  923. * @see menu_link_load()
  924. * @see _token_menu_link_translate()
  925. */
  926. function token_menu_link_load($mlid) {
  927. $cache = &drupal_static(__FUNCTION__, array());
  928. if (!is_numeric($mlid)) {
  929. return FALSE;
  930. }
  931. if (!isset($cache[$mlid])) {
  932. $item = db_query("SELECT * FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path WHERE ml.mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc();
  933. if (!empty($item)) {
  934. _token_menu_link_translate($item);
  935. }
  936. $cache[$mlid] = $item;
  937. }
  938. return $cache[$mlid];
  939. }
  940. /**
  941. * Get a translated book menu link by its mlid, without access checking.
  942. *
  943. * This function is a copy of book_link_load() but with its own cache and a
  944. * simpler query to load the link. This also skips normal menu link access
  945. * checking by using _token_menu_link_translate().
  946. *
  947. * @param $mlid
  948. * The mlid of the book menu item.
  949. *
  950. * @return
  951. * A book menu link translated for rendering.
  952. *
  953. * @see book_link_load()
  954. * @see _token_menu_link_translate()
  955. */
  956. function token_book_link_load($mlid) {
  957. $cache = &drupal_static(__FUNCTION__, array());
  958. if (!is_numeric($mlid)) {
  959. return FALSE;
  960. }
  961. if (!isset($cache[$mlid])) {
  962. $item = db_query("SELECT * FROM {menu_links} ml INNER JOIN {book} b ON b.mlid = ml.mlid LEFT JOIN {menu_router} m ON m.path = ml.router_path WHERE ml.mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc();
  963. if (!empty($item)) {
  964. _token_menu_link_translate($item);
  965. }
  966. $cache[$mlid] = $item;
  967. }
  968. return $cache[$mlid];
  969. }
  970. function _token_menu_link_translate(&$item) {
  971. $map = array();
  972. if (!is_array($item['options'])) {
  973. $item['options'] = unserialize($item['options']);
  974. }
  975. if ($item['external']) {
  976. $item['access'] = 1;
  977. $item['href'] = $item['link_path'];
  978. $item['title'] = $item['link_title'];
  979. $item['localized_options'] = $item['options'];
  980. }
  981. else {
  982. // Complete the path of the menu link with elements from the current path,
  983. // if it contains dynamic placeholders (%).
  984. $map = explode('/', $item['link_path']);
  985. if (strpos($item['link_path'], '%') !== FALSE) {
  986. // Invoke registered to_arg callbacks.
  987. if (!empty($item['to_arg_functions'])) {
  988. _menu_link_map_translate($map, $item['to_arg_functions']);
  989. }
  990. }
  991. $item['href'] = implode('/', $map);
  992. // Skip links containing untranslated arguments.
  993. if (strpos($item['href'], '%') !== FALSE) {
  994. $item['access'] = FALSE;
  995. return FALSE;
  996. }
  997. $item['access'] = TRUE;
  998. _menu_item_localize($item, $map, TRUE);
  999. }
  1000. // Allow other customizations - e.g. adding a page-specific query string to the
  1001. // options array. For performance reasons we only invoke this hook if the link
  1002. // has the 'alter' flag set in the options array.
  1003. if (!empty($item['options']['alter'])) {
  1004. drupal_alter('translated_menu_link', $item, $map);
  1005. }
  1006. return $map;
  1007. }
  1008. /**
  1009. * Prepare a string for use as a valid token name.
  1010. *
  1011. * @param $name
  1012. * The token name to clean.
  1013. * @return
  1014. * The cleaned token name.
  1015. */
  1016. function token_clean_token_name($name) {
  1017. static $names = array();
  1018. if (!isset($names[$name])) {
  1019. $cleaned_name = strtr($name, array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => ''));
  1020. $cleaned_name = preg_replace('/[^\w\-]/i', '', $cleaned_name);
  1021. $cleaned_name = trim($cleaned_name, '-');
  1022. $names[$name] = $cleaned_name;
  1023. }
  1024. return $names[$name];
  1025. }
  1026. /**
  1027. * Do not use this function yet. Its API has not been finalized.
  1028. */
  1029. function token_render_array(array $array, array $options = array()) {
  1030. $rendered = array();
  1031. foreach (element_children($array) as $key) {
  1032. $value = $array[$key];
  1033. $rendered[] = is_array($value) ? render($value) : (string) $value;
  1034. }
  1035. if (!empty($options['sanitize'])) {
  1036. $rendered = array_map('check_plain', $rendered);
  1037. }
  1038. $join = isset($options['join']) ? $options['join'] : ', ';
  1039. return implode($join, $rendered);
  1040. }
  1041. /**
  1042. * Do not use this function yet. Its API has not been finalized.
  1043. */
  1044. function token_render_array_value($value, array $options = array()) {
  1045. $rendered = is_array($value) ? render($value) : (string) $value;
  1046. if (!empty($options['sanitize'])) {
  1047. $rendered = check_plain($rendered);
  1048. }
  1049. return $rendered;
  1050. }
  1051. /**
  1052. * Copy of drupal_render_cache_get() that does not care about request method.
  1053. */
  1054. function token_render_cache_get($elements) {
  1055. if (!$cid = drupal_render_cid_create($elements)) {
  1056. return FALSE;
  1057. }
  1058. $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
  1059. if (!empty($cid) && $cache = cache_get($cid, $bin)) {
  1060. // Add additional libraries, JavaScript, CSS and other data attached
  1061. // to this element.
  1062. if (isset($cache->data['#attached'])) {
  1063. drupal_process_attached($cache->data);
  1064. }
  1065. // Return the rendered output.
  1066. return $cache->data['#markup'];
  1067. }
  1068. return FALSE;
  1069. }
  1070. /**
  1071. * Coyp of drupal_render_cache_set() that does not care about request method.
  1072. */
  1073. function token_render_cache_set(&$markup, $elements) {
  1074. // This should only run of drupal_render_cache_set() did not.
  1075. if (in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD'))) {
  1076. return FALSE;
  1077. }
  1078. $original_method = $_SERVER['REQUEST_METHOD'];
  1079. $_SERVER['REQUEST_METHOD'] = 'GET';
  1080. drupal_render_cache_set($markup, $elements);
  1081. $_SERVER['REQUEST_METHOD'] = $original_method;
  1082. }
  1083. function token_menu_link_load_all_parents($mlid) {
  1084. $cache = &drupal_static(__FUNCTION__, array());
  1085. if (!is_numeric($mlid)) {
  1086. return array();
  1087. }
  1088. if (!isset($cache[$mlid])) {
  1089. $cache[$mlid] = array();
  1090. $plid = db_query("SELECT plid FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchField();
  1091. while ($plid && $parent = token_menu_link_load($plid)) {
  1092. $cache[$mlid] = array($plid => $parent['title']) + $cache[$mlid];
  1093. $plid = $parent['plid'];
  1094. }
  1095. }
  1096. return $cache[$mlid];
  1097. }
  1098. function token_taxonomy_term_load_all_parents($tid) {
  1099. $cache = &drupal_static(__FUNCTION__, array());
  1100. if (!is_numeric($tid)) {
  1101. return array();
  1102. }
  1103. if (!isset($cache[$tid])) {
  1104. $cache[$tid] = array();
  1105. $parents = taxonomy_get_parents_all($tid);
  1106. array_shift($parents); // Remove this term from the array.
  1107. $parents = array_reverse($parents);
  1108. foreach ($parents as $term) {
  1109. $cache[$tid][$term->tid] = entity_label('taxonomy_term', $term);
  1110. }
  1111. }
  1112. return $cache[$tid];
  1113. }
  1114. /**
  1115. * Load the preferred menu link associated with a node.
  1116. *
  1117. * @param $node
  1118. * A node object.
  1119. *
  1120. * @return
  1121. * A menu link array from token_menu_link_load() or FALSE if a menu link was
  1122. * not found.
  1123. *
  1124. * @see menu_node_prepare()
  1125. * @see token_menu_link_load()
  1126. */
  1127. function token_node_menu_link_load($node) {
  1128. $cache = &drupal_static(__FUNCTIon__, array());
  1129. if (!isset($cache[$node->nid])) {
  1130. $mlid = FALSE;
  1131. // Nodes do not have their menu links loaded via menu_node_load().
  1132. if (!isset($node->menu)) {
  1133. // We need to clone the node as menu_node_prepare() may cause data loss.
  1134. // @see http://drupal.org/node/1317926
  1135. $menu_node = clone $node;
  1136. menu_node_prepare($menu_node);
  1137. $mlid = !empty($menu_node->menu['mlid']) ? $menu_node->menu['mlid'] : FALSE;
  1138. }
  1139. else {
  1140. $mlid = !empty($node->menu['mlid']) ? $node->menu['mlid'] : FALSE;
  1141. }
  1142. $cache[$node->nid] = $mlid;
  1143. }
  1144. return $cache[$node->nid] ? token_menu_link_load($cache[$node->nid]) : FALSE;
  1145. }