You are here

menu_token.module in Menu Token 7

Main module file for the Menu Token module.

File

menu_token.module
View source
<?php

/**
 * @file
 * Main module file for the Menu Token module.
 */

/**
 * Implements hook_theme().
 */
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() {
  drupal_add_css(drupal_get_path('module', 'menu_token') . '/menu_token.css');
  return ' <span class="uses-tokens">' . t('uses tokens') . '</span>';
}

/**
 * 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() {
  $plugins = array();
  $entity_info = entity_get_info();
  $entities = variable_get('menu_token_entities', drupal_map_assoc(array(
    'node',
    'user',
  )));
  foreach ($entities as $entity => $enabled) {
    if ($enabled) {
      $token_type = $entity_info[$entity]['token type'];
      $plugins["{$token_type}_context"] = array(
        'type' => $token_type,
        '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',
        ),
      );
      $plugins["{$token_type}_panel_context"] = array(
        'type' => $token_type,
        'label' => t('@entity_label from panel argument', array(
          '@entity_label' => $entity_info[$entity]['label'],
        )),
        'description' => t('Picks a @entity_label from the panel context.', array(
          '@entity_label' => $entity_info[$entity]['label'],
        )),
        'handler' => array(
          'path' => drupal_get_path('module', 'menu_token') . '/plugins',
          'file' => 'menu_token_panel_context.inc',
          'class' => 'menu_token_panel_context',
        ),
      );
      $plugins["{$token_type}_random"] = array(
        'type' => $token_type,
        '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',
        ),
      );
      $plugins["{$token_type}_user_defined"] = array(
        'type' => $token_type,
        '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',
        ),
      );
    }
  }
  return $plugins;
}

/**
 * Implements hook_translated_menu_link_alter().
 */
function menu_token_translated_menu_link_alter(&$item, $map) {
  global $menu_admin;

  // Check whether we should replace the path.
  if (empty($menu_admin) && isset($item['options']['menu_token_link_path'])) {
    if (_menu_token_is_called_from_features()) {
      return;
    }
    $info = token_get_info();
    $data = array();
    $token_entity_mapping = token_get_entity_mapping();

    // Load data objects used when replacing link.
    if (isset($item['options']['menu_token_data'])) {
      foreach ($item['options']['menu_token_data'] as $type => $values) {
        if (!empty($info['types'][$type]) && ($handler = menu_token_get_handler($values['plugin']))) {
          $values['options']['_type'] = $token_entity_mapping[$type];
          if ($object = $handler
            ->object_load($values['options'])) {
            $data[$type] = $object;
          }
        }
      }
    }
    $options['title_localize'] = !empty($item['options']['menu_token_options']['title_localize']) ? TRUE : FALSE;
    $options['clear'] = !empty($item['options']['menu_token_options']['clear']) ? TRUE : FALSE;
    $options['sanitize'] = FALSE;

    // Store the UUID link path.
    $item['options']['menu_token_link_uuid'] = $item['link_path'];
    $original_title = $item['title'];

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

    // Localize resulting title (for security, only when it has no tokens)
    if ($options['title_localize'] && $original_title == $item['title']) {
      $item['title'] = t(filter_xss($item['title']));
    }

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

    // 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.
    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.
    if (url_is_external($url)) {
      $item['href'] = $item['link_path'] = $url;
      return;
    }

    // Split url into parts and save in proper format.
    $url_parts = parse_url($url);
    $url = !empty($url_parts['path']) ? $url_parts['path'] : '';
    $item['href'] = $item['link_path'] = $item['router_path'] = $url;
    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'];
    }
    if (!isset($item['localized_options'])) {
      $item['localized_options'] = array();
    }
    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)) {
      $item['access'] = $menu_item['access'];
      return;
    }
    $item['access'] = FALSE;
  }
}

/**
 * Find a link path based on a router path.
 * @param  $router_path
 * @return The link path.
 */
