Projet

Général

Profil

Paste
Télécharger (39,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / token / token.module @ 99781f3b

1
<?php
2

    
3
/**
4
 * @file
5
 * Enhances the token API in core: adds a browseable UI, missing tokens, etc.
6
 */
7

    
8
/**
9
 * The maximum depth for token tree recursion.
10
 */
11
define('TOKEN_MAX_DEPTH', 9);
12

    
13
/**
14
 * Implements hook_help().
15
 */
16
function token_help($path, $arg) {
17
  if ($path == 'admin/help#token') {
18
    if (current_path() != 'admin/help/token') {
19
      // Because system_modules() executes hook_help() for each module to 'test'
20
      // if they will return anything, but not actually display it, we want to
21
      // return a TRUE value if this is not actually the help page.
22
      return TRUE;
23
    }
24
    $output = '<dl>';
25
    $output .= '<dt>' . t('List of the currently available tokens on this site') . '</dt>';
26
    $output .= '<dd>' . theme('token_tree', array('token_types' => 'all', 'click_insert' => FALSE, 'show_restricted' => TRUE)) . '</dd>';
27
    $output .= '</dl>';
28
    return $output;
29
  }
30
}
31

    
32
/**
33
 * Implements hook_system_info_alter().
34
 *
35
 * Prevent the token_actions module from being enabled since updates may have
36
 * left the old module files still in the directory.
37
 */
38
function token_system_info_alter(&$info, $file, $type) {
39
  if ($type == 'module' && $file->name == 'token_actions') {
40
    $info['hidden'] = TRUE;
41
  }
42
}
43

    
44
/**
45
 * Return an array of the core modules supported by token.module.
46
 */
47
function _token_core_supported_modules() {
48
  return array('book', 'field', 'menu', 'profile');
49
}
50

    
51
/**
52
 * Implements hook_menu().
53
 */
54
function token_menu() {
55
  /*$items['token/autocomplete/all/%menu_tail'] = array(
56
    'page callback' => 'token_autocomplete',
57
    'access callback' => TRUE,
58
    'type' => MENU_CALLBACK,
59
    'file' => 'token.pages.inc',
60
  );*/
61
  $items['token/autocomplete/%token_type'] = array(
62
    'page callback' => 'token_autocomplete_token',
63
    'page arguments' => array(2),
64
    'access callback' => TRUE,
65
    'type' => MENU_CALLBACK,
66
    'file' => 'token.pages.inc',
67
  );
68
  /*$items['token/autocomplete/%token_type/%menu_tail'] = array(
69
    'page callback' => 'token_autocomplete_token',
70
    'page arguments' => array(2, 3),
71
    'access callback' => TRUE,
72
    'type' => MENU_CALLBACK,
73
    'file' => 'token.pages.inc',
74
  );*/
75

    
76
  $items['token/tree'] = array(
77
    'page callback' => 'token_page_output_tree',
78
    'access callback' => TRUE,
79
    'type' => MENU_CALLBACK,
80
    'file' => 'token.pages.inc',
81
    'theme callback' => 'ajax_base_page_theme',
82
  );
83

    
84
  // Devel token pages.
85
  if (module_exists('devel')) {
86
    $items['node/%node/devel/token'] = array(
87
      'title' => 'Tokens',
88
      'page callback' => 'token_devel_token_object',
89
      'page arguments' => array('node', 1),
90
      'access arguments' => array('access devel information'),
91
      'type' => MENU_LOCAL_TASK,
92
      'file' => 'token.pages.inc',
93
      'weight' => 5,
94
    );
95
    $items['comment/%comment/devel/token'] = array(
96
      'title' => 'Tokens',
97
      'page callback' => 'token_devel_token_object',
98
      'page arguments' => array('comment', 1),
99
      'access arguments' => array('access devel information'),
100
      'type' => MENU_LOCAL_TASK,
101
      'file' => 'token.pages.inc',
102
      'weight' => 5,
103
    );
104
    $items['taxonomy/term/%taxonomy_term/devel/token'] = array(
105
      'title' => 'Tokens',
106
      'page callback' => 'token_devel_token_object',
107
      'page arguments' => array('taxonomy_term', 2),
108
      'access arguments' => array('access devel information'),
109
      'type' => MENU_LOCAL_TASK,
110
      'file' => 'token.pages.inc',
111
      'weight' => 5,
112
    );
113
    $items['user/%user/devel/token'] = array(
114
      'title' => 'Tokens',
115
      'page callback' => 'token_devel_token_object',
116
      'page arguments' => array('user', 1),
117
      'access arguments' => array('access devel information'),
118
      'type' => MENU_LOCAL_TASK,
119
      'file' => 'token.pages.inc',
120
      'weight' => 5,
121
    );
122
  }
123

    
124
  // Admin menu callback to clear token caches.
125
  $items['token/flush-cache'] = array(
126
    'page callback' => 'token_flush_cache_callback',
127
    'access arguments' => array('flush caches'),
128
    'type' => MENU_CALLBACK,
129
    'file' => 'token.pages.inc',
130
  );
131

    
132
  return $items;
133
}
134

    
135
/**
136
 * Implements hook_admin_menu_output_alter().
137
 */
138
function token_admin_menu_output_alter(&$content) {
139
  $content['icon']['icon']['flush-cache']['token'] = array(
140
    '#title' => t('Token registry'),
141
    '#href' => 'token/flush-cache',
142
    '#options' => array(
143
      'query' => drupal_get_destination() + array('token' => drupal_get_token('token/flush-cache')),
144
    ),
145
  );
146
}
147

    
148
function token_type_load($token_type) {
149
  $info = token_get_info();
150
  return isset($info['types'][$token_type]) ? $info['types'][$token_type] : FALSE;
151
}
152

    
153
/**
154
 * Implements hook_theme().
155
 */
156
function token_theme() {
157
  $info['tree_table'] = array(
158
    'variables' => array(
159
      'header' => array(),
160
      'rows' => array(),
161
      'attributes' => array(),
162
      'empty' => '',
163
      'caption' => '',
164
    ),
165
    'file' => 'token.pages.inc',
166
  );
167
  $info['token_tree'] = array(
168
    'variables' => array(
169
      'token_types' => array(),
170
      'global_types' => TRUE,
171
      'click_insert' => TRUE,
172
      'show_restricted' => FALSE,
173
      'recursion_limit' => 3,
174
      'dialog' => FALSE,
175
    ),
176
    'file' => 'token.pages.inc',
177
  );
178
  $info['token_tree_link'] = array(
179
    'variables' => array(
180
      'text' => NULL,
181
      'options' => array(),
182
      'dialog' => TRUE,
183
    ) + $info['token_tree']['variables'],
184
    'file' => 'token.pages.inc',
185
  );
186

    
187
  return $info;
188
}
189

    
190
/**
191
 * Implements hook_library().
192
 */
193
function token_library() {
194
  // jQuery treeTable plugin.
195
  $libraries['treeTable'] = array(
196
    'title' => 'jQuery treeTable',
197
    'website' => 'http://plugins.jquery.com/project/treetable',
198
    'version' => '2.3.0',
199
    'js' => array(
200
      drupal_get_path('module', 'token') . '/jquery.treeTable.js' => array(),
201
    ),
202
    'css' => array(
203
      drupal_get_path('module', 'token') . '/jquery.treeTable.css' => array(),
204
    ),
205
  );
206

    
207
  $libraries['dialog'] = array(
208
    'title' => 'Token dialog',
209
    'version' => '1.0',
210
    'js' => array(
211
      drupal_get_path('module', 'token') . '/token.js' => array(),
212
    ),
213
    'dependencies' => array(
214
      array('system', 'ui.dialog'),
215
    ),
216
  );
217

    
218
  return $libraries;
219
}
220

    
221
/**
222
 * Implements hook_form_alter().
223
 *
224
 * Adds a submit handler to forms which could affect the tokens available on
225
 * the site.
226
 */
227
function token_form_alter(&$form, $form_state, $form_id) {
228
  switch ($form_id) {
229
    // Profile field forms.
230
    case 'profile_field_form':
231
    case 'profile_field_delete':
232
    // User picture form.
233
    case 'user_admin_settings':
234
    // System date type form.
235
    // @todo Remove when http://drupal.org/node/1173706 is fixed.
236
    case 'system_add_date_format_type_form':
237
    case 'system_delete_date_format_type_form':
238
      $form += array('#submit' => array());
239
      array_unshift($form['#submit'], 'token_clear_cache');
240
      break;
241
  }
242
}
243

    
244
/**
245
 * Implements hook_block_view_alter().
246
 */
247
function token_block_view_alter(&$data, $block) {
248
  if (!empty($block->title) && $block->title != '<none>') {
249
    // Perform unsanitized token replacement since _block_render_blocks() will
250
    // call check_plain() on $block->title.
251
    $block->title = token_replace($block->title, array(), array('sanitize' => FALSE));
252
  }
253
}
254

    
255
/**
256
 * Implements hook_form_FORM_ID_alter().
257
 */
258
function token_form_block_add_block_form_alter(&$form, $form_state) {
259
  token_form_block_admin_configure_alter($form, $form_state);
260
}
261

    
262
/**
263
 * Implements hook_form_FORM_ID_alter().
264
 */
265
function token_form_block_admin_configure_alter(&$form, $form_state) {
266
  $form['settings']['title']['#description'] .= ' ' . t('This field supports tokens.');
267
  // @todo Figure out why this token validation does not seem to be working here.
268
  $form['settings']['title']['#element_validate'][] = 'token_element_validate';
269
  $form['settings']['title'] += array('#token_types' => array());
270
}
271

    
272
/**
273
 * Implements hook_widget_form_alter().
274
 */
275
function token_field_widget_form_alter(&$element, &$form_state, $context) {
276
  if (!empty($element['#description']) && !empty($context['instance']['description'])) {
277
    $instance = $context['instance'];
278
    if (module_exists('i18n_field')) {
279
      $instance = i18n_string_object_translate('field_instance', $instance);
280
    }
281
    $element['#description'] = field_filter_xss(token_replace($instance['description']));
282
  }
283
}
284

    
285
/**
286
 * Implements hook_field_info_alter().
287
 */
288
function token_field_info_alter(&$info) {
289
  $defaults = array(
290
    'taxonomy_term_reference' => 'taxonomy_term_reference_plain',
291
    'number_integer' => 'number_unformatted',
292
    'number_decimal' => 'number_unformatted',
293
    'number_float' => 'number_unformatted',
294
    'file' => 'file_url_plain',
295
    'image' => 'file_url_plain',
296
    'text' => 'text_default',
297
    'text_long' => 'text_default',
298
    'text_with_summary' => 'text_default',
299
    'list_integer' => 'list_default',
300
    'list_float' => 'list_default',
301
    'list_text' => 'list_default',
302
    'list_boolean' => 'list_default',
303
  );
304
  foreach ($defaults as $field_type => $default_token_formatter) {
305
    if (isset($info[$field_type])) {
306
      $info[$field_type] += array('default_token_formatter' => $default_token_formatter);
307
    }
308
  }
309
}
310

    
311
/**
312
 * Implements hook_field_display_alter().
313
 */
314
function token_field_display_alter(&$display, $context) {
315
  if ($context['view_mode'] == 'token') {
316
    $view_mode_settings = field_view_mode_settings($context['instance']['entity_type'], $context['instance']['bundle']);
317
    // If the token view mode fell back to the 'default' view mode, then
318
    // use the default token formatter.
319
    if (empty($view_mode_settings[$context['view_mode']]['custom_settings'])) {
320
      $field_type_info = field_info_field_types($context['field']['type']);
321

    
322
      // If the field has specified a specific formatter to be used by default
323
      // with tokens, use that, otherwise use the default formatter.
324
      $formatter = !empty($field_type_info['default_token_formatter']) ? $field_type_info['default_token_formatter'] : $field_type_info['default_formatter'];
325

    
326
      // Now that we have a formatter, fill in all the settings.
327
      $display['type'] = $formatter;
328
      $formatter_info = field_info_formatter_types($formatter);
329
      $display['settings'] = isset($formatter_info['settings']) ? $formatter_info['settings'] : array();
330
      $display['settings']['label'] = 'hidden';
331
      $display['module'] = $formatter_info['module'];
332
    }
333
  }
334
}
335

    
336
/**
337
 * Implements hook_field_create_instance().
338
 */
339
function token_field_create_instance($instance) {
340
  token_clear_cache();
341
}
342

    
343
/**
344
 * Implements hook_field_update_instance().
345
 */
346
function token_field_update_instance($instance) {
347
  token_clear_cache();
348
}
349

    
350
/**
351
 * Implements hook_field_delete_instance().
352
 */
353
function token_field_delete_instance($instance) {
354
  token_clear_cache();
355
}
356

    
357
/**
358
 * Clear token caches and static variables.
359
 */
360
function token_clear_cache() {
361
  if (db_table_exists('cache_token')) {
362
    cache_clear_all('*', 'cache_token', TRUE);
363
  }
364
  drupal_static_reset('token_get_info');
365
  drupal_static_reset('token_get_global_token_types');
366
  drupal_static_reset('token_get_entity_mapping');
367
  drupal_static_reset('token_build_tree');
368
  drupal_static_reset('_token_profile_fields');
369
  drupal_static_reset('token_menu_link_load');
370
  drupal_static_reset('token_book_link_load');
371
  drupal_static_reset('token_node_menu_link_load');
372
  drupal_static_reset('_token_field_info');
373
}
374

    
375
/**
376
 * Return an array of entity type to token type mappings.
377
 *
378
 * Why do we need this? Because when the token API was moved to core we did not
379
 * re-use the entity type as the base name for taxonomy terms and vocabulary
380
 * tokens.
381
 *
382
 * @see token_entity_info_alter()
383
 * @see http://drupal.org/node/737726
384
 */
385
function token_get_entity_mapping($value_type = 'token', $value = NULL, $fallback = FALSE) {
386
  $mapping = &drupal_static(__FUNCTION__, array());
387

    
388
  if (empty($mapping)) {
389
    foreach (entity_get_info() as $entity_type => $info) {
390
      $mapping[$entity_type] = !empty($info['token type']) ? $info['token type'] : $entity_type;
391
    }
392
    // Allow modules to alter the mapping array.
393
    drupal_alter('token_entity_mapping', $mapping);
394
  }
395

    
396
  if (!isset($value)) {
397
    return $value_type == 'token' ? array_flip($mapping) : $mapping;
398
  }
399
  elseif ($value_type == 'token') {
400
    $return = array_search($value, $mapping);
401
    return $return !== FALSE ? $return : ($fallback ? $value : FALSE);
402
  }
403
  elseif ($value_type == 'entity') {
404
    return isset($mapping[$value]) ? $mapping[$value] : ($fallback ? $value : FALSE);
405
  }
406
}
407

    
408
/**
409
 * Implements hook_entity_info_alter().
410
 *
411
 * Because some token types to do not match their entity type names, we have to
412
 * map them to the proper type. This is purely for other modules' benefit.
413
 *
414
 * @see token_get_entity_mapping()
415
 * @see http://drupal.org/node/737726
416
 */
417
function token_entity_info_alter(&$info) {
418
  foreach (array_keys($info) as $entity_type) {
419
    // Add a token view mode if it does not already exist. Only work with
420
    // fieldable entities.
421
    if (!empty($info[$entity_type]['fieldable'])) {
422
      if (!isset($info[$entity_type])) {
423
        $info[$entity_type]['view modes'] = array();
424
      }
425
      if (!isset($info[$entity_type]['view modes']['token'])) {
426
        $info[$entity_type]['view modes']['token'] = array(
427
          'label' => t('Tokens'),
428
          'custom settings' => FALSE,
429
        );
430
      }
431
    }
432

    
433
    if (!empty($info[$entity_type]['token type'])) {
434
      // If the entity's token type is already defined, great!
435
      continue;
436
    }
437

    
438
    // Fill in default token types for entities.
439
    switch ($entity_type) {
440
      case 'taxonomy_term':
441
      case 'taxonomy_vocabulary':
442
        // Stupid taxonomy token types...
443
        $info[$entity_type]['token type'] = str_replace('taxonomy_', '', $entity_type);
444
        break;
445
      default:
446
        // By default the token type is the same as the entity type.
447
        $info[$entity_type]['token type'] = $entity_type;
448
        break;
449
    }
450
  }
451
}
452

    
453
/**
454
 * Implements hook_module_implements_alter().
455
 *
456
 * Adds missing token support for core modules.
457
 */
458
function token_module_implements_alter(&$implementations, $hook) {
459
  module_load_include('inc', 'token', 'token.tokens');
460

    
461
  if ($hook == 'tokens' || $hook == 'token_info' || $hook == 'token_info_alter' || $hook == 'tokens_alter') {
462
    foreach (_token_core_supported_modules() as $module) {
463
      if (module_exists($module) && function_exists($module . '_' . $hook)) {
464
        $implementations[$module] = FALSE;
465
      }
466
    }
467
    // Move token.module to get included first since it is responsible for
468
    // other modules.
469
    unset($implementations['token']);
470
    $implementations = array_merge(array('token' => 'tokens'), $implementations);
471
  }
472
}
473

    
474
/**
475
 * Implements hook_flush_caches().
476
 */
477
function token_flush_caches() {
478
  if (db_table_exists('cache_token')) {
479
    return array('cache_token');
480
  }
481
}
482

    
483
/**
484
 * Retrieve, sort, store token info from the cache.
485
 *
486
 * @param $token_type
487
 *   The optional token type that if specified will return
488
 *   $info['types'][$token_type].
489
 * @param $token
490
 *   The optional token name if specified will return
491
 *   $info['tokens'][$token_type][$token].
492
 *
493
 * @return
494
 *   An array of all token information from hook_token_info(), or the array
495
 *   of a token type or specific token.
496
 *
497
 * @see hook_token_info()
498
 * @see hook_token_info_alter()
499
 */
500
function token_get_info($token_type = NULL, $token = NULL) {
501
  global $language;
502

    
503
  // Use the advanced drupal_static() pattern, since this is called very often.
504
  static $drupal_static_fast;
505
  if (!isset($drupal_static_fast)) {
506
    $drupal_static_fast['token_info'] = &drupal_static(__FUNCTION__);
507
  }
508
  $token_info = &$drupal_static_fast['token_info'];
509

    
510
  if (empty($token_info)) {
511
    $cid = "info:{$language->language}";
512

    
513
    if ($cache = cache_get($cid, 'cache_token')) {
514
      $token_info = $cache->data;
515
    }
516
    else {
517
      $token_info = token_info();
518

    
519
      foreach (array_keys($token_info['types']) as $type_key) {
520
        if (isset($token_info['types'][$type_key]['type'])) {
521
          $base_type = $token_info['types'][$type_key]['type'];
522
          // If this token type extends another token type, then merge in
523
          // the base token type's tokens.
524
          if (isset($token_info['tokens'][$base_type])) {
525
            $token_info['tokens'] += array($type_key => array());
526
            $token_info['tokens'][$type_key] += $token_info['tokens'][$base_type];
527
          }
528
        }
529
        else {
530
          // Add a 'type' value to each token type so we can properly use
531
          // token_type_load().
532
          $token_info['types'][$type_key]['type'] = $type_key;
533
        }
534
      }
535

    
536
      // Pre-sort tokens.
537
      uasort($token_info['types'], 'token_asort_tokens');
538
      foreach (array_keys($token_info['tokens']) as $type) {
539
        uasort($token_info['tokens'][$type], 'token_asort_tokens');
540
      }
541

    
542
      // Store info in cache for future use.
543
      cache_set($cid, $token_info, 'cache_token');
544
    }
545
  }
546

    
547
  if (isset($token_type) && isset($token)) {
548
    return isset($token_info['tokens'][$token_type][$token]) ? $token_info['tokens'][$token_type][$token] : NULL;
549
  }
550
  elseif (isset($token_type)) {
551
    return isset($token_info['types'][$token_type]) ? $token_info['types'][$token_type] : NULL;
552
  }
553
  else {
554
    return $token_info;
555
  }
556
}
557

    
558
/**
559
 * Return the module responsible for a token.
560
 *
561
 * @param string $type
562
 *   The token type.
563
 * @param string $name
564
 *   The token name.
565
 *
566
 * @return mixed
567
 *   The value of $info['tokens'][$type][$name]['module'] from token_get_info(),
568
 *   or NULL if the value does not exist.
569
 */
570
function _token_module($type, $name) {
571
  $token_info = token_get_info($type, $name);
572
  return isset($token_info['module']) ? $token_info['module'] : NULL;
573
}
574

    
575
/**
576
 * uasort() callback to sort tokens by the 'name' property.
577
 */
578
function token_asort_tokens($token_a, $token_b) {
579
  return strnatcmp($token_a['name'], $token_b['name']);
580
}
581

    
582
/**
583
 * Get a list of token types that can be used without any context (global).
584
 *
585
 * @return
586
 *   An array of global token types.
587
 */
588
function token_get_global_token_types() {
589
  $global_types = &drupal_static(__FUNCTION__, array());
590

    
591
  if (empty($global_types)) {
592
    $token_info = token_get_info();
593
    foreach ($token_info['types'] as $type => $type_info) {
594
      // If the token types has not specified that 'needs-data' => TRUE, then
595
      // it is a global token type that will always be replaced in any context.
596
      if (empty($type_info['needs-data'])) {
597
        $global_types[] = $type;
598
      }
599
    }
600
  }
601

    
602
  return $global_types;
603
}
604

    
605
/**
606
 * Validate an tokens in raw text based on possible contexts.
607
 *
608
 * @param $value
609
 *   A string with the raw text containing the raw tokens, or an array of
610
 *   tokens from token_scan().
611
 * @param $tokens
612
 *   An array of token types that will be used when token replacement is
613
 *   performed.
614
 * @return
615
 *   An array with the invalid tokens in their original raw forms.
616
 */
617
function token_get_invalid_tokens_by_context($value, $valid_types = array()) {
618
  if (in_array('all', $valid_types)) {
619
    $info = token_get_info();
620
    $valid_types = array_keys($info['types']);
621
  }
622
  else {
623
    // Add the token types that are always valid in global context.
624
    $valid_types = array_merge($valid_types, token_get_global_token_types());
625
  }
626

    
627
  $invalid_tokens = array();
628
  $value_tokens = is_string($value) ? token_scan($value) : $value;
629

    
630
  foreach ($value_tokens as $type => $tokens) {
631
    if (!in_array($type, $valid_types)) {
632
      // If the token type is not a valid context, its tokens are invalid.
633
      $invalid_tokens = array_merge($invalid_tokens, array_values($tokens));
634
    }
635
    else {
636
      // Check each individual token for validity.
637
      $invalid_tokens = array_merge($invalid_tokens, token_get_invalid_tokens($type, $tokens));
638
    }
639
  }
640

    
641
  array_unique($invalid_tokens);
642
  return $invalid_tokens;
643
}
644

    
645
/**
646
 * Validate an array of tokens based on their token type.
647
 *
648
 * @param $type
649
 *   The type of tokens to validate (e.g. 'node', etc.)
650
 * @param $tokens
651
 *   A keyed array of tokens, and their original raw form in the source text.
652
 * @return
653
 *   An array with the invalid tokens in their original raw forms.
654
 */
655
function token_get_invalid_tokens($type, $tokens) {
656
  $token_info = token_get_info();
657
  $invalid_tokens = array();
658

    
659
  foreach ($tokens as $token => $full_token) {
660
    if (isset($token_info['tokens'][$type][$token])) {
661
      continue;
662
    }
663

    
664
    // Split token up if it has chains.
665
    $parts = explode(':', $token, 2);
666

    
667
    if (!isset($token_info['tokens'][$type][$parts[0]])) {
668
      // This is an invalid token (not defined).
669
      $invalid_tokens[] = $full_token;
670
    }
671
    elseif (count($parts) == 2) {
672
      $sub_token_info = $token_info['tokens'][$type][$parts[0]];
673
      if (!empty($sub_token_info['dynamic'])) {
674
        // If this token has been flagged as a dynamic token, skip it.
675
        continue;
676
      }
677
      elseif (empty($sub_token_info['type'])) {
678
        // If the token has chains, but does not support it, it is invalid.
679
        $invalid_tokens[] = $full_token;
680
      }
681
      else {
682
        // Resursively check the chained tokens.
683
        $sub_tokens = token_find_with_prefix(array($token => $full_token), $parts[0]);
684
        $invalid_tokens = array_merge($invalid_tokens, token_get_invalid_tokens($sub_token_info['type'], $sub_tokens));
685
      }
686
    }
687
  }
688

    
689
  return $invalid_tokens;
690
}
691

    
692
/**
693
 * Validate a form element that should have tokens in it.
694
 *
695
 * Form elements that want to add this validation should have the #token_types
696
 * parameter defined.
697
 *
698
 * For example:
699
 * @code
700
 * $form['my_node_text_element'] = array(
701
 *   '#type' => 'textfield',
702
 *   '#title' => t('Some text to token-ize that has a node context.'),
703
 *   '#default_value' => 'The title of this node is [node:title].',
704
 *   '#element_validate' => array('token_element_validate'),
705
 *   '#token_types' => array('node'),
706
 *   '#min_tokens' => 1,
707
 *   '#max_tokens' => 10,
708
 * );
709
 * @endcode
710
 */
711
function token_element_validate(&$element, &$form_state) {
712
  $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
713

    
714
  if (!drupal_strlen($value)) {
715
    // Empty value needs no further validation since the element should depend
716
    // on using the '#required' FAPI property.
717
    return $element;
718
  }
719

    
720
  $tokens = token_scan($value);
721
  $title = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
722
  // @todo Find old Drupal 6 style tokens and add them to invalid tokens.
723

    
724
  // Validate if an element must have a minimum number of tokens.
725
  if (isset($element['#min_tokens']) && count($tokens) < $element['#min_tokens']) {
726
    $error = format_plural($element['#min_tokens'], '%name must contain at least one token.', '%name must contain at least @count tokens.', array('%name' => $title));
727
    form_error($element, $error);
728
  }
729

    
730
  // Validate if an element must have a maximum number of tokens.
731
  if (isset($element['#max_tokens']) && count($tokens) > $element['#max_tokens']) {
732
    $error = format_plural($element['#max_tokens'], '%name must contain at most one token.', '%name must contain at most @count tokens.', array('%name' => $title));
733
    form_error($element, $error);
734
  }
735

    
736
  // Check if the field defines specific token types.
737
  if (isset($element['#token_types'])) {
738
    $invalid_tokens = token_get_invalid_tokens_by_context($tokens, $element['#token_types']);
739
    if ($invalid_tokens) {
740
      form_error($element, t('%name is using the following invalid tokens: @invalid-tokens.', array('%name' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens))));
741
    }
742
  }
743

    
744
  return $element;
745
}
746

    
747
/**
748
 * Deprecated. Use token_element_validate() instead.
749
 */
