menu_token.module 19.5 KB
Newer Older
fubhy's avatar
fubhy committed
1 2 3 4
<?php

/**
 * @file
5
 * Main module file for the Menu Token module.
fubhy's avatar
fubhy committed
6 7 8
 */

/**
9
 * Implements hook_theme().
fubhy's avatar
fubhy committed
10 11 12 13 14 15 16 17 18 19 20 21
 */
function menu_token_theme() {
  return array(
    'menu_token_uses_tokens' => array(),
  );
}

/**
 * Appends the "uses tokens" label to links on the admin menu links overview
 * form.
 */
function theme_menu_token_uses_tokens() {
22 23
  drupal_add_css(drupal_get_path('module', 'menu_token') . '/menu_token.css');
  return ' <span class="uses-tokens">' . t('uses tokens') . '</span>';
fubhy's avatar
fubhy committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
}

/**
 * Implements hook_ctools_plugin_type().
 */
function menu_token_ctools_plugin_type() {
  return array(
    'plugins' => array(
      'cache' => TRUE,
      'use hooks' => TRUE,
      'classes' => array('handler'),
    ),
  );
}

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

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

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

  return $plugins;
fubhy's avatar
fubhy committed
86 87
}

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

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

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

    // Load data objects used when replacing link.
fubhy's avatar
fubhy committed
105
    if (isset($item['options']['menu_token_data'])) {
106 107
      foreach ($item['options']['menu_token_data'] as $type => $values) {
        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;
fubhy's avatar
fubhy committed
111
          }
fubhy's avatar
fubhy committed
112 113 114
        }
      }
    }
fubhy's avatar
fubhy committed
115

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

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

122 123
    // If item is generated by admin menu module, tokens should not be replaced
    // 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);
fubhy's avatar
fubhy committed
126

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

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

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

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

    // Load menu item and check access.
    if ($menu_item = menu_get_item($url)) {
fubhy's avatar
fubhy committed
169 170 171 172 173 174 175 176 177
      $item['access'] = $menu_item['access'];
      return;
    }

    $item['access'] = FALSE;
  }
}

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

/**
 * Returns TRUE if 'menu_links_features_export_render' is in the callstack.
 */
function _menu_token_is_called_from_features() {
  $called = &drupal_static(__FUNCTION__);
  if (!isset($called)) {
194 195
    if (module_exists('features')) {
      // Save memory in the debug_backtrace() function when possible
196
      if (version_compare(PHP_VERSION, '5.3.6', '>=')) {
197 198 199 200 201
        $callstack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
      }
      else {
        $callstack = debug_backtrace();
      }
202 203 204 205 206
      foreach($callstack as $function) {
        $called = ($function['function'] == 'menu_links_features_export_render');
        if ($called) {
          break;
        }
207 208
      }
    }
209 210 211
    else {
      $called = FALSE;
    }
fubhy's avatar
fubhy committed
212
  }
213
  return !$called;
214
}
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318

/**
 * Retrieves the handler of a menu token plugin.
 *
 * @param $name
 *   The name of a plugin.
 *
 * @return
 *   A menu_token_handler object that represents the handler of the plugin
 *   defined by $name or FALSE if no plugin named $name exists.
 */
function menu_token_get_handler($name) {
  $handlers = &drupal_static(__FUNCTION__);

  if (!isset($handlers[$name])) {
    if ($plugin = menu_token_get_plugin($name)) {
      $handlers[$name] = new $plugin['class']($plugin);
    }
  }

  if (isset($handlers[$name])) {
    return $handlers[$name];
  }

  return FALSE;
}

/**
 * Retrieves a menu token plugin.
 *
 * @param $name
 *   The name of a plugin.
 *
 * @return
 *   An array containing information about the plugin as returned by the ctools
 *   plugin API.
 */
function menu_token_get_plugin($name) {
  $plugins = _menu_token_plugin_info()->plugins;

  if (isset($plugins[$name])) {
    return $plugins[$name];
  }

  return FALSE;
}