function menu_token_find_link_path($router_path) {
  $query = db_select('menu_links', 'ml');
  $query
    ->fields('ml', array(
    'link_path',
  ))
    ->condition('ml.router_path', 'menutoken/%')
    ->condition('ml.options', '%' . db_like("\"{$router_path}\"") . '%', 'LIKE');
  $link_path = $query
    ->execute()
    ->fetchField();
  return $link_path;
}

/**
 * Implements hook_query_alter().
 *
 * No active trail is set when using paths with tokens, as the tokens are
 * replaced, and the correct path is not found in the menu link table. To fix
 * this, we replace the resolved path in the the preferred menu query's
 * conditions with menutoken one. Also replace the path that will be returned
 * with the resolved path, to allow it to be matched with the candidates in
 * menu_link_get_preferred().
 *
 * @see menu_link_get_preferred()
 */
function menu_token_query_alter(QueryAlterableInterface $query) {
  if ($query
    ->hasTag('preferred_menu_links')) {

    // Get all the conditions as a reference.
    $conditions =& $query
      ->conditions();
    foreach ($conditions as &$condition) {

      // If the current condition is the link_path one
      if (is_array($condition) && isset($condition['field']) && $condition['field'] == 'ml.link_path') {
        foreach ($condition['value'] as $path_key => $path_value) {

          // If the path has a corresponding menutoken path
          if (!empty($path_value) && ($menutoken_path = menu_token_find_link_path($path_value))) {

            // Replace the condition value with the menutoken path.
            $condition['value'] = array(
              $path_key => $menutoken_path,
            );

            // Add the resolved link path as an expression to the query. This
            // will replace the field link_path from the table menu_links with
            // the resolved path, allowing menu_link_get_preferred() to match it
            // based on data available in that function.
            $query
              ->addExpression("'{$path_value}'", 'link_path');
          }
        }
      }
    }
  }
}

/**
 * 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)) {
    if (module_exists('features')) {

      // Save memory in the debug_backtrace() function when possible
      if (version_compare(PHP_VERSION, '5.3.6', '>=')) {
        $callstack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
      }
      else {
        $callstack = debug_backtrace();
      }
      foreach ($callstack as $function) {
        $called = $function['function'] == 'menu_links_features_export_render';
        if ($called) {
          break;
        }
      }
    }
    else {
      $called = FALSE;
    }
  }
  return $called;
}

/**
 * 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 (in_array($form['module']['#value'], array(
    'menu',
    'system',
  ))) {
    $types = menu_token_get_plugin_types();
    $options = $form['options']['#value'];

    // Replace fake path (/menutoken/ouruid) with user inputed one.
    if (!empty($options['menu_token_link_path']) && !empty($options['menu_token_link_uuid'])) {
      $form['menu_token_uuid'] = array(
        '#type' => 'hidden',
        '#value' => $options['menu_token_link_uuid'],
      );
      $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',
      '#title' => t('<strong>Use tokens</strong> in title and in path.'),
      '#description' => t('Active this option in order to use Menu token.'),
      '#default_value' => isset($options['menu_token_link_path']),
      '#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'),
        ),
        '#default_value' => isset($default) && in_array($default, array_keys($items)) ? $default : array(
          '_none',
        ),
        '#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;
        }
      }
    }
    $form['menu_token_options']['menu_token_title_localize'] = array(
      '#type' => 'checkbox',
      '#title' => t('Localize resulting title.'),
      '#description' => t('After replacing all tokens, pass resulting title through t() function. <strong>FOR SECURITY</strong>, only when it has no tokens.'),
      '#default_value' => isset($options['menu_token_options']['title_localize']) ? $options['menu_token_options']['title_localize'] : '',
    );
    $form['menu_token_options']['menu_token_clear'] = array(
      '#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'),
      '#collapsible' => FALSE,
      '#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),
      '#dialog' => TRUE,
    );

    // 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) {
  $values =& $form_state['values'];

  // If token replacing is enabled and this is a custom menu item.
  if (in_array($values['module'], array(
    'menu',
    'system',
  )) && !empty($values['menu_token_enabled'])) {

    // Substitute link_path with our own unique menu path. This will make sure features will export our menu items.
    $values['options']['menu_token_link_path'] = $values['link_path'];

    // Set 'alter' option to use hook_translated_menu_link_alter()
    $values['options']['alter'] = TRUE;

    // If a uuid already exists, don't change it
    $uuid_path = !empty($values['menu_token_uuid']) ? $values['menu_token_uuid'] : 'menutoken/' . uniqid();
    $values['link_path'] = $uuid_path;
    $values['options']['menu_token_link_uuid'] = $uuid_path;
    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.
          $form_state['_menu_token_entity_type'] = $type;
          $handler
            ->form_validate($form, $form_state);
        }
      }
    }
  }
}

/**
 * Custom submit for form menu_edit_item.
 */