750
function token_element_validate_token_context(&$element, &$form_state) {
751
  return token_element_validate($element, $form_state);
752
}
753

    
754
/**
755
 * Implements hook_form_FORM_ID_alter().
756
 */
757
function token_form_field_ui_field_edit_form_alter(&$form, $form_state) {
758
  if (!isset($form['instance']) || !empty($form['#field']['locked'])) {
759
    return;
760
  }
761

    
762
  if (($form['#field']['type'] == 'file' || $form['#field']['type'] == 'image') && isset($form['instance']['settings']['file_directory']) && !module_exists('filefield_paths')) {
763
    // GAH! We can only support global tokens in the upload file directory path.
764
    $form['instance']['settings']['file_directory']['#element_validate'][] = 'token_element_validate';
765
    $form['instance']['settings']['file_directory'] += array('#token_types' => array());
766
    $form['instance']['settings']['file_directory']['#description'] .= ' ' . t('This field supports tokens.');
767
  }
768

    
769
  // Note that the description is tokenized via token_field_widget_form_alter().
770
  $form['instance']['description']['#description'] .= '<br />' . t('This field supports tokens.');
771
  $form['instance']['description']['#element_validate'][] = 'token_element_validate';
772
  $form['instance']['description'] += array('#token_types' => array());
773

    
774
  $form['instance']['settings']['token_tree'] = array(
775
    '#theme' => 'token_tree',
776
    '#token_types' => array(),
777
    '#dialog' => TRUE,
778
    '#weight' => $form['instance']['description']['#weight'] + 0.5,
779
  );
780
}
781

    
782
/**
783
 * Implements hook_form_FORM_ID_alter().
784
 *
785
 * Alters the configure action form to add token context validation and
786
 * adds the token tree for a better token UI and selection.
787
 */
