token.module 39 KB

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