Projet

Général

Profil

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

root / drupal7 / sites / all / modules / menu_token / menu_token.module @ 27370441

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
238
  return FALSE;
239
}
240

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

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

    
258
  return FALSE;
259
}
260

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

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

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

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

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

    
296
    $info = token_get_info();
297

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

    
307
  return $cache;
308
}
309

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

    
318
    // Replace fake path (/menutoken/ouruid) with user inputed one.
319
    if (!empty($options['menu_token_link_path']) && !empty($options['menu_token_link_uuid'])) {
320
      $form['menu_token_uuid'] = array(
321
        '#type' => 'hidden',
322
        '#value' => substr($form['link_path']['#default_value'], 0, 10) == 'menutoken/'
323
                      ? $form['link_path']['#default_value'] : '',
324
      );
325
      $form['link_path']['#default_value'] = $options['menu_token_link_path'];
326
    }
327

    
328
    $form['link_title']['#weight'] = -5;
329
    $form['link_path']['#weight'] = -4;
330

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

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

    
351
    foreach ($types as $type => $items) {
352
      $info = token_get_info($type);
353
      $default = NULL;
354

    
355
      if (isset($form_state['values']['menu_token_type_' . $type])) {
356
        $default = $form_state['values']['menu_token_type_' . $type];
357
      }
358
      elseif (!empty($options['menu_token_data'][$type])) {
359
        $default = $options['menu_token_data'][$type]['plugin'];
360
      }
361

    
362
      $form['menu_token_options'][$type] = array(
363
        '#type' => 'container',
364
      );
365

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

    
380
      foreach ($items as $name => $label) {
381
        $form['menu_token_options'][$type]['menu_token_type_' . $type]['#options'][$name] = $label;
382
      }
383

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

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

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

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

    
421
    $form['menu_token_replacement_patterns']['patterns'] = array(
422
      '#theme' => 'token_tree',
423
      '#token_types' => array_keys($types),
424
      '#dialog' => TRUE,
425
    );
426

    
427
    // Add custom validation and submit functions.
428
    array_unshift($form['#validate'], 'menu_token_form_menu_edit_item_validate');
429
    array_unshift($form['#submit'], 'menu_token_form_menu_edit_item_submit');
430

    
431
    foreach (array_keys(menu_token_get_plugins()) as $plugin) {
432
      if ($handler = menu_token_get_handler($plugin)) {
433
        $handler->form_alter($form, $form_state);
434
      }
435
    }
436
  }
437
}
438

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

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

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

    
511
/**
512
 * Ajax callback for the method select dropdown.
513
 */
514
function menu_token_method_callback($form, $form_state) {
515
  $parents = $form_state['triggering_element']['#array_parents'];
516

    
517
  array_pop($parents);
518
  array_push($parents, 'menu_token_method_options_wrapper');
519

    
520
  return drupal_array_get_nested_value($form, $parents);
521
}
522

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

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

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

    
553
  /**
554
   * You can alter the menu item administration form with this function.
555
   */
556
  function form_alter(&$form, &$form_state);
557

    
558
  /**
559
   * This function is used to load the relevant token replacement object.
560
   */
561
  function object_load($options);
562
}
563

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

    
575
/**
576
 * Implements hook_menu().
577
 */
578
function menu_token_menu() {
579
  $items = array();
580

    
581
  $items['menutoken/%'] = array(
582
    'title' => "Dummy Menu Token item",
583
    'access callback' => TRUE,
584
    'page callback' => 'theme_menu_token_uses_tokens',
585
  );
586

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

    
596
  return $items;
597
}