788
function token_form_system_actions_configure_alter(&$form, $form_state) {
789
  $action = actions_function_lookup($form['actions_action']['#value']);
790

    
791
  switch ($action) {
792
    case 'system_message_action':
793
    case 'system_send_email_action':
794
    case 'system_goto_action':
795
      $form['token_tree'] = array(
796
        '#theme' => 'token_tree',
797
        '#token_types' => 'all',
798
        '#dialog' => TRUE,
799
        '#weight' => 100,
800
      );
801
      // @todo Add token validation to the action fields that can use tokens.
802
      break;
803
  }
804
}
805

    
806
/**
807
 * Implements hook_form_FORM_ID_alter().
808
 *
809
 * Alters the user e-mail fields to add token context validation and
810
 * adds the token tree for a better token UI and selection.
811
 */
812
function token_form_user_admin_settings_alter(&$form, &$form_state) {
813
  $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].');
814

    
815
  foreach (element_children($form) as $key) {
816
    $element = &$form[$key];
817

    
818
    // Remove the crummy default token help text.
819
    if (!empty($element['#description'])) {
820
      $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']));
821
    }
822

    
823
    switch ($key) {
824
      case 'email_admin_created':
825
      case 'email_pending_approval':
826
      case 'email_no_approval_required':
827
      case 'email_password_reset':
828
      case 'email_cancel_confirm':
829
        // Do nothing, but allow execution to continue.
830
        break;
831
      case 'email_activated':
832
      case 'email_blocked':
833
      case 'email_canceled':
834
        // These fieldsets have their e-mail elements inside a 'settings'
835
        // sub-element, so switch to that element instead.
836
        $element = &$form[$key]['settings'];
837
        break;
838
      default:
839
        continue 2;
840
    }
841

    
842
    foreach (element_children($element) as $sub_key) {
843
      if (!isset($element[$sub_key]['#type'])) {
844
        continue;
845
      }
846
      elseif ($element[$sub_key]['#type'] == 'textfield' && substr($sub_key, -8) === '_subject') {
847
        // Add validation to subject textfields.
848
        $element[$sub_key]['#element_validate'][] = 'token_element_validate';
849
        $element[$sub_key] += array('#token_types' => array('user'));
850
      }
851
      elseif ($element[$sub_key]['#type'] == 'textarea' && substr($sub_key, -5) === '_body') {
852
        // Add validation to body textareas.
853
        $element[$sub_key]['#element_validate'][] = 'token_element_validate';
854
        $element[$sub_key] += array('#token_types' => array('user'));
855
      }
856
    }
857
  }
