Projet

Général

Profil

Paste
Télécharger (40 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / token / token.module @ f9d4b898

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
      'colgroups' => array(),
165
      'sticky' => TRUE,
166
    ),
167
    'file' => 'token.pages.inc',
168
  );
169
  $info['token_tree'] = array(
170
    'variables' => array(
171
      'token_types' => array(),
172
      'global_types' => TRUE,
173
      'click_insert' => TRUE,
174
      'show_restricted' => FALSE,
175
      'recursion_limit' => 3,
176
      'dialog' => FALSE,
177
    ),
178
    'file' => 'token.pages.inc',
179
  );
180
  $info['token_tree_link'] = array(
181
    'variables' => array(
182
      'text' => NULL,
183
      'options' => array(),
184
      'dialog' => TRUE,
185
    ) + $info['token_tree']['variables'],
186
    'file' => 'token.pages.inc',
187
  );
188

    
189
  return $info;
190
}
191

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

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

    
220
  return $libraries;
221
}
222

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
604
  return $global_types;
605
}
606

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

    
629
  $invalid_tokens = array();
630
  $value_tokens = is_string($value) ? token_scan($value) : $value;
631

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

    
643
  array_unique($invalid_tokens);
644
  return $invalid_tokens;
645
}
646

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

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

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

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

    
691
  return $invalid_tokens;
692
}
693

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

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

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

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

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

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

    
746
  return $element;
747
}
748

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
924
  $tree = $trees[$tree_cid];
925

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

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

    
950
  return $tree;
951
}
952

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

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

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

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

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

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

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

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

    
1023
  return $tree;
1024
}
1025

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

    
1045
  if (!is_numeric($mlid)) {
1046
    return FALSE;
1047
  }
1048

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

    
1057
  return $cache[$mlid];
1058
}
1059

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

    
1079
  if (!is_numeric($mlid)) {
1080
    return FALSE;
1081
  }
1082

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

    
1091
  return $cache[$mlid];
1092
}
1093

    
1094
function _token_menu_link_translate(&$item) {
1095
  $map = array();
1096

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

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

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

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

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

    
1136
  return $map;
1137
}
1138

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

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

    
1157
  return $names[$name];
1158
}
1159

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

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

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

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

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

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

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

    
1226
  if (!is_numeric($mlid)) {
1227
    return array();
1228
  }
1229

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

    
1239
  return $cache[$mlid];
1240
}
1241

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

    
1245
  if (!is_numeric($tid)) {
1246
    return array();
1247
  }
1248

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

    
1259
  return $cache[$tid];
1260
}
1261

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

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

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

    
1293
    $cache[$node->nid] = $mlid;
1294
  }
1295

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