Projet

Général

Profil

Paste
Télécharger (18,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / menu_token / menu_token.module @ 87dbc3bf

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
      $plugins["{$entity}_context"] = array(
50
        'type' => $entity,
51
        'label' => t('@entity_label from context', array('@entity_label' => $entity_info[$entity]['label'])),
52
        'description' => t('Picks a @entity_label from the current context.', array('@entity_label' => $entity_info[$entity]['label'])),
53
        'handler' => array(
54
          'path' => drupal_get_path('module', 'menu_token') . '/plugins',
55
          'file' => 'menu_token_entity_context.inc',
56
          'class' => 'menu_token_entity_context',
57
        ),
58
      );
59

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

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

    
84
  return $plugins;
85
}
86

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

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

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

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

    
114
    $options['clear'] = !empty($item['options']['menu_token_options']['clear']) ? TRUE : FALSE;
115

    
116
    // If item is generated by admin menu module, tokens should not be replaced
117
    // and indicator that tokens are used should be shown.
118
    $item['title'] = token_replace($item['title'], $data, $options);
119
    $url = token_replace($item['options']['menu_token_link_path'], $data, $options);
120

    
121
    // Make sure aliases are proccessed correctly
122
    $url = trim($url, '/');
123
    $url = drupal_get_normal_path($url);
124

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

    
137
    // Check whether path is external.
138
    if (url_is_external($url)) {
139
      $item['href'] = $item['link_path'] = $url;
140
      return;
141
    }
142

    
143
    // Split url into parts and save in proper format.
144
    $url_parts = parse_url($url);
145
    $url = $url_parts['path'];
146
    $item['href'] = $item['link_path'] = $item['router_path'] = $url;
147
    if (isset($url_parts['query'])) {
148
      $query = drupal_get_query_array($url_parts['query']);
149
      $item['localized_options']['query'] = $item['options']['query'] = $query;
150
    }
151
    if (isset($url_parts['fragment'])) {
152
      $item['localized_options']['fragment'] = $item['options']['fragment'] = $url_parts['fragment'];
153
    }
154

    
155
    if ($url == '<front>') {
156
      $url = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
157
    }
158

    
159
    // Load menu item and check access.
160
    if ($menu_item = menu_get_item($url)) {
161
      $item['access'] = $menu_item['access'];
162
      return;
163
    }
164

    
165
    $item['access'] = FALSE;
166
  }
167
}
168

    
169
/**
170
 * Implements hook_menu_link_alter().
171
 */
172
function menu_token_menu_link_alter(&$item) {
173
  if (isset($item['options']['menu_token_link_path'])) {
174
    // Set 'alter' option to use hook_translated_menu_link_alter()
175
    // Only alter if not called from within menu_links_features_export_render
176
    $item['options']['alter'] = _menu_token_is_called_from_features();
177
  }
178
}
179

    
180
/**
181
 * Returns TRUE if 'menu_links_features_export_render' is in the callstack.
182
 */
183
function _menu_token_is_called_from_features() {
184
  $called = &drupal_static(__FUNCTION__);
185
  if (!isset($called)) {
186
    if (module_exists('features')) {
187
      // Save memory in the debug_backtrace() function when possible
188
      $options = (version_compare(PHP_VERSION, '5.3.6', '>=') ? DEBUG_BACKTRACE_IGNORE_ARGS : NULL);
189
      $callstack = debug_backtrace($options);
190
      foreach($callstack as $function) {
191
        $called = ($function['function'] == 'menu_links_features_export_render');
192
        if ($called) {
193
          break;
194
        }
195
      }
196
    }
197
    else {
198
      $called = FALSE;
199
    }
200
  }
201
  return !$called;
202
}
203

    
204
/**
205
 * Retrieves the handler of a menu token plugin.
206
 *
207
 * @param $name
208
 *   The name of a plugin.
209
 *
210
 * @return
211
 *   A menu_token_handler object that represents the handler of the plugin
212
 *   defined by $name or FALSE if no plugin named $name exists.
213
 */