858

    
859
  // Add the token tree UI.
860
  $form['email']['token_tree'] = array(
861
    '#theme' => 'token_tree',
862
    '#token_types' => array('user'),
863
    '#show_restricted' => TRUE,
864
    '#dialog' => TRUE,
865
    '#weight' => 90,
866
  );
867
}
868

    
869
/**
870
 * Build a tree array of tokens used for themeing or information.
871
 *
872
 * @param $token_type
873
 *   The token type.
874
 * @param $flat_tree
875
 *   A boolean if TRUE will only make a flat array of tokens, otherwise
876
 *   child tokens will be inside the 'children' parameter of a token.
877
 * @param $show_restricted
878
 *   A boolean if TRUE will show restricted tokens. Otherwise they will be
879
 *   hidden. Default is FALSE.
880
 * @param $recursion_limit
881
 *   An integer with the maximum number of token levels to recurse.
882
 * @param $parents
883
 *   An optional array with the current parents of the tokens.
884
 */
885
function token_build_tree($token_type, array $options = array()) {
886
  global $language;
887

    
888
  // Static cache of already built token trees.
889
  $trees = &drupal_static(__FUNCTION__, array());
890

    
891
  $options += array(
892
    'restricted' => FALSE,
893
    'depth' => 4,
894
    'data' => array(),
895
    'values' => FALSE,
896
    'flat' => FALSE,
897
  );
898

    
899
  // Do not allow past the maximum token information depth.
900
  $options['depth'] = min($options['depth'], TOKEN_MAX_DEPTH);
901

    
902
  // If $token_type is an entity, make sure we are using the actual token type.
903
  if ($entity_token_type = token_get_entity_mapping('entity', $token_type)) {
904
    $token_type = $entity_token_type;
905
  }
906

    
907
  $tree_cid = "tree:{$token_type}:{$language->language}:{$options['depth']}";
908

    
909
  // If we do not have this base tree in the static cache, check {cache_token}
910
  // otherwise generate and store it in the cache.
911
  if (!isset($trees[$tree_cid])) {
912
    if ($cache = cache_get($tree_cid, 'cache_token')) {
913
      $trees[$tree_cid] = $cache->data;
914
    }
915
    else {
916
      $options['parents'] = array();
917
      $trees[$tree_cid] = _token_build_tree($token_type, $options);
918
      cache_set($tree_cid, $trees[$tree_cid], 'cache_token');
919
    }
920
  }
921

    
922
  $tree = $trees[$tree_cid];
923

    
924
  // If the user has requested a flat tree, convert it.
925
  if (!empty($options['flat'])) {
926
    $tree = token_flatten_tree($tree);
927
  }
928

    
929
  // Fill in token values.
930
  if (!empty($options['values'])) {
931
    $token_values = array();
932
    foreach ($tree as $token => $token_info) {
933
      if (!empty($token_info['dynamic']) || !empty($token_info['restricted'])) {
934
        continue;
935
      }
936
      elseif (!isset($token_info['value'])) {
937
        $token_values[$token_info['token']] = $token;
938
      }
939
    }
940
    if (!empty($token_values)) {
941
      $token_values = token_generate($token_type, $token_values, $options['data']);
942
      foreach ($token_values as $token => $replacement) {
943
        $tree[$token]['value'] = $replacement;
944
      }
945
    }
946
  }
947

    
948
  return $tree;
949
}
950

    
951
/**
952
 * Flatten a token tree.
953
 */
