Projet

Général

Profil

Paste
Télécharger (19,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / menu_token / menu_token.module @ 7547bb19

1
<?php
2

    
3
/**
4
 * @file
5
 * Main module file for the Menu Token module.
6
 */
7

    
8
/**
9
 * Implements hook_theme().
10
 */
11
function menu_token_theme() {
12
  return array(
13
    'menu_token_uses_tokens' => array(),
14
  );
15
}
16

    
17
/**
18
 * Appends the "uses tokens" label to links on the admin menu links overview
19
 * form.
20
 */
21
function theme_menu_token_uses_tokens() {
22
  drupal_add_css(drupal_get_path('module', 'menu_token') . '/menu_token.css');
23
  return ' <span class="uses-tokens">' . t('uses tokens') . '</span>';
24
}
25

    
26
/**
27
 * Implements hook_ctools_plugin_type().
28
 */
29
function menu_token_ctools_plugin_type() {
30
  return array(
31
    'plugins' => array(
32
      'cache' => TRUE,
33
      'use hooks' => TRUE,
34
      'classes' => array('handler'),
35
    ),
36
  );
37
}
38

    
39
/**
40
 * Implements hook_menu_token_plugins().
41
 */
42
function menu_token_menu_token_plugins() {
43
  $plugins = array();
44
  $entity_info = entity_get_info();
45
  $entities = variable_get('menu_token_entities', drupal_map_assoc(array('node', 'user')));
46

    
47
  foreach ($entities as $entity => $enabled) {
48
    if ($enabled) {
49
      $token_type = $entity_info[$entity]['token type'];
50
      $plugins["{$token_type}_context"] = array(
51
        'type' => $token_type,
52
        'label' => t('@entity_label from context', array('@entity_label' => $entity_info[$entity]['label'])),
53
        'description' => t('Picks a @entity_label from the current context.', array('@entity_label' => $entity_info[$entity]['label'])),
54
        'handler' => array(
55
          'path' => drupal_get_path('module', 'menu_token') . '/plugins',
56
          'file' => 'menu_token_entity_context.inc',
57
          'class' => 'menu_token_entity_context',
58
        ),
59
      );
60

    
61
      $plugins["{$token_type}_random"] = array(
62
        'type' => $token_type,
63
        'label' => t('Random @entity_label', array('@entity_label' => $entity_info[$entity]['label'])),
64
        'description' => t('Picks a random @entity_label from the database.', array('@entity_label' => $entity_info[$entity]['label'])),
65
        'handler' => array(
66
          'path' => drupal_get_path('module', 'menu_token') . '/plugins',
67
          'file' => 'menu_token_entity_random.inc',
68
          'class' => 'menu_token_entity_random',
69
        ),
70
      );
71

    
72
      $plugins["{$token_type}_user_defined"] = array(
73
        'type' => $token_type,
74
        'label' => t('User-defined @entity_label', array('@entity_label' => $entity_info[$entity]['label'])),
75
        'description' => t('Uses a user-defined @entity_label.', array('@entity_label' => $entity_info[$entity]['label'])),
76
        'handler' => array(
77
          'path' => drupal_get_path('module', 'menu_token') . '/plugins',
78
          'file' => 'menu_token_entity_user_defined.inc',
79
          'class' => 'menu_token_entity_user_defined',
80
        ),
81
      );
82
    }
83
  }
84

    
85
  return $plugins;
86
}
87

    
88
/**
89
 * Implements hook_translated_menu_link_alter().
90
 */
91
function menu_token_translated_menu_link_alter(&$item, $map) {
92
  global $menu_admin;
93

    
94
  if (!_menu_token_is_called_from_features()) {
95
    return;
96
  }
97

    
98
  // Check whether we should replace the path.
99
  if (empty($menu_admin) && isset($item['options']['menu_token_link_path'])) {
100
    $info = token_get_info();
101
    $data = array();
102
    $token_entity_mapping = token_get_entity_mapping();
103

    
104
    // Load data objects used when replacing link.
105
    if (isset($item['options']['menu_token_data'])) {
106
      foreach ($item['options']['menu_token_data'] as $type => $values) {
107
        if (!empty($info['types'][$type]) && $handler = menu_token_get_handler($values['plugin'])) {
108
          $values['options']['_type'] = $token_entity_mapping[$type];
109
          if ($object = $handler->object_load($values['options'])) {
110
            $data[$type] = $object;
111
          }
112
        }
113
      }
114
    }
115

    
116
    $options['clear'] = !empty($item['options']['menu_token_options']['clear']) ? TRUE : FALSE;
117
    $options['sanitize'] = FALSE;
118

    
119
    // Store the UUID link path.
120
    $item['options']['menu_token_link_uuid'] = $item['link_path'];
121

    
122
    // If item is generated by admin menu module, tokens should not be replaced
123
    // and indicator that tokens are used should be shown.
124
    $item['title'] = token_replace($item['link_title'], $data, $options);
125
    $url = token_replace($item['options']['menu_token_link_path'], $data, $options);
126

    
127
    // Make sure aliases are proccessed correctly
128
    $url = trim($url, '/');
129
    $url = drupal_get_normal_path($url);
130

    
131
    // Override active trail if showing front page but translated link is not to
132
    // front page.
133
    // NOTE: This relies on any parent of a tokenised menu item having "option"
134
    // flag "alter" set, which is most easily achieved by setting it to use
135
    // token translation but not specifying a token. Otherwise parent does not
136
    // get processed through this function and because its untranslated child
137
    // has an href of <front>, the menu system thinks it is part of the active
138
    // trail to the front page.
139
    if (drupal_is_front_page() && $item['href'] != drupal_get_normal_path(variable_get('site_frontpage', 'node'))) {
140
      $item['in_active_trail'] = FALSE;
141
    }
142

    
143
    // Check whether path is external.
144
    if (url_is_external($url)) {
145
      $item['href'] = $item['link_path'] = $url;
146
      return;
147
    }
148

    
149
    // Split url into parts and save in proper format.
150
    $url_parts = parse_url($url);
151
    $url = $url_parts['path'];
152
    $item['href'] = $item['link_path'] = $item['router_path'] = $url;
153
    if (isset($url_parts['query'])) {
154
      $query = drupal_get_query_array($url_parts['query']);
155
      $item['localized_options']['query'] = $item['options']['query'] = $query;
156
    }
157
    if (isset($url_parts['fragment'])) {
158
      $item['localized_options']['fragment'] = $item['options']['fragment'] = $url_parts['fragment'];
159
    }
160
    if (!isset($item['localized_options'])) {
161
      $item['localized_options'] = array();
162
    }
163
    if ($url == '<front>') {
164
      $url = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
165
    }
166

    
167
    // Load menu item and check access.
168
    if ($menu_item = menu_get_item($url)) {
169
      $item['access'] = $menu_item['access'];
170
      return;
171
    }
172

    
173
    $item['access'] = FALSE;
174
  }
175
}
176

    
177
/**
178
 * Implements hook_menu_link_alter().
179
 */
180
function menu_token_menu_link_alter(&$item) {
181
  if (isset($item['options']['menu_token_link_path'])) {
182
    // Set 'alter' option to use hook_translated_menu_link_alter()
183
    // Only alter if not called from within menu_links_features_export_render
184
    $item['options']['alter'] = _menu_token_is_called_from_features();
185
  }
186
}
187

    
188
/**
189
 * Returns TRUE if 'menu_links_features_export_render' is in the callstack.
190
 */
191
function _menu_token_is_called_from_features() {
192
  $called = &drupal_static(__FUNCTION__);
193
  if (!isset($called)) {
194
    if (module_exists('features')) {
195
      // Save memory in the debug_backtrace() function when possible
196
      if (version_compare(PHP_VERSION, '5.3.6', '>=')) {
197
        $callstack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
198
      }
199
      else {
200
        $callstack = debug_backtrace();
201
      }
202
      foreach($callstack as $function) {
203
        $called = ($function['function'] == 'menu_links_features_export_render');
204
        if ($called) {
205
          break;
206
        }
207
      }
208
    }
209
    else {
210
      $called = FALSE;
211
    }
212
  }
213
  return !$called;
214
}
215

    
216
/**
217
 * Retrieves the handler of a menu token plugin.
218
 *
219
 * @param $name
220
 *   The name of a plugin.
221
 *
222
 * @return
223
 *   A menu_token_handler object that represents the handler of the plugin
224
 *   defined by $name or FALSE if no plugin named $name exists.
225
 */
226
function menu_token_get_handler($name) {
227
  $handlers = &drupal_static(__FUNCTION__);
228

    
229
  if (!isset($handlers[$name])) {
230
    if ($plugin = menu_token_get_plugin($name)) {
231
      $handlers[$name] = new $plugin['class']($plugin);
232
    }
233
  }
234

    
235
  if (isset($handlers[$name])) {
236
    return $handlers[$name];
237
  }
238

    
239
  return FALSE;
240
}
241

    
242
/**
243
 * Retrieves a menu token plugin.
244
 *
245
 * @param $name
246
 *   The name of a plugin.
247
 *
248
 * @return
249
 *   An array containing information about the plugin as returned by the ctools
250
 *   plugin API.
251
 */
252
function menu_token_get_plugin($name) {
253
  $plugins = _menu_token_plugin_info()->plugins;
254

    
255
  if (isset($plugins[$name])) {
256
    return $plugins[$name];
257
  }
258

    
259
  return FALSE;
260
}
261

    
262
/**
263
 * Retrieves a list of all available menu token plugins.
264
 *
265
 * @return
266
 *   An array containing all available plugins.
267
 */
268
function menu_token_get_plugins() {
269
  return _menu_token_plugin_info()->plugins;
270
}
271

    
272
/**
273
 * Retrieves a list of all token types that are covered by the available menu
274
 * token plugins.
275
 *
276
 * @return
277
 *   An array containing all token types covered by menu token plugins.
278
 */
279
function menu_token_get_plugin_types() {
280
  return _menu_token_plugin_info()->types;
281
}
282

    
283
/**
284
 * Builds and returns information about the menu token plugins and their types.
285
 */
286
function _menu_token_plugin_info() {
287
  $cache = &drupal_static(__FUNCTION__);
288

    
289
  if (!isset($cache)) {
290
    ctools_include('plugins');
291

    
292
    $cache = (object) array(
293
      'plugins' => array(),
294
      'types' => array(),
295
    );
296

    
297
    $info = token_get_info();
298

    
299
    foreach (ctools_get_plugins('menu_token', 'plugins') as $plugin) {
300
      if (isset($info['types'][$plugin['type']]) && $class = ctools_plugin_get_class($plugin, 'handler')) {
301
        $cache->plugins[$plugin['name']] = $plugin;
302
        $cache->plugins[$plugin['name']]['class'] = $class;
303
        $cache->types[$plugin['type']][$plugin['name']] = $plugin['label'];
304
      }
305
    }
306
  }
307

    
308
  return $cache;
309
}
310

    
311
/**
312
 * Implementation of hook_form_FORM_ID_alter().
313
 */
314
function menu_token_form_menu_edit_item_alter(&$form, &$form_state) {
315
  if ($form['module']['#value'] == 'menu') {
316
    $types = menu_token_get_plugin_types();
317
    $options = $form['options']['#value'];
318

    
319
    // Replace fake path (/menutoken/ouruid) with user inputed one.
320
    if (!empty($options['menu_token_link_path']) && !empty($options['menu_token_link_uuid'])) {
321
      // If the input token is current-user, then return it to the fake path.
322
      if (strpos($options['menu_token_link_path'], 'current-user') !== FALSE) {
323
        $form['link_path']['#default_value'] = 'menutoken/' . uniqid();
324
      }
325
      $form['menu_token_uuid'] = array(
326
        '#type' => 'hidden',
327
        '#value' => $form['link_path']['#default_value'],
328
      );
329
      $form['link_path']['#default_value'] = $options['menu_token_link_path'];
330
    }
331

    
332
    $form['link_title']['#weight'] = -5;
333
    $form['link_path']['#weight'] = -4;
334

    
335
    $form['menu_token_enabled'] = array(
336
      '#type' => 'checkbox',
337
      '#title' => t('<strong>Use tokens</strong> in title and in path.'),
338
      '#description' => t('Active this option in order to use Menu token.'),
339
      '#default_value' => isset($options['menu_token_link_path']),
340
      '#weight' => -3,
341
    );
342

    
343
    $form['menu_token_options'] = array(
344
      '#type' => 'fieldset',
345
      '#title' => t('Menu Token options'),
346
      '#collapsible' => TRUE,
347
      '#weight' => -2,
348
      '#states' => array(
349
        'visible' => array(
350
          ':input[name="menu_token_enabled"]' => array('checked' => TRUE),
351
        ),
352
      ),
353
    );
354

    
355
    foreach ($types as $type => $items) {
356
      $info = token_get_info($type);
357
      $default = NULL;
358

    
359
      if (isset($form_state['values']['menu_token_type_' . $type])) {
360
        $default = $form_state['values']['menu_token_type_' . $type];
361
      }
362
      elseif (!empty($options['menu_token_data'][$type])) {
363
        $default = $options['menu_token_data'][$type]['plugin'];
364
      }
365

    
366
      $form['menu_token_options'][$type] = array(
367
        '#type' => 'container',
368
      );
369

    
370
      $form['menu_token_options'][$type]['menu_token_type_' . $type] = array(
371
        '#type' => 'select',
372
        '#title' => t('Method for') . ' ' . $info['name'],
373
        '#description' => $info['description'],
374
        '#options' => array('_none' => t('Disabled')),
375
        '#default_value' => isset($default) && in_array($default, array_keys($items)) ? $default : array('_none'),
376
        '#ajax' => array(
377
          'callback' => 'menu_token_method_callback',
378
          'wrapper' => 'menu-token-method-options-' . $type,
379
          'method' => 'replace',
380
          'effect' => 'fade',
381
        ),
382
      );
383

    
384
      foreach ($items as $name => $label) {
385
        $form['menu_token_options'][$type]['menu_token_type_' . $type]['#options'][$name] = $label;
386
      }
387

    
388
      $form['menu_token_options'][$type]['menu_token_method_options_wrapper'] = array(
389
        '#type' => 'container',
390
        '#prefix' => '<div id="menu-token-method-options-' . $type . '">',
391
        '#suffix' => '</div>',
392
      );
393

    
394
      if (isset($default) && $handler = menu_token_get_handler($default)) {
395
        if ($append = $handler->form_options($options['menu_token_data'][$type]['options'])) {
396
          $form['menu_token_options'][$type]['menu_token_method_options_wrapper']['menu_token_method_options'] = array(
397
            '#type' => 'fieldset',
398
            '#title' => t('Method options'),
399
            '#collapsible' => TRUE,
400
          ) + $append;
401
        }
402
      }
403
    }
404

    
405
    $form['menu_token_options']['menu_token_clear'] = array(
406
      '#type' => 'checkbox',
407
      '#title' => t('Remove token if replacement is not present'),
408
      '#description' => t('If the replacement token is not available on the page being viewed, the token will be removed if checked.'),
409
      '#default_value' => isset($options['menu_token_options']['clear']) ? $options['menu_token_options']['clear'] : '',
410
    );
411

    
412
    // Create new fieldset.
413
    $form['menu_token_replacement_patterns'] = array(
414
      '#type' => 'fieldset',
415
      '#title' => t('Replacement patterns'),
416
      '#collapsible' => FALSE,
417
      '#weight' => -1,
418
      '#states' => array(
419
        'visible' => array(
420
          ':input[name="menu_token_enabled"]' => array('checked' => TRUE),
421
        ),
422
      ),
423
    );
424

    
425
    $form['menu_token_replacement_patterns']['patterns'] = array(
426
      '#theme' => 'token_tree',
427
      '#token_types' => array_keys($types),
428
      '#dialog' => TRUE,
429
    );
430

    
431
    // Add custom validation and submit functions.
432
    array_unshift($form['#validate'], 'menu_token_form_menu_edit_item_validate');
433
    array_unshift($form['#submit'], 'menu_token_form_menu_edit_item_submit');
434

    
435
    foreach (array_keys(menu_token_get_plugins()) as $plugin) {
436
      if ($handler = menu_token_get_handler($plugin)) {
437
        $handler->form_alter($form, $form_state);
438
      }
439
    }
440
  }
441
}
442

    
443
/**
444
 * Custom validation for form menu_edit_item.
445
 */
446
function menu_token_form_menu_edit_item_validate($form, &$form_state) {
447
  $values = $form_state['values'];
448
  // If token replacing is enabled and this is a custom menu item.
449
  if ($values['module'] == 'menu' && !empty($values['menu_token_enabled'])) {
450
    // Substitute link_path with our own unique menu path. This will make sure features will export our menu items.
451
    form_set_value(array('#parents' => array('options', 'menu_token_link_path')), $values['link_path'], $form_state);
452
    form_set_value(array('#parents' => array('link_path')), '<front>', $form_state);
453
    if (!empty($values['menu_token_uuid'])) {
454
      // If a uuid already exists, dont change it
455
      form_set_value(array('#parents' => array('link_path')), $values['menu_token_uuid'], $form_state);
456
    }
457
    else {
458
      form_set_value(array('#parents' => array('link_path')), 'menutoken/' . uniqid(), $form_state);
459
    }
460
    foreach (array_keys(menu_token_get_plugin_types()) as $type) {
461
      if (!empty($values['menu_token_type_' . $type]) && $values['menu_token_type_' . $type] != '_none') {
462
        $plugin = $values['menu_token_type_' . $type];
463
        if ($handler = menu_token_get_handler($plugin)) {
464
          // Validate the form via the handler.
465
          $form_state['_menu_token_entity_type'] = $type;
466
          $handler->form_validate($form, $form_state);
467
        }
468
      }
469
    }
470
  }
471
}
472

    
473
/**
474
 * Custom submit for form menu_edit_item.
475
 */
476
function menu_token_form_menu_edit_item_submit($form, &$form_state) {
477
  $values = &$form_state['values'];
478
  // If token replacing is enabled and this is a custom menu item
479
  if ($values['module'] == 'menu' && !empty($values['menu_token_enabled'])) {
480
    // Store the actual path in the options array.
481
    form_set_value(array('#parents' => array('options', 'menu_token_data')), array(), $form_state);
482
    form_set_value(array('#parents' => array('options', 'menu_token_options', 'clear')), $values['menu_token_clear'], $form_state);
483
    foreach (array_keys(menu_token_get_plugin_types()) as $type) {
484
      if (!empty($values['menu_token_type_' . $type]) && $values['menu_token_type_' . $type] != '_none') {
485
        $plugin = $values['menu_token_type_' . $type];
486
        if ($handler = menu_token_get_handler($plugin)) {
487
          form_set_value(array('#parents' => array('options', 'menu_token_data', $type)), array('type' => $type, 'plugin' => $plugin, 'options' => array()), $form_state);
488
          // Validate the form via the handler.
489
          if ($output = $handler->form_submit($form, $form_state)) {
490
            $output = $values['options']['menu_token_data'][$type]['options'] + $output;
491
            form_set_value(array('#parents' => array('options', 'menu_token_data', $type, 'options')), $output, $form_state);
492
          }
493
        }
494
      }
495
    }
496
  }
497
  else {
498
    foreach (array('menu_token_link_path', 'menu_token_data', 'menu_token_options') as $key) {
499
      unset($values['options'][$key]);
500
    }
501
  }
502
}
503

    
504
/**
505
 * Implementation hook_form_FORM_ID_alter().
506
 */
507
function menu_token_form_menu_overview_form_alter(&$form, $form_state) {
508
  foreach ($form as &$item) {
509
    if (isset($item['mlid'], $item['#item']['options']) && isset($item['#item']['options']['menu_token_link_path'])) {
510
      $item['title']['#markup'] .= theme('menu_token_uses_tokens');
511
    }
512
  }
513
}
514

    
515
/**
516
 * Ajax callback for the method select dropdown.
517
 */
518
function menu_token_method_callback($form, $form_state) {
519
  $parents = $form_state['triggering_element']['#array_parents'];
520

    
521
  array_pop($parents);
522
  array_push($parents, 'menu_token_method_options_wrapper');
523

    
524
  return drupal_array_get_nested_value($form, $parents);
525
}
526

    
527
/**
528
 * The menu token handler interface should be implemented by all menu token
529
 * plugins.
530
 */
531
interface menu_token_handler {
532
  /**
533
   * You can provide options for your menu token handler via this function.
534
   * The return value will be appended to the form as soon as the administrator
535
   * chooses your plugin.
536
   */
537
  function form_options($options);
538

    
539
  /**
540
   * This function allows your plugin to act upon form submission. The return
541
   * value will be added to the $options array and thus should be an array
542
   * itself.
543
   *
544
   * Note: Only invoked for selected plugins.
545
   */
546
  function form_submit($form, &$form_state);
547

    
548
  /**
549
   * This function allows your plugin to act upon form validation. The return
550
   * value will be added to the $options array and thus should be an array
551
   * itself.
552
   *
553
   * Note: Only invoked for selected plugins.
554
   */
555
  function form_validate($form, &$form_state);
556

    
557
  /**
558
   * You can alter the menu item administration form with this function.
559
   */
560
  function form_alter(&$form, &$form_state);
561

    
562
  /**
563
   * This function is used to load the relevant token replacement object.
564
   */
565
  function object_load($options);
566
}
567

    
568
/**
569
 * Implements hook_permission().
570
 */
571
function menu_token_permission() {
572
  return array(
573
    'administer menu_token' => array(
574
      'title' => t('Administer Menu Token'),
575
    ),
576
  );
577
}
578

    
579
/**
580
 * Implements hook_menu().
581
 */
582
function menu_token_menu() {
583
  $items = array();
584

    
585
  $items['menutoken/%'] = array(
586
    'title' => "Dummy Menu Token item",
587
    'access callback' => TRUE,
588
    'page callback' => 'theme_menu_token_uses_tokens',
589
  );
590

    
591
  $items['admin/config/menu_token'] = array(
592
    'title' => 'Menu Token',
593
    'description' => 'Configure the Menu Token module.',
594
    'page callback' => 'drupal_get_form',
595
    'page arguments' => array('menu_token_settings_form'),
596
    'access arguments' => array('administer menu_token'),
597
    'file' => 'menu_token.admin.inc',
598
  );
599

    
600
  return $items;
601
}