function menu_token_form_menu_edit_item_submit($form, &$form_state) {
  $values =& $form_state['values'];

  // If token replacing is enabled and this is a custom menu item
  if (in_array($values['module'], array(
    'menu',
    'system',
  )) && !empty($values['menu_token_enabled'])) {

    // 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);
    form_set_value(array(
      '#parents' => array(
        'options',
        'menu_token_options',
        'title_localize',
      ),
    ), $values['menu_token_title_localize'], $form_state);
    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)) {
          form_set_value(array(
            '#parents' => array(
              'options',
              'menu_token_data',
              $type,
            ),
          ), array(
            'type' => $type,
            'plugin' => $plugin,
            'options' => array(),
          ), $form_state);

          // Validate the form via the handler.
          if ($output = $handler
            ->form_submit($form, $form_state)) {
            $output = $values['options']['menu_token_data'][$type]['options'] + $output;
            form_set_value(array(
              '#parents' => array(
                'options',
                'menu_token_data',
                $type,
                'options',
              ),
            ), $output, $form_state);
          }
        }
      }
    }
  }
  else {
    foreach (array(
      'menu_token_link_path',
      'menu_token_data',
      'menu_token_options',
    ) as $key) {
      unset($values['options'][$key]);
    }
  }
}

/**
 * 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);
}

/**
 * Implements hook_permission().
 */
function menu_token_permission() {
  return array(
    'administer menu_token' => array(
      'title' => t('Administer Menu Token'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function menu_token_menu() {
  $items = array();
  $items['menutoken'] = array(
    'title' => "Dummy Menu Token item",
    'access callback' => TRUE,
    'page callback' => 'theme_menu_token_uses_tokens',
  );
  $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;
}

Functions

Namesort descending Description
menu_token_ctools_plugin_type Implements hook_ctools_plugin_type().
menu_token_find_link_path Find a link path based on a router path.
menu_token_form_menu_edit_item_alter Implementation of hook_form_FORM_ID_alter().
menu_token_form_menu_edit_item_submit Custom submit for form menu_edit_item.
menu_token_form_menu_edit_item_validate Custom validation for form menu_edit_item.
menu_token_form_menu_overview_form_alter Implementation hook_form_FORM_ID_alter().
menu_token_get_handler Retrieves the handler of a menu token plugin.
menu_token_get_plugin Retrieves a menu token plugin.
menu_token_get_plugins Retrieves a list of all available menu token plugins.
menu_token_get_plugin_types Retrieves a list of all token types that are covered by the available menu token plugins.
menu_token_menu Implements hook_menu().
menu_token_menu_token_plugins Implements hook_menu_token_plugins().
menu_token_method_callback Ajax callback for the method select dropdown.
menu_token_permission Implements hook_permission().
menu_token_query_alter Implements hook_query_alter().
menu_token_theme Implements hook_theme().
menu_token_translated_menu_link_alter Implements hook_translated_menu_link_alter().
theme_menu_token_uses_tokens Appends the "uses tokens" label to links on the admin menu links overview form.
_menu_token_is_called_from_features Returns TRUE if 'menu_links_features_export_render' is in the callstack.
_menu_token_plugin_info Builds and returns information about the menu token plugins and their types.