954
function token_flatten_tree($tree) {
955
  $result = array();
956
  foreach ($tree as $token => $token_info) {
957
    $result[$token] = $token_info;
958
    if (isset($token_info['children']) && is_array($token_info['children'])) {
959
      $result += token_flatten_tree($token_info['children']);
960
      // unset($result[$token]['children']);
961
    }
962
  }
963
  return $result;
964
}
965

    
966
/**
967
 * Generate a token tree.
968
 */
969
function _token_build_tree($token_type, array $options) {
970
  $options += array(
971
    'parents' => array(),
972
  );
973

    
974
  $info = token_get_info();
975
  if ($options['depth'] <= 0 || !isset($info['types'][$token_type]) || !isset($info['tokens'][$token_type])) {
976
    return array();
977
  }
978

    
979
  $tree = array();
980
  foreach ($info['tokens'][$token_type] as $token => $token_info) {
981
    // Build the raw token string.
982
    $token_parents = $options['parents'];
983
    if (empty($token_parents)) {
984
      // If the parents array is currently empty, assume the token type is its
985
      // parent.
986
      $token_parents[] = $token_type;
987
    }
988
    elseif (in_array($token, array_slice($token_parents, 1), TRUE)) {
989
      // Prevent duplicate recursive tokens. For example, this will prevent
990
      // the tree from generating the following tokens or deeper:
991
      // [comment:parent:parent]
992
      // [comment:parent:root:parent]
993
      continue;
994
    }
995

    
996
    $token_parents[] = $token;
997
    if (!empty($token_info['dynamic'])) {
998
      $token_parents[] = '?';
999
    }
1000
    $raw_token = '[' . implode(':', $token_parents) . ']';
1001
    $tree[$raw_token] = $token_info;
1002
    $tree[$raw_token]['raw token'] = $raw_token;
1003

    
1004
    // Add the token's real name (leave out the base token type).
1005
    $tree[$raw_token]['token'] = implode(':', array_slice($token_parents, 1));
1006

    
1007
    // Add the token's parent as its raw token value.
1008
    if (!empty($options['parents'])) {
1009
      $tree[$raw_token]['parent'] = '[' . implode(':', $options['parents']) . ']';
1010
    }
1011

    
1012
    // Fetch the child tokens.
1013
    if (!empty($token_info['type'])) {
1014
      $child_options = $options;
1015
      $child_options['depth']--;
1016
      $child_options['parents'] = $token_parents;
1017
      $tree[$raw_token]['children'] = _token_build_tree($token_info['type'], $child_options);
1018
    }
1019
  }
1020

    
1021
  return $tree;
1022
}
1023

    
1024
/**
1025
 * Get a translated menu link by its mlid, without access checking.
1026
 *
1027
 * This function is a copy of menu_link_load() but with its own cache and a
1028
 * simpler query to load the link. This also skips normal menu link access
1029
 * checking by using _token_menu_link_translate().
1030
 *
1031
 * @param $mlid
1032
 *   The mlid of the menu item.
1033
 *
1034
 * @return
1035
 *   A menu link translated for rendering.
1036
 *
1037
 * @see menu_link_load()
1038
 * @see _token_menu_link_translate()
1039
 */