214
function menu_token_get_handler($name) {
215
  $handlers = &drupal_static(__FUNCTION__);
216

    
217
  if (!isset($handlers[$name])) {
218
    if ($plugin = menu_token_get_plugin($name)) {
219
      $handlers[$name] = new $plugin['class']($plugin);
220
    }
221
  }
222

    
223
  if (isset($handlers[$name])) {
224
    return $handlers[$name];
225
  }
226

    
227
  return FALSE;
228
}
229

    
230
/**
231
 * Retrieves a menu token plugin.
232
 *
233
 * @param $name
234
 *   The name of a plugin.
235
 *
236
 * @return
237
 *   An array containing information about the plugin as returned by the ctools
238
 *   plugin API.
239
 */
240
function menu_token_get_plugin($name) {
241
  $plugins = _menu_token_plugin_info()->plugins;
242

    
243
  if (isset($plugins[$name])) {
244
    return $plugins[$name];
245
  }
246

    
247
  return FALSE;
248
}
249

    
250
/**
251
 * Retrieves a list of all available menu token plugins.
252
 *
253
 * @return
254
 *   An array containing all available plugins.
255
 */
256
function menu_token_get_plugins() {
257
  return _menu_token_plugin_info()->plugins;
258
}
259

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

    
271
/**
272
 * Builds and returns information about the menu token plugins and their types.
273
 */
274
function _menu_token_plugin_info() {
275
  $cache = &drupal_static(__FUNCTION__);
276

    
277
  if (!isset($cache)) {
278
    ctools_include('plugins');
279

    
280
    $cache = (object) array(
281
      'plugins' => array(),
282
      'types' => array(),
283
    );
284

    
285
    $info = token_get_info();
286

    
287
    foreach (ctools_get_plugins('menu_token', 'plugins') as $plugin) {
288
      if (isset($info['types'][$plugin['type']]) && $class = ctools_plugin_get_class($plugin, 'handler')) {
289
        $cache->plugins[$plugin['name']] = $plugin;
290
        $cache->plugins[$plugin['name']]['class'] = $class;
291
        $cache->types[$plugin['type']][$plugin['name']] = $plugin['label'];
292
      }
293
    }
294
  }
295

    
296
  return $cache;
297
}
298

    
299
/**
300
 * Implementation of hook_form_FORM_ID_alter().
301
 */
