token.module 40 KB

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