1040
function token_menu_link_load($mlid) {
1041
  $cache = &drupal_static(__FUNCTION__, array());
1042

    
1043
  if (!is_numeric($mlid)) {
1044
    return FALSE;
1045
  }
1046

    
1047
  if (!isset($cache[$mlid])) {
1048
    $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();
1049
    if (!empty($item)) {
1050
      _token_menu_link_translate($item);
1051
    }
1052
    $cache[$mlid] = $item;
1053
  }
1054

    
1055
  return $cache[$mlid];
1056
}
1057

    
1058
/**
1059
 * Get a translated book menu link by its mlid, without access checking.
1060
 *
1061
 * This function is a copy of book_link_load() but with its own cache and a
1062
 * simpler query to load the link. This also skips normal menu link access
1063
 * checking by using _token_menu_link_translate().
1064
 *
1065
 * @param $mlid
1066
 *   The mlid of the book menu item.
1067
 *
1068
 * @return
1069
 *   A book menu link translated for rendering.
1070
 *
1071
 * @see book_link_load()
1072
 * @see _token_menu_link_translate()
1073
 */
1074
function token_book_link_load($mlid) {
1075
  $cache = &drupal_static(__FUNCTION__, array());
1076

    
1077
  if (!is_numeric($mlid)) {
1078
    return FALSE;
1079
  }
1080

    
1081
  if (!isset($cache[$mlid])) {
1082
    $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();
1083
    if (!empty($item)) {
1084
      _token_menu_link_translate($item);
1085
    }
1086
    $cache[$mlid] = $item;
1087
  }
1088

    
1089
  return $cache[$mlid];
1090
}
1091

    
1092
function _token_menu_link_translate(&$item) {
1093
  $map = array();
1094

    
1095
  if (!is_array($item['options'])) {
1096
    $item['options'] = unserialize($item['options']);
1097
  }
1098

    
1099
  if ($item['external']) {
1100
    $item['access'] = 1;
1101
    $item['href'] = $item['link_path'];
1102
    $item['title'] = $item['link_title'];
1103
    $item['localized_options'] = $item['options'];
1104
  }
1105
  else {
1106
    // Complete the path of the menu link with elements from the current path,
1107
    // if it contains dynamic placeholders (%).
1108
    $map = explode('/', $item['link_path']);
1109
    if (strpos($item['link_path'], '%') !== FALSE) {
1110
      // Invoke registered to_arg callbacks.
1111
      if (!empty($item['to_arg_functions'])) {
1112
        _menu_link_map_translate($map, $item['to_arg_functions']);
1113
      }
1114
    }
1115
    $item['href'] = implode('/', $map);
1116

    
1117
    // Skip links containing untranslated arguments.
1118
    if (strpos($item['href'], '%') !== FALSE) {
1119
      $item['access'] = FALSE;
1120
      return FALSE;
1121
    }
1122

    
1123
    $item['access'] = TRUE;
1124
    _menu_item_localize($item, $map, TRUE);
1125
  }
1126

    
1127
  // Allow other customizations - e.g. adding a page-specific query string to the
1128
  // options array. For performance reasons we only invoke this hook if the link
1129
  // has the 'alter' flag set in the options array.
1130
  if (!empty($item['options']['alter'])) {
1131
    drupal_alter('translated_menu_link', $item, $map);
1132
  }
1133

    
1134
  return $map;
1135
}
1136

    
1137
/**
1138
 * Prepare a string for use as a valid token name.
1139
 *
1140
 * @param $name
1141
 *   The token name to clean.
1142
 * @return
1143
 *   The cleaned token name.
1144
 */