/**
 * Retrieves a list of all available menu token plugins.
 *
 * @return
 *   An array containing all available plugins.
 */
function menu_token_get_plugins() {
  return _menu_token_plugin_info()->plugins;
}

/**
 * Retrieves a list of all token types that are covered by the available menu
 * token plugins.
 *
 * @return
 *   An array containing all token types covered by menu token plugins.
 */
function menu_token_get_plugin_types() {
  return _menu_token_plugin_info()->types;
}

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

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

    $cache = (object) array(
      'plugins' => array(),
      'types' => array(),
    );

    $info = token_get_info();

    foreach (ctools_get_plugins('menu_token', 'plugins') as $plugin) {
      if (isset($info['types'][$plugin['type']]) && $class = ctools_plugin_get_class($plugin, 'handler')) {
        $cache->plugins[$plugin['name']] = $plugin;
        $cache->plugins[$plugin['name']]['class'] = $class;
        $cache->types[$plugin['type']][$plugin['name']] = $plugin['label'];
      }
    }
  }

  return $cache;
}

/**
 * Implementation of hook_form_FORM_ID_alter().
 */
function menu_token_form_menu_edit_item_alter(&$form, &$form_state) {
  if ($form['module']['#value'] == 'menu') {
    $types = menu_token_get_plugin_types();
    $options = $form['options']['#value'];

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 322 323 324
      // If the input token is current-user, then return it to the fake path.
      if (strpos($options['menu_token_link_path'], 'current-user') !== FALSE) {
        $form['link_path']['#default_value'] = 'menutoken/' . uniqid();
      }
325 326
      $form['menu_token_uuid'] = array(
        '#type' => 'hidden',
327
        '#value' => $form['link_path']['#default_value'],
328
      );
329 330 331 332 333 334 335 336
      $form['link_path']['#default_value'] = $options['menu_token_link_path'];
    }

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

    $form['menu_token_enabled'] = array(
      '#type' => 'checkbox',
337 338
      '#title' => t('<strong>Use tokens</strong> in title and in path.'),
      '#description' => t('Active this option in order to use Menu token.'),
339
      '#default_value' => isset($options['menu_token_link_path']),
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
      '#weight' => -3,
    );

    $form['menu_token_options'] = array(
      '#type' => 'fieldset',
      '#title' => t('Menu Token options'),
      '#collapsible' => TRUE,
      '#weight' => -2,
      '#states' => array(
        'visible' => array(
          ':input[name="menu_token_enabled"]' => array('checked' => TRUE),
        ),
      ),
    );

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

      if (isset($form_state['values']['menu_token_type_' . $type])) {
        $default = $form_state['values']['menu_token_type_' . $type];
      }
      elseif (!empty($options['menu_token_data'][$type])) {
        $default = $options['menu_token_data'][$type]['plugin'];
      }

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

      $form['menu_token_options'][$type]['menu_token_type_' . $type] = array(
        '#type' => 'select',
        '#title' => t('Method for') . ' ' . $info['name'],
        '#description' => $info['description'],
        '#options' => array('_none' => t('Disabled')),
375
        '#default_value' => isset($default) && in_array($default, array_keys($items)) ? $default : array('_none'),
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        '#ajax' => array(
          'callback' => 'menu_token_method_callback',
          'wrapper' => 'menu-token-method-options-' . $type,
          'method' => 'replace',
          'effect' => 'fade',
        ),
      );

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

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

      if (isset($default) && $handler = menu_token_get_handler($default)) {
        if ($append = $handler->form_options($options['menu_token_data'][$type]['options'])) {
          $form['menu_token_options'][$type]['menu_token_method_options_wrapper']['menu_token_method_options'] = array(
            '#type' => 'fieldset',
            '#title' => t('Method options'),
            '#collapsible' => TRUE,
          ) + $append;
        }
      }
    }

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

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

    $form['menu_token_replacement_patterns']['patterns'] = array(
      '#theme' => 'token_tree',
      '#token_types' => array_keys($types),
428
      '#dialog' => TRUE,
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    );

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

    foreach (array_keys(menu_token_get_plugins()) as $plugin) {
      if ($handler = menu_token_get_handler($plugin)) {
        $handler->form_alter($form, $form_state);
      }
    }
  }
}