302
function menu_token_form_menu_edit_item_alter(&$form, &$form_state) {
303
  if ($form['module']['#value'] == 'menu') {
304
    $types = menu_token_get_plugin_types();
305
    $options = $form['options']['#value'];
306

    
307
    // Replace fake path (/menutoken/ouruid) with user inputed one.
308
    if (!empty($options['menu_token_link_path'])) {
309
      $form['menu_token_uuid'] = array(
310
        '#type' => 'hidden',
311
        '#value' => $form['link_path']['#default_value'],
312
      );
313
      $form['link_path']['#default_value'] = $options['menu_token_link_path'];
314
    }
315

    
316
    $form['link_title']['#weight'] = -5;
317
    $form['link_path']['#weight'] = -4;
318

    
319
    $form['menu_token_enabled'] = array(
320
      '#type' => 'checkbox',
321
      '#title' => t('<strong>Use tokens</strong> in title and in path.'),
322
      '#description' => t('Active this option in order to use Menu token.'),
323
      '#default_value' => isset($options['menu_token_link_path']),
324
      '#weight' => -3,
325
    );
326

    
327
    $form['menu_token_options'] = array(
328
      '#type' => 'fieldset',
329
      '#title' => t('Menu Token options'),
330
      '#collapsible' => TRUE,
331
      '#weight' => -2,
332
      '#states' => array(
333
        'visible' => array(
334
          ':input[name="menu_token_enabled"]' => array('checked' => TRUE),
335
        ),
336
      ),
337
    );
338

    
339
    foreach ($types as $type => $items) {
340
      $info = token_get_info($type);
341
      $default = NULL;
342

    
343
      if (isset($form_state['values']['menu_token_type_' . $type])) {
344
        $default = $form_state['values']['menu_token_type_' . $type];
345
      }
346
      elseif (!empty($options['menu_token_data'][$type])) {
347
        $default = $options['menu_token_data'][$type]['plugin'];
348
      }
349

    
350
      $form['menu_token_options'][$type] = array(
351
        '#type' => 'container',
352
      );
353

    
354
      $form['menu_token_options'][$type]['menu_token_type_' . $type] = array(
355
        '#type' => 'select',
356
        '#title' => t('Method for') . ' ' . $info['name'],
357
        '#description' => $info['description'],
358
        '#options' => array('_none' => t('Disabled')),
359
        '#default_value' => isset($default) && in_array($default, array_keys($items)) ? $default : array('_none'),
360
        '#ajax' => array(
361
          'callback' => 'menu_token_method_callback',
362
          'wrapper' => 'menu-token-method-options-' . $type,
363
          'method' => 'replace',
364
          'effect' => 'fade',
365
        ),
366
      );
367

    
368
      foreach ($items as $name => $label) {
369
        $form['menu_token_options'][$type]['menu_token_type_' . $type]['#options'][$name] = $label;
370
      }
371

    
372
      $form['menu_token_options'][$type]['menu_token_method_options_wrapper'] = array(
373
        '#type' => 'container',
374
        '#prefix' => '<div id="menu-token-method-options-' . $type . '">',
375
        '#suffix' => '</div>',
376
      );
377

    
378
      if (isset($default) && $handler = menu_token_get_handler($default)) {
379
        if ($append = $handler->form_options($options['menu_token_data'][$type]['options'])) {
380
          $form['menu_token_options'][$type]['menu_token_method_options_wrapper']['menu_token_method_options'] = array(
381
            '#type' => 'fieldset',
382
            '#title' => t('Method options'),
383
            '#collapsible' => TRUE,
384
          ) + $append;
385
        }
386
      }
387
    }
388

    
389
    $form['menu_token_options']['menu_token_clear'] = array(
390
      '#type' => 'checkbox',
391
      '#title' => t('Remove token if replacement is not present'),
392
      '#description' => t('If the replacement token is not available on the page being viewed, the token will be removed if checked.'),
393
      '#default_value' => isset($options['menu_token_options']['clear']) ? $options['menu_token_options']['clear'] : '',
394
    );
395

    
396
    // Create new fieldset.
397
    $form['menu_token_replacement_patterns'] = array(
398
      '#type' => 'fieldset',
399
      '#title' => t('Replacement patterns'),
400
      '#collapsible' => FALSE,
401
      '#weight' => -1,
402
      '#states' => array(
403
        'visible' => array(
404
          ':input[name="menu_token_enabled"]' => array('checked' => TRUE),
405
        ),
406
      ),
407
    );
408

    
409
    $form['menu_token_replacement_patterns']['patterns'] = array(
410
      '#theme' => 'token_tree',
411
      '#token_types' => array_keys($types),
412
      '#dialog' => TRUE,
413
    );
414

    
415
    // Add custom validation and submit functions.
416
    array_unshift($form['#validate'], 'menu_token_form_menu_edit_item_validate');
417
    array_unshift($form['#submit'], 'menu_token_form_menu_edit_item_submit');
418

    
419
    foreach (array_keys(menu_token_get_plugins()) as $plugin) {
420
      if ($handler = menu_token_get_handler($plugin)) {
421
        $handler->form_alter($form, $form_state);
422
      }
423
    }
424
  }
425
}
426

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

    
457
/**
458
 * Custom submit for form menu_edit_item.
459
 */