1145
function token_clean_token_name($name) {
1146
  static $names = array();
1147

    
1148
  if (!isset($names[$name])) {
1149
    $cleaned_name = strtr($name, array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => ''));
1150
    $cleaned_name = preg_replace('/[^\w\-]/i', '', $cleaned_name);
1151
    $cleaned_name = trim($cleaned_name, '-');
1152
    $names[$name] = $cleaned_name;
1153
  }
1154

    
1155
  return $names[$name];
1156
}
1157

    
1158
/**
1159
 * Do not use this function yet. Its API has not been finalized.
1160
 */
1161
function token_render_array(array $array, array $options = array()) {
1162
  $rendered = array();
1163
  foreach (element_children($array) as $key) {
1164
    $value = $array[$key];
1165
    $rendered[] = is_array($value) ? render($value) : (string) $value;
1166
  }
1167
  if (!empty($options['sanitize'])) {
1168
    $rendered = array_map('check_plain', $rendered);
1169
  }
1170
  $join = isset($options['join']) ? $options['join'] : ', ';
1171
  return implode($join, $rendered);
1172
}
1173

    
1174
/**
1175
 * Do not use this function yet. Its API has not been finalized.
1176
 */
1177
function token_render_array_value($value, array $options = array()) {
1178
  $rendered = is_array($value) ? render($value) : (string) $value;
1179
  if (!empty($options['sanitize'])) {
1180
    $rendered = check_plain($rendered);
1181
  }
1182
  return $rendered;
1183
}
1184

    
1185
/**
1186
 * Copy of drupal_render_cache_get() that does not care about request method.
1187
 */