/**
 * Custom validation for form menu_edit_item.
 */
function menu_token_form_menu_edit_item_validate($form, &$form_state) {
447
  $values = $form_state['values'];
448 449
  // If token replacing is enabled and this is a custom menu item.
  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.
fubhy's avatar
fubhy committed
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 454 455 456 457 458 459
    if (!empty($values['menu_token_uuid'])) {
      // If a uuid already exists, dont change it
      form_set_value(array('#parents' => array('link_path')), $values['menu_token_uuid'], $form_state);
    }
    else {
      form_set_value(array('#parents' => array('link_path')), 'menutoken/' . uniqid(), $form_state);
    }
460 461 462 463 464
    foreach (array_keys(menu_token_get_plugin_types()) as $type) {
      if (!empty($values['menu_token_type_' . $type]) && $values['menu_token_type_' . $type] != '_none') {
        $plugin = $values['menu_token_type_' . $type];
        if ($handler = menu_token_get_handler($plugin)) {
          // 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 475 476 477
        }
      }
    }
  }
}

/**
 * Custom submit for form menu_edit_item.
 */
function menu_token_form_menu_edit_item_submit($form, &$form_state) {
  $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 481 482
    // Store the actual path in the options array.
    form_set_value(array('#parents' => array('options', 'menu_token_data')), array(), $form_state);
    form_set_value(array('#parents' => array('options', 'menu_token_options', 'clear')), $values['menu_token_clear'], $form_state);
483 484 485 486
    foreach (array_keys(menu_token_get_plugin_types()) as $type) {
      if (!empty($values['menu_token_type_' . $type]) && $values['menu_token_type_' . $type] != '_none') {
        $plugin = $values['menu_token_type_' . $type];
        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 489
          // Validate the form via the handler.
          if ($output = $handler->form_submit($form, $form_state)) {
490 491
            $output = $values['options']['menu_token_data'][$type]['options'] + $output;
            form_set_value(array('#parents' => array('options', 'menu_token_data', $type, 'options')), $output, $form_state);
492 493 494 495
          }
        }
      }
    }
496 497 498 499
  }
  else {
    foreach (array('menu_token_link_path', 'menu_token_data', 'menu_token_options') as $key) {
      unset($values['options'][$key]);
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    }
  }
}

/**
 * Implementation hook_form_FORM_ID_alter().
 */
function menu_token_form_menu_overview_form_alter(&$form, $form_state) {
  foreach ($form as &$item) {
    if (isset($item['mlid'], $item['#item']['options']) && isset($item['#item']['options']['menu_token_link_path'])) {
      $item['title']['#markup'] .= theme('menu_token_uses_tokens');
    }
  }
}

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

  array_pop($parents);
  array_push($parents, 'menu_token_method_options_wrapper');

  return drupal_array_get_nested_value($form, $parents);
}

/**
 * The menu token handler interface should be implemented by all menu token
 * plugins.
 */
interface menu_token_handler {
  /**
   * You can provide options for your menu token handler via this function.
   * The return value will be appended to the form as soon as the administrator
   * chooses your plugin.
   */
  function form_options($options);

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

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

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

  /**
   * This function is used to load the relevant token replacement object.
   */
  function object_load($options);
}
567 568 569 570 571 572 573 574 575 576 577

/**
 * Implements hook_permission().
 */
function menu_token_permission() {
  return array(
    'administer menu_token' => array(
      'title' => t('Administer Menu Token'),
    ),
  );
}
578 579 580 581 582 583 584

/**
 * Implements hook_menu().
 */
function menu_token_menu() {
  $items = array();

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

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

  return $items;
601
}