460
function menu_token_form_menu_edit_item_submit($form, &$form_state) {
461
  $values = &$form_state['values'];
462
  // If token replacing is enabled and this is a custom menu item
463
  if ($values['module'] == 'menu' && !empty($values['menu_token_enabled'])) {
464
    // Store the actual path in the options array.
465
    form_set_value(array('#parents' => array('options', 'menu_token_data')), array(), $form_state);
466
    form_set_value(array('#parents' => array('options', 'menu_token_options', 'clear')), $values['menu_token_clear'], $form_state);
467
    foreach (array_keys(menu_token_get_plugin_types()) as $type) {
468
      if (!empty($values['menu_token_type_' . $type]) && $values['menu_token_type_' . $type] != '_none') {
469
        $plugin = $values['menu_token_type_' . $type];
470
        if ($handler = menu_token_get_handler($plugin)) {
471
          form_set_value(array('#parents' => array('options', 'menu_token_data', $type)), array('type' => $type, 'plugin' => $plugin, 'options' => array()), $form_state);
472
          // Validate the form via the handler.
473
          if ($output = $handler->form_submit($form, $form_state)) {
474
            $output = $values['options']['menu_token_data'][$type]['options'] + $output;
475
            form_set_value(array('#parents' => array('options', 'menu_token_data', $type, 'options')), $output, $form_state);
476
          }
477
        }
478
      }
479
    }
480
  }
481
  else {
482
    foreach (array('menu_token_link_path', 'menu_token_data', 'menu_token_options') as $key) {
483
      unset($values['options'][$key]);
484
    }
485
  }
486
}
487

    
488
/**
489
 * Implementation hook_form_FORM_ID_alter().
490
 */
491
function menu_token_form_menu_overview_form_alter(&$form, $form_state) {
492
  foreach ($form as &$item) {
493
    if (isset($item['mlid'], $item['#item']['options']) && isset($item['#item']['options']['menu_token_link_path'])) {
494
      $item['title']['#markup'] .= theme('menu_token_uses_tokens');
495
    }
496
  }
497
}
498

    
499
/**
500
 * Ajax callback for the method select dropdown.
501
 */
502
function menu_token_method_callback($form, $form_state) {
503
  $parents = $form_state['triggering_element']['#array_parents'];
504

    
505
  array_pop($parents);
506
  array_push($parents, 'menu_token_method_options_wrapper');
507

    
508
  return drupal_array_get_nested_value($form, $parents);
509
}
510

    
511
/**
512
 * The menu token handler interface should be implemented by all menu token
513
 * plugins.
514
 */
515
interface menu_token_handler {
516
  /**
517
   * You can provide options for your menu token handler via this function.
518
   * The return value will be appended to the form as soon as the administrator
519
   * chooses your plugin.
520
   */
521
  function form_options($options);
522

    
523
  /**
524
   * This function allows your plugin to act upon form submission. The return
525
   * value will be added to the $options array and thus should be an array
526
   * itself.
527
   *
528
   * Note: Only invoked for selected plugins.
529
   */
530
  function form_submit($form, &$form_state);
531

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

    
541
  /**
542
   * You can alter the menu item administration form with this function.
543
   */
544
  function form_alter(&$form, &$form_state);
545

    
546
  /**
547
   * This function is used to load the relevant token replacement object.
548
   */
549
  function object_load($options);
550
}
551

    
552
/**
553
 * Implements hook_permission().
554
 */
555
function menu_token_permission() {
556
  return array(
557
    'administer menu_token' => array(
558
      'title' => t('Administer Menu Token'),
559
    ),
560
  );
561
}
562

    
563
/**
564
 * Implements hook_menu().
565
 */
566
function menu_token_menu() {
567
  $items = array();
568

    
569
  $items['menutoken/%'] = array(
570
    'title' => "Dummy Menu Token item",
571
    'access callback' => TRUE,
572
    'page callback' => 'theme_menu_token_uses_tokens',
573
  );
574

    
575
  $items['admin/config/menu_token'] = array(
576
    'title' => 'Menu Token',
577
    'description' => 'Configure the Menu Token module.',
578
    'page callback' => 'drupal_get_form',
579
    'page arguments' => array('menu_token_settings_form'),
580
    'access arguments' => array('administer menu_token'),
581
    'file' => 'menu_token.admin.inc',
582
  );
583

    
584
  return $items;
585
}