1188
function token_render_cache_get($elements) {
1189
  if (!$cid = drupal_render_cid_create($elements)) {
1190
    return FALSE;
1191
  }
1192
  $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
1193

    
1194
  if (!empty($cid) && $cache = cache_get($cid, $bin)) {
1195
    // Add additional libraries, JavaScript, CSS and other data attached
1196
    // to this element.
1197
    if (isset($cache->data['#attached'])) {
1198
      drupal_process_attached($cache->data);
1199
    }
1200
    // Return the rendered output.
1201
    return $cache->data['#markup'];
1202
  }
1203
  return FALSE;
1204
}
1205

    
1206
/**
1207
 * Coyp of drupal_render_cache_set() that does not care about request method.
1208
 */
1209
function token_render_cache_set(&$markup, $elements) {
1210
  // This should only run of drupal_render_cache_set() did not.
1211
  if (in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD'))) {
1212
    return FALSE;
1213
  }
1214

    
1215
  $original_method = $_SERVER['REQUEST_METHOD'];
1216
  $_SERVER['REQUEST_METHOD'] = 'GET';
1217
  drupal_render_cache_set($markup, $elements);
1218
  $_SERVER['REQUEST_METHOD'] = $original_method;
1219
}
1220

    
1221
function token_menu_link_load_all_parents($mlid) {
1222
  $cache = &drupal_static(__FUNCTION__, array());
1223

    
1224
  if (!is_numeric($mlid)) {
1225
    return array();
1226
  }
1227

    
1228
  if (!isset($cache[$mlid])) {
1229
    $cache[$mlid] = array();
1230
    $plid = db_query("SELECT plid FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchField();
1231
    while ($plid && $parent = token_menu_link_load($plid)) {
1232
      $cache[$mlid] = array($plid => $parent['title']) + $cache[$mlid];
1233
      $plid = $parent['plid'];
1234
    }
1235
  }
1236

    
1237
  return $cache[$mlid];
1238
}
1239

    
1240
function token_taxonomy_term_load_all_parents($tid) {
1241
  $cache = &drupal_static(__FUNCTION__, array());
1242

    
1243
  if (!is_numeric($tid)) {
1244
    return array();
1245
  }
1246

    
1247
  if (!isset($cache[$tid])) {
1248
    $cache[$tid] = array();
1249
    $parents = taxonomy_get_parents_all($tid);
1250
    array_shift($parents); // Remove this term from the array.
1251
    $parents = array_reverse($parents);
1252
    foreach ($parents as $term) {
1253
      $cache[$tid][$term->tid] = entity_label('taxonomy_term', $term);
1254
    }
1255
  }
1256

    
1257
  return $cache[$tid];
1258
}
1259

    
1260
/**
1261
 * Load the preferred menu link associated with a node.
1262
 *
1263
 * @param $node
1264
 *   A node object.
1265
 *
1266
 * @return
1267
 *   A menu link array from token_menu_link_load() or FALSE if a menu link was
1268
 *   not found.
1269
 *
1270
 * @see menu_node_prepare()
1271
 * @see token_menu_link_load()
1272
 */
1273
function token_node_menu_link_load($node) {
1274
  $cache = &drupal_static(__FUNCTIon__, array());
1275

    
1276
  if (!isset($cache[$node->nid])) {
1277
    $mlid = FALSE;
1278

    
1279
    // Nodes do not have their menu links loaded via menu_node_load().
1280
    if (!isset($node->menu)) {
1281
      // We need to clone the node as menu_node_prepare() may cause data loss.
1282
      // @see http://drupal.org/node/1317926
1283
      $menu_node = clone $node;
1284
      menu_node_prepare($menu_node);
1285
      $mlid = !empty($menu_node->menu['mlid']) ? $menu_node->menu['mlid'] : FALSE;
1286
    }
1287
    else {
1288
      $mlid = !empty($node->menu['mlid']) ? $node->menu['mlid'] : FALSE;
1289
    }
1290

    
1291
    $cache[$node->nid] = $mlid;
1292
  }
1293

    
1294
  return $cache[$node->nid] ? token_menu_link_load($cache[$node->nid]) : FALSE;
1295
}