Projet

Général

Profil

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

root / drupal7 / sites / all / modules / token / token.module @ 76df55b7

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
    $element['#description'] = filter_xss_admin(token_replace($context['instance']['description']));
278
  }
279
}
280

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

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

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

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

    
332
/**
333
 * Implements hook_field_create_instance().
334
 */
335
function token_field_create_instance($instance) {
336
  token_clear_cache();
337
}
338

    
339
/**
340
 * Implements hook_field_update_instance().
341
 */
342
function token_field_update_instance($instance) {
343
  token_clear_cache();
344
}
345

    
346
/**
347
 * Implements hook_field_delete_instance().
348
 */
349
function token_field_delete_instance($instance) {
350
  token_clear_cache();
351
}
352

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

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

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

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

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

    
429
    if (!empty($info[$entity_type]['token type'])) {
430
      // If the entity's token type is already defined, great!
431
      continue;
432
    }
433

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

    
449
/**
450
 * Implements hook_module_implements_alter().
451
 *
452
 * Adds missing token support for core modules.
453
 */
454
function token_module_implements_alter(&$implementations, $hook) {
455
  module_load_include('inc', 'token', 'token.tokens');
456

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

    
470
/**
471
 * Implements hook_flush_caches().
472
 */
473
function token_flush_caches() {
474
  if (db_table_exists('cache_token')) {
475
    return array('cache_token');
476
  }
477
}
478

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

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

    
506
  if (empty($token_info)) {
507
    $cid = "info:{$language->language}";
508

    
509
    if ($cache = cache_get($cid, 'cache_token')) {
510
      $token_info = $cache->data;
511
    }
512
    else {
513
      $token_info = token_info();
514

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

    
532
      // Pre-sort tokens.
533
      uasort($token_info['types'], 'token_asort_tokens');
534
      foreach (array_keys($token_info['tokens']) as $type) {
535
        uasort($token_info['tokens'][$type], 'token_asort_tokens');
536
      }
537

    
538
      // Store info in cache for future use.
539
      cache_set($cid, $token_info, 'cache_token');
540
    }
541
  }
542

    
543
  if (isset($token_type) && isset($token)) {
544
    return isset($token_info['tokens'][$token_type][$token]) ? $token_info['tokens'][$token_type][$token] : NULL;
545
  }
546
  elseif (isset($token_type)) {
547
    return isset($token_info['types'][$token_type]) ? $token_info['types'][$token_type] : NULL;
548
  }
549
  else {
550
    return $token_info;
551
  }
552
}
553

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

    
571
/**
572
 * uasort() callback to sort tokens by the 'name' property.
573
 */
574
function token_asort_tokens($token_a, $token_b) {
575
  return strnatcmp($token_a['name'], $token_b['name']);
576
}
577

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

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

    
598
  return $global_types;
599
}
600

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

    
623
  $invalid_tokens = array();
624
  $value_tokens = is_string($value) ? token_scan($value) : $value;
625

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

    
637
  array_unique($invalid_tokens);
638
  return $invalid_tokens;
639
}
640

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

    
655
  foreach ($tokens as $token => $full_token) {
656
    if (isset($token_info['tokens'][$type][$token])) {
657
      continue;
658
    }
659

    
660
    // Split token up if it has chains.
661
    $parts = explode(':', $token, 2);
662

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

    
685
  return $invalid_tokens;
686
}
687

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

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

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

    
720
  // Validate if an element must have a minimum number of tokens.
721
  if (isset($element['#min_tokens']) && count($tokens) < $element['#min_tokens']) {
722
    // @todo Change this error message to include the minimum number.
723
    $error = format_plural($element['#min_tokens'], 'The %element-title cannot contain fewer than one token.', 'The %element-title must contain at least @count tokens.', array('%element-title' => $title));
724
    form_error($element, $error);
725
  }
726

    
727
  // Validate if an element must have a maximum number of tokens.
728
  if (isset($element['#max_tokens']) && count($tokens) > $element['#max_tokens']) {
729
    // @todo Change this error message to include the maximum number.
730
    $error = format_plural($element['#max_tokens'], 'The %element-title must contain as most one token.', 'The %element-title must contain at most @count tokens.', array('%element-title' => $title));
731
    form_error($element, $error);
732
  }
733

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

    
742
  return $element;
743
}
744

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
920
  $tree = $trees[$tree_cid];
921

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

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

    
946
  return $tree;
947
}
948

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

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

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

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

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

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

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

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

    
1019
  return $tree;
1020
}
1021

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

    
1041
  if (!is_numeric($mlid)) {
1042
    return FALSE;
1043
  }
1044

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

    
1053
  return $cache[$mlid];
1054
}
1055

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

    
1075
  if (!is_numeric($mlid)) {
1076
    return FALSE;
1077
  }
1078

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

    
1087
  return $cache[$mlid];
1088
}
1089

    
1090
function _token_menu_link_translate(&$item) {
1091
  $map = array();
1092

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

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

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

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

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

    
1132
  return $map;
1133
}
1134

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

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

    
1153
  return $names[$name];
1154
}
1155

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

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

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

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

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

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

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

    
1222
  if (!is_numeric($mlid)) {
1223
    return array();
1224
  }
1225

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

    
1235
  return $cache[$mlid];
1236
}
1237

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

    
1241
  if (!is_numeric($tid)) {
1242
    return array();
1243
  }
1244

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

    
1255
  return $cache[$tid];
1256
}
1257

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

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

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

    
1289
    $cache[$node->nid] = $mlid;
1290
  }
1291

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