menu_block.module 34 KB
Newer Older
1
<?php
JohnAlbin's avatar
JohnAlbin committed
2 3 4 5 6
/**
 * @file
 * Provides configurable blocks of menu items.
 */

7
/**
8
 * Denotes that the tree should use the menu picked by the current page.
9 10 11
 */
define('MENU_TREE__CURRENT_PAGE_MENU', '_active');

12
// Off-load the following infrequently called hooks to another file.
JohnAlbin's avatar
JohnAlbin committed
13 14 15 16
function menu_block_block_info() {
  module_load_include('inc', 'menu_block', 'menu_block.admin');
  return _menu_block_block_info();
}
17
function menu_block_block_configure($delta = '') {
JohnAlbin's avatar
JohnAlbin committed
18 19 20 21 22 23 24
  module_load_include('inc', 'menu_block', 'menu_block.admin');
  return _menu_block_block_configure($delta);
}
function menu_block_block_save($delta = '', $edit = array()) {
  module_load_include('inc', 'menu_block', 'menu_block.admin');
  return _menu_block_block_save($delta, $edit);
}
JohnAlbin's avatar
JohnAlbin committed
25 26 27 28
function menu_block_form_block_admin_display_form_alter(&$form, $form_state) {
  module_load_include('inc', 'menu_block', 'menu_block.admin');
  return _menu_block_form_block_admin_display_form_alter($form, $form_state);
}
29

30 31 32 33 34 35 36 37 38 39 40
/**
 * Implements hook_menu().
 */
function menu_block_menu() {
  // @todo Remove this check if block module is re-added as a dependency.
  if (module_exists('block')) {
    $items['admin/structure/block/add-menu-block'] = array(
      'title' => 'Add menu block',
      'description' => 'Add a new menu block.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('menu_block_add_block_form'),
41
      'access callback' => 'menu_block_access',
42 43 44 45 46 47 48 49 50 51 52
      'type' => MENU_LOCAL_ACTION,
      'file' => 'menu_block.admin.inc',
    );
    $default_theme = variable_get('theme_default', 'bartik');
    foreach (list_themes() as $key => $theme) {
      if ($key != $default_theme) {
        $items['admin/structure/block/list/' . $key . '/add-menu-block'] = array(
          'title' => 'Add menu block',
          'description' => 'Add a new menu block.',
          'page callback' => 'drupal_get_form',
          'page arguments' => array('menu_block_add_block_form'),
53
          'access callback' => 'menu_block_access',
54 55 56 57 58 59 60 61
          'type' => MENU_LOCAL_ACTION,
          'file' => 'menu_block.admin.inc',
        );
      }
    }
    $items['admin/structure/block/delete-menu-block'] = array(
      'title' => 'Delete menu block',
      'page callback' => 'drupal_get_form',
62
      'page arguments' => array('menu_block_delete_form'),
63
      'access callback' => 'menu_block_access',
64 65 66 67 68 69 70 71 72 73
      'type' => MENU_CALLBACK,
      'file' => 'menu_block.admin.inc',
    );
  }

  $items['admin/config/user-interface/menu-block'] = array(
    'title' => 'Menu block',
    'description' => 'Configure menu block.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_block_admin_settings_form'),
74
    'access callback' => 'menu_block_access',
75 76 77 78 79 80
    'type' => MENU_NORMAL_ITEM,
    'file' => 'menu_block.admin.inc',
  );
  return $items;
}

81 82 83 84
/**
 * Determine whether the user has permission to use menu_block module.
 */
function menu_block_access($account = NULL) {
85
  return user_access('administer blocks', $account) && user_access('administer menu', $account);
86 87
}

88 89 90 91 92 93 94 95 96 97
/**
 * Implements hook_menu_alter().
 */
function menu_block_menu_alter(&$items) {
  // Fake the necessary menu attributes necessary for a contextual link.
  $items['admin/content/book/%node']['title'] = 'Edit book outline';
  $items['admin/content/book/%node']['type'] = MENU_LOCAL_TASK;
  $items['admin/content/book/%node']['context'] = (MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE);
  $items['admin/content/book/%node']['tab_root'] = 'admin/content/book';
}
JohnAlbin's avatar
JohnAlbin committed
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
/**
 * Implements hook_ctools_plugin_directory().
 */
function menu_block_ctools_plugin_directory($module, $plugin) {
  if ($plugin == 'content_types') {
    return 'plugins/' . $plugin;
  }
}

/**
 * Implements hook_ctools_block_info().
 *
 * @see ctools_block_content_type_content_types().
 */
function menu_block_ctools_block_info($module, $delta, &$info) {
  $info['icon'] = 'icon_contrib_menu.png';
  $info['category'] = t('Menus');
}

/**
 * Implements hook_theme().
 */
function menu_block_theme(&$existing, $type, $theme, $path) {
  // Add theme hook suggestion patterns for the core theme functions used in
  // this module. We can't add them during hook_theme_registry_alter() because
  // we will already have missed the opportunity for the theme engine's
  // theme_hook() to process the pattern. And we can't run the pattern ourselves
  // because we aren't given the type, theme and path in that hook.
  $existing['menu_tree']['pattern'] = 'menu_tree__';
  $existing['menu_link']['pattern'] = 'menu_link__';

  return array(
    'menu_block_wrapper' => array(
      'template' => 'menu-block-wrapper',
      'variables' => array('content' => array(), 'config' => array(), 'delta' => NULL),
      'pattern' => 'menu_block_wrapper__',
    ),
    'menu_block_menu_order' => array(
      'render element' => 'element',
      'file' => 'menu_block.admin.inc',
    ),
  );
}

JohnAlbin's avatar
JohnAlbin committed
143 144 145 146 147
/**
 * Implements hook_help().
 */
function menu_block_help($path, $arg) {
  switch ($path) {
148
    case 'admin/structure/block/manage/%/%':
149 150 151
      if ($arg[4] != 'menu_block') {
        break;
      }
JohnAlbin's avatar
JohnAlbin committed
152
    case 'admin/help#menu_block':
153
    case 'admin/structure/block/add-menu-block':
154
      module_load_include('inc', 'menu_block', 'menu_block.pages');
JohnAlbin's avatar
JohnAlbin committed
155 156 157 158
      return _menu_block_help($path, $arg);
  }
}

159
/**
160
 * Implements hook_block_view().
161
 */
162
function menu_block_block_view($delta = '') {
163
  $config = menu_block_get_config($delta);
164 165 166 167 168 169 170 171 172 173 174 175
  return menu_tree_build($config);
}

/**
 * Implements hook_block_view_alter().
 */
function menu_block_block_view_alter(&$data, $block) {
  // Add contextual links for menu blocks.
  if ($block->module == 'menu_block' && !empty($data['content']['#config'])) {
    $menu_name = $data['content']['#config']['menu_name'];
    if (in_array($menu_name, array_keys(menu_get_menus()))) {
      $data['content']['#contextual_links']['menu_block'] = array('admin/structure/menu/manage', array($menu_name));
176
    }
177 178
    elseif (strpos($menu_name, 'book-toc-') === 0) {
      $node = str_replace('book-toc-', '', $menu_name);
179 180
      $data['content']['#contextual_links']['menu_block'] = array('admin/content/book', array($node));
    }
181
  }
182 183
}

184 185 186 187 188 189
/**
 * Process variables for menu-block-wrapper.tpl.php.
 *
 * @see menu-block-wrapper.tpl.php
 */
function template_preprocess_menu_block_wrapper(&$variables) {
190
  $variables['classes_array'][] = 'menu-block-' . $variables['delta'];
191
  $variables['classes_array'][] = 'menu-name-' . $variables['config']['menu_name'];
192
  $variables['classes_array'][] = 'parent-mlid-' . menu_block_clean_css_identifier($variables['config']['parent_mlid']);
193
  $variables['classes_array'][] = 'menu-level-' . $variables['config']['level'];
194 195
}

196 197 198 199 200 201 202
/**
 * A copy of drupal_clean_css_identifier() that cleans up colon characters.
 */
function menu_block_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '', ':' => '-')) {
  return drupal_clean_css_identifier($identifier, $filter);
}

203 204 205
/**
 * Returns a list of menu names implemented by all modules.
 *
206 207
 * @return array
 *   An array of menu titles keyed by menu machine name.
208 209
 */
function menu_block_get_all_menus() {
JohnAlbin's avatar
JohnAlbin committed
210
  $all_menus = &drupal_static(__FUNCTION__);
211 212

  if (!$all_menus) {
213 214
    $cid = 'menu_block_menus:' . $GLOBALS['language']->language;
    if ($cached = cache_get($cid, 'cache_menu')) {
215 216 217 218 219 220 221 222
      $all_menus = $cached->data;
    }
    else {
      // Retrieve core's menus.
      $all_menus = menu_get_menus();
      // Retrieve all the menu names provided by hook_menu_block_get_menus().
      $all_menus = array_merge($all_menus, module_invoke_all('menu_block_get_menus'));
      asort($all_menus);
223 224 225
      // Add an option to use the menu for the active menu item.
      $all_menus = array(MENU_TREE__CURRENT_PAGE_MENU => '<' . t('the menu selected by the page') . '>') + $all_menus;
      cache_set($cid, $all_menus, 'cache_menu');
226 227
    }
  }
228

229 230 231
  return $all_menus;
}

232 233 234 235 236 237 238 239 240 241 242 243
/**
 * The default menu block configuration.
 *
 * @return array
 */
function menu_block_default_config() {
  return array(
    'parent' => 'main-menu:0',
    'title_link' => 0,
    'admin_title' => '',
    'level' => 1,
    'follow' => 0,
244
    'display_empty' => 0,
245
    'depth' => 0,
246
    'depth_relative' => 0,
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    'expanded' => 0,
    'sort' => 0,
  );
}

/**
 * Fetch all exported menu blocks.
 *
 * @return array
 */
function menu_block_get_exported_blocks() {
  $blocks = &drupal_static(__FUNCTION__);
  if (!isset($blocks)) {
    $blocks = array();
    // Do not use module_invoke_all() since it rewrites numeric indexes.
    // Although exported menu blocks should not be using numeric IDs, we
    // should still prevent them from being changed.
    foreach (module_implements('menu_block_blocks') as $module) {
      $blocks += module_invoke($module, 'menu_block_blocks');
    }
  }
  return $blocks;
}

271
/**
272
 * Returns the configuration for the requested block delta.
273
 *
274 275
 * @param string $delta
 *   The delta that uniquely identifies the block in the block system. If
276
 *   not specified, the default configuration will be returned.
277
 *   This is deprecated. Use menu_block_default_config() instead.
278 279 280
 *
 * @return array
 *   An associated array of configuration options.
281 282
 *
 * @see menu_block_default_config()
283
 */
284
function menu_block_get_config($delta = NULL) {
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  static $defaults, $exported;

  if (!isset($defaults)) {
    $defaults = menu_block_default_config();
  }

  if (!isset($delta)) {
    return $defaults;
  }

  if (!isset($exported)) {
    $exported = menu_block_get_exported_blocks();
  }

  $configs = &drupal_static(__FUNCTION__, array());
  if (!isset($configs[$delta])) {
    $config = array();
302

303 304 305
    // Check if this an exported menu block.
    if (isset($exported[$delta])) {
      $config += $exported[$delta];
306
      $config['exported_to_code'] = TRUE;
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
      // Exported blocks generally have 'menu_name' and 'parent_mlid' defined
      // but not 'parent'
      if (!isset($config['parent'])) {
        $config['parent'] = $config['menu_name'] . ':' . $config['parent_mlid'];
      }
    }

    // Add in variable overrides and defaults.
    foreach ($defaults as $key => $default) {
      $override = variable_get("menu_block_{$delta}_{$key}");
      if (isset($override)) {
        $config[$key] = $override;
      }
      elseif (!isset($config[$key])) {
        $config[$key] = $default;
      }
    }

    // Split out the 'parent' item into 'menu_name' and 'parent_mlid'.
    if (!isset($config['menu_name']) && !isset($config['parent_mlid'])) {
      list($config['menu_name'], $config['parent_mlid']) = explode(':', $config['parent']);
328 329
    }

330 331
    $config['delta'] = $delta;
    $configs[$delta] = $config;
332 333
  }

334
  return $configs[$delta];
335 336
}

337
/**
338
 * Gets the data structure representing a menu tree for the given configuration.
339
 *
340
 * @param array $config
341
 *   See the $config param of menu_tree_build().
342 343
 *
 * @return array
344
 */
345
function menu_tree_block_data(array &$config) {
346
  // Determine the max depth based on level and depth setting.
347
  $max_depth = ($config['depth'] == 0) ? NULL : min($config['level'] + $config['depth'] - 1, MENU_MAX_DEPTH);
348

349
  if ($config['expanded'] || $config['parent_mlid']) {
350
    // Get the full, un-pruned tree.
351
    if ($config['parent_mlid'] || !empty($config['depth_relative'])) {
352 353 354 355 356
      $tree = menu_tree_all_data($config['menu_name']);
    }
    else {
      $tree = menu_tree_all_data($config['menu_name'], NULL, $max_depth);
    }
357 358
    // And add the active trail data back to the full tree.
    menu_tree_add_active_path($tree);
359 360
  }
  else {
361
    if (!empty($config['depth_relative'])) {
362 363 364 365 366 367
      // Get the tree pruned for just the active trail.
      $tree = menu_tree_page_data($config['menu_name']);
    }
    else {
      $tree = menu_tree_page_data($config['menu_name'], $max_depth);
    }
368
  }
369

370 371
  // Allow alteration of the tree and config before we begin operations on it.
  drupal_alter('menu_block_tree', $tree, $config);
372

373
  // Localize the tree.
374 375
  if (module_exists('i18n_menu')) {
    $tree = i18n_menu_localize_tree($tree);
376 377
  }

378
  // Prune the tree along the active trail to the specified level.
379 380 381
  if ($config['level'] > 1 || $config['parent_mlid']) {
    if ($config['parent_mlid']) {
      $parent_item = menu_link_load($config['parent_mlid']);
382 383 384 385 386 387 388
      if (!$parent_item) {
        watchdog('menu_block', "Menu block @delta is set to use parent menu link @plid but the menu link was not loadable or does not exist.", array(
          '@delta' => $config['delta'],
          '@plid' => $config['parent_mlid'],
        ), WATCHDOG_ERROR);
        $parent_item = NULL;
      }
389
      menu_tree_prune_tree($tree, $config['level'], $parent_item);
390 391
    }
    else {
392
      menu_tree_prune_tree($tree, $config['level']);
393
    }
394 395
  }

396
  // Prune the tree to the active menu item.
397 398
  if ($config['follow']) {
    menu_tree_prune_active_tree($tree, $config['follow']);
399 400
  }

401
  // If the menu-item-based tree is not "expanded", trim the tree to the active path.
402
  if ($config['parent_mlid'] && !$config['expanded']) {
403
    menu_tree_trim_active_path($tree);
404
  }
405 406

  // Trim the branches that extend beyond the specified depth.
407 408
  if ($config['depth'] > 0) {
    menu_tree_depth_trim($tree, $config['depth']);
409 410
  }

411
  // Sort the active path to the top of the tree.
412
  if ($config['sort']) {
413 414 415
    menu_tree_sort_active_path($tree);
  }

416 417 418 419 420
  return $tree;
}

/**
 * Returns the current page's menu.
421 422 423
 *
 * @return string|bool
 *   The current page's menu, or FALSE if no menu applied.
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
 */
function menu_block_get_current_page_menu() {
  // Retrieve the list of available menus.
  $menu_order = variable_get('menu_block_menu_order', array('main-menu' => '', 'user-menu' => ''));

  // Check for regular expressions as menu keys.
  $patterns = array();
  foreach (array_keys($menu_order) as $pattern) {
    if ($pattern[0] == '/') {
      $patterns[$pattern] = NULL;
    }
  }

  // Extract the "current" path from the request, or from the active menu
  // trail if applicable.
  $link_path = $_GET['q'] ? $_GET['q'] : '<front>';
  $trail = menu_get_active_trail();
  $last_item = end($trail);
  if (!empty($last_item['link_path'])) {
    $link_path = $last_item['link_path'];
  }

  // Retrieve all the menus containing a link to the current page.
  $result = db_query("SELECT menu_name FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $link_path));
  foreach ($result as $item) {
    // Check if the menu is in the list of available menus.
    if (isset($menu_order[$item->menu_name])) {
      // Mark the menu.
      $menu_order[$item->menu_name] = MENU_TREE__CURRENT_PAGE_MENU;
    }
    else {
      // Check if the menu matches one of the available patterns.
      foreach (array_keys($patterns) as $pattern) {
        if (preg_match($pattern, $item->menu_name)) {
          // Mark the menu.
          $menu_order[$pattern] = MENU_TREE__CURRENT_PAGE_MENU;
          // Store the actual menu name.
          $patterns[$pattern] = $item->menu_name;
        }
      }
    }
  }
  // Find the first marked menu.
  $menu_name = array_search(MENU_TREE__CURRENT_PAGE_MENU, $menu_order);
  // If a pattern was matched, use the actual menu name instead of the pattern.
  if (!empty($patterns[$menu_name])) {
    $menu_name = $patterns[$menu_name];
  }

  return $menu_name;
}

/**
 * Build a menu tree based on the provided configuration.
 *
479 480
 * @param array $config
 *   An array of configuration options that specifies how to build the
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
 *   menu tree and its title.
 *   - delta: (string) The menu_block's block delta.
 *   - menu_name: (string) The machine name of the requested menu. Can also be
 *     set to MENU_TREE__CURRENT_PAGE_MENU to use the menu selected by the page.
 *   - parent_mlid: (int) The mlid of the item that should root the tree. Use 0
 *     to use the menu's root.
 *   - title_link: (boolean) Specifies if the title should be rendered as a link
 *     or a simple string.
 *   - admin_title: (string) An optional title to uniquely identify the block on
 *     the administer blocks page.
 *   - level: (int) The starting level of the tree.
 *   - follow: (string) Specifies if the starting level should follow the
 *     active menu item. Should be set to 0, 'active' or 'child'.
 *   - depth: (int) The maximum depth the tree should contain, relative to the
 *     starting level.
 *   - expanded: (boolean) Specifies if the entire tree be expanded or not.
 *   - sort: (boolean) Specifies if the tree should be sorted with the active
 *     trail at the top of the tree.
499 500 501
 *
 * @return array
 *   An associative array containing several pieces of data.
502 503 504 505
 *   - content: The tree as a renderable array.
 *   - subject: The title rendered as HTML.
 *   - subject_array: The title as a renderable array.
 */
506
function menu_tree_build(array &$config) {
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
  // Retrieve the active menu item from the database.
  if ($config['menu_name'] == MENU_TREE__CURRENT_PAGE_MENU) {
    $config['menu_name'] = menu_block_get_current_page_menu();
    $config['parent_mlid'] = 0;

    // If no menu link was found, don't display the block.
    if (empty($config['menu_name'])) {
      return array(
        'subject' => t('The menu selected by the page'),
        'subject_array' => array(),
        'content' => array(),
      );
    }
  }

  // Get the default block name.
523
  drupal_static_reset('menu_block_set_title');
524 525 526 527 528
  $menu_names = menu_block_get_all_menus();
  menu_block_set_title($menu_names[$config['menu_name']]);

  // Get the raw menu tree data.
  $tree = menu_tree_block_data($config);
529
  $title = menu_block_get_title($config['title_link']);
530 531 532

  // Create a renderable tree.
  $data = array();
533 534
  $data['subject_array'] = $title;
  $data['subject'] = drupal_render($title);
535
  $data['content'] = array();
536 537
  if (!empty($tree) || !empty($config['display_empty'])) {
    if ($output = menu_block_tree_output($tree, $config)) {
538 539 540 541 542 543 544 545 546 547
      $data['content']['#content'] = $output;
      $data['content']['#theme'] = array(
        'menu_block_wrapper__' . str_replace('-', '_', $config['delta']),
        'menu_block_wrapper__' . str_replace('-', '_', $config['menu_name']),
        'menu_block_wrapper'
      );
    }
    else {
      $data['content']['#content'] = NULL;
    }
548 549 550
    $data['content']['#config'] = $config;
    $data['content']['#delta'] = $config['delta'];
  }
551

552
  return $data;
JohnAlbin's avatar
JohnAlbin committed
553 554
}

555
/**
556 557
 * Retrieves the menu item to use for the tree's title.
 *
558
 * @param bool $render_title_as_link
JohnAlbin's avatar
JohnAlbin committed
559 560
 *   boolean A boolean that says whether to render the title as a link or a
 *   simple string.
561 562 563
 *
 * @return array|string
 *   A render array or string containing the tree's title.
564
 */
565
function menu_block_get_title($render_title_as_link = TRUE) {
566
  $menu_item = menu_block_set_title();
567 568

  if (is_string($menu_item)) {
569
    // The tree's title is a menu title, a normal string.
570
    $title = array('#markup' => check_plain($menu_item));
571
  }
572
  elseif ($render_title_as_link) {
573
    // The tree's title is a menu item with a link.
574
    if (!empty($menu_item['in_active_trail'])) {
575
      $menu_item['localized_options']['attributes']['class'][] = 'active-trail';
576
    }
577 578 579 580 581 582
    $title = array(
      '#type' => 'link',
      '#title' => $menu_item['title'],
      '#href' => $menu_item['href'],
      '#options' => $menu_item['localized_options'],
    );
583
  }
584
  // The tree's title is a menu item.
585
  else {
586
    $title = array('#markup' => check_plain($menu_item['title']));
587 588 589 590
  }
  return $title;
}

591 592 593
/**
 * Sets the menu item to use for the tree's title.
 *
594 595 596 597 598
 * @param array|string $item
 *   The menu item (an array) or the menu item's title as a string.
 *
 * @return array|string
 *   The saved title value.
599 600
 */
function menu_block_set_title($item = NULL) {
601
  $menu_item = &drupal_static(__FUNCTION__, '');
602 603 604 605 606 607 608 609 610

  // Save the menu item.
  if (!is_null($item)) {
    $menu_item = $item;
  }

  return $menu_item;
}

611 612 613 614 615 616 617 618
/**
 * Add the active trail indicators into the tree.
 *
 * The data returned by menu_tree_page_data() has link['in_active_trail'] set to
 * TRUE for each menu item in the active trail. The data returned from
 * menu_tree_all_data() does not contain the active trail indicators. This is a
 * helper function that adds it back in.
 *
619 620
 * @param array $tree
 *   The menu tree.
621
 */
622
function menu_tree_add_active_path(array &$tree) {
623 624 625 626 627
  // Return if there are no menu items.
  if (!$tree) {
    return;
  }

628 629 630 631 632 633 634 635 636
  // Grab any menu item to find the menu_name for this tree.
  $menu_item = current($tree);
  $tree_with_trail = menu_tree_page_data($menu_item['link']['menu_name']);

  // To traverse the original tree down the active trail, we use a pointer.
  $subtree_pointer =& $tree;

  // Find each key in the active trail.
  while ($tree_with_trail) {
637
    foreach ($tree_with_trail as $key => &$value) {
638
      if ($tree_with_trail[$key]['link']['in_active_trail'] && isset($subtree_pointer[$key])) {
639 640 641 642 643 644 645 646 647 648 649 650 651 652
        // Set the active trail info in the original tree.
        $subtree_pointer[$key]['link']['in_active_trail'] = TRUE;
        // Continue in the subtree, if it exists.
        $tree_with_trail =& $tree_with_trail[$key]['below'];
        $subtree_pointer =& $subtree_pointer[$key]['below'];
        break;
      }
      else {
        unset($tree_with_trail[$key]);
      }
    }
  }
}

653 654 655
/**
 * Trim everything but the active trail in the tree.
 *
656 657
 * @param array $tree
 *   The menu tree to trim.
658
 */
659 660
function menu_tree_trim_active_path(array &$tree) {
  foreach ($tree as $key => &$value) {
661 662 663
    if (($tree[$key]['link']['in_active_trail'] || $tree[$key]['link']['expanded']) && $tree[$key]['below']) {
      // Continue in the subtree, if it exists.
      menu_tree_trim_active_path($tree[$key]['below']);
664
    }
665 666 667
    else {
      // Trim anything not expanded or along the active trail.
      $tree[$key]['below'] = FALSE;
668
    }
669
  }
670 671
}

672 673 674
/**
 * Sort the active trail to the top of the tree.
 *
675
 * @param array $tree
676 677
 *   array The menu tree to sort.
 */
678
function menu_tree_sort_active_path(array &$tree) {
679 680 681 682
  module_load_include('inc', 'menu_block', 'menu_block.sort');
  _menu_tree_sort_active_path($tree);
}

683
/**
684
 * Prune a tree so that it begins at the specified level.
685
 *
686
 * This function will follow the active menu trail to the specified level.
687
 *
688 689 690 691 692 693
 * @param array $tree
 *   The menu tree to prune.
 * @param int $level
 *   The level of the original tree that will start the pruned tree.
 * @param array $parent_item
 *   The menu item that should be used as the root of the tree.
694
 */
695
function menu_tree_prune_tree(array &$tree, $level, array $parent_item = NULL) {
696
  if (!empty($parent_item)) {
697
    // Prune the tree along the path to the menu item.
JohnAlbin's avatar
JohnAlbin committed
698
    for ($i = 1; $i <= MENU_MAX_DEPTH && $parent_item["p$i"] != '0'; $i++) {
699
      $plid = $parent_item["p$i"];
700 701
      $found_active_trail = FALSE;
      // Examine each element at this level for the ancestor.
702
      foreach ($tree as $key => &$value) {
703
        if ($tree[$key]['link']['mlid'] == $plid) {
704
          menu_block_set_title($tree[$key]['link']);
705 706 707 708 709 710 711 712 713 714 715 716 717 718
          // Prune the tree to the children of this ancestor.
          $tree = $tree[$key]['below'] ? $tree[$key]['below'] : array();
          $found_active_trail = TRUE;
          break;
        }
      }
      // If we don't find the ancestor, bail out.
      if (!$found_active_trail) {
        $tree = array();
        break;
      }
    }
  }

719
  $is_front_page = drupal_is_front_page();
720
  // Trim the upper levels down to the one desired.
JohnAlbin's avatar
JohnAlbin committed
721
  for ($i = 1; $i < $level; $i++) {
722 723
    $found_active_trail = FALSE;
    // Examine each element at this level for the active trail.
724
    foreach ($tree as $key => &$value) {
725 726
      // Also include the children of the front page.
      if ($tree[$key]['link']['in_active_trail'] || ($tree[$key]['link']['link_path'] == '<front>' && $is_front_page)) {
727
        // Get the title for the pruned tree.
728
        menu_block_set_title($tree[$key]['link']);
729 730 731 732 733 734 735 736 737 738 739
        // Prune the tree to the children of the item in the active trail.
        $tree = $tree[$key]['below'] ? $tree[$key]['below'] : array();
        $found_active_trail = TRUE;
        break;
      }
    }
    // If we don't find the active trail, the active item isn't in the tree we want.
    if (!$found_active_trail) {
      $tree = array();
      break;
    }
740 741 742
  }
}

743 744 745
/**
 * Prune a tree so that it begins at the active menu item.
 *
746 747 748 749
 * @param array $tree
 *   The menu tree to prune.
 * @param string $level
 *   The level which the tree will be pruned to: 'active' or 'child'.
750
 */
751
function menu_tree_prune_active_tree(array &$tree, $level) {
752
  module_load_include('inc', 'menu_block', 'menu_block.follow');
753
  _menu_tree_prune_active_tree($tree, $level);
754 755
}

756
/**
757
 * Prune a tree so it does not extend beyond the specified depth limit.
758
 *
759 760 761 762
 * @param array $tree
 *   The menu tree to prune.
 * @param int $depth_limit
 *   The maximum depth of the returned tree; must be a positive integer.
763
 */
764
function menu_tree_depth_trim(array &$tree, $depth_limit) {
JohnAlbin's avatar
JohnAlbin committed
765
  // Prevent invalid input from returning a trimmed tree.
766 767 768
  if ($depth_limit < 1) {
    return;
  }
769 770

  // Examine each element at this level to find any possible children.
771
  foreach ($tree as $key => &$value) {
772 773 774 775 776 777 778 779
    if ($tree[$key]['below']) {
      if ($depth_limit > 1) {
        menu_tree_depth_trim($tree[$key]['below'], $depth_limit-1);
      }
      else {
        // Remove the children items.
        $tree[$key]['below'] = FALSE;
      }
780
    }
781 782 783
    if ($depth_limit == 1 && $tree[$key]['link']['has_children']) {
      // Turn off the menu styling that shows there were children.
      $tree[$key]['link']['has_children'] = FALSE;
784
      $tree[$key]['link']['leaf_has_children'] = TRUE;
785
    }
786 787
  }
}
788 789

/**
790
 * Returns a renderable menu tree.
791
 *
792 793
 * This is a copy of menu_tree_output() with additional classes added to the
 * output.
794
 *
795 796 797 798 799 800
 * @param array $tree
 *   A data structure representing the tree as returned from menu_tree_data.
 * @param array $config
 *
 * @return array
 *   The menu tree as a render array.
801
 */
802
function menu_block_tree_output(array &$tree, array $config = array()) {
803
  $build = array();
804 805
  $items = array();

806 807 808 809 810 811 812
  // Create context if no config was provided.
  if (empty($config)) {
    $config['delta'] = 0;
    // Grab any menu item to find the menu_name for this tree.
    $menu_item = current($tree);
    $config['menu_name'] = $menu_item['link']['menu_name'];
  }
813
  $hook_delta = str_replace('-', '_', $config['delta']);
814 815
  $hook_menu_name = str_replace('-', '_', $config['menu_name']);

816
  // Pull out just the menu links we are going to render so that we
817
  // get an accurate count for the first/last classes.
JohnAlbin's avatar
JohnAlbin committed
818
  foreach ($tree as $key => &$value) {
819
    if ($tree[$key]['link']['access'] && !$tree[$key]['link']['hidden']) {
820
      $items[] = $tree[$key];
821 822 823
    }
  }

824
  $router_item = menu_get_item();
825
  $num_items = count($items);
826 827 828 829 830 831 832
  foreach ($items as $i => &$data) {
    $class = array();
    if ($i == 0) {
      $class[] = 'first';
    }
    if ($i == $num_items - 1) {
      $class[] = 'last';
833
    }
834 835 836 837
    // Set a class for the <li>-tag. Since $data['below'] may contain local
    // tasks, only set 'expanded' class if the link also has children within
    // the current menu.
    if ($data['link']['has_children'] && $data['below']) {
838
      $class[] = 'expanded';
839
    }
840 841
    elseif ($data['link']['has_children']) {
      $class[] = 'collapsed';
842
    }
843 844
    else {
      $class[] = 'leaf';
845
    }
846 847
    if (!empty($data['link']['leaf_has_children'])) {
      $class[] = 'has-children';
848
    }
849 850 851 852
    // Set a class if the link is in the active trail.
    if ($data['link']['in_active_trail']) {
      $class[] = 'active-trail';
      $data['link']['localized_options']['attributes']['class'][] = 'active-trail';
853
    }
854 855
    if ($data['link']['href'] == $_GET['q'] || ($data['link']['href'] == '<front>' && drupal_is_front_page())) {
      $class[] = 'active';
856
    }
857 858
    // Set a menu link ID class.
    $class[] = 'menu-mlid-' . $data['link']['mlid'];
859 860 861 862
    // Normally, l() compares the href of every link with $_GET['q'] and sets
    // the active class accordingly. But local tasks do not appear in menu
    // trees, so if the current path is a local task, and this link is its
    // tab root, then we have to set the class manually.
863
    if ($router_item && $data['link']['href'] == $router_item['tab_root_href'] && $data['link']['href'] != $_GET['q']) {
864 865
      $data['link']['localized_options']['attributes']['class'][] = 'active';
    }
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880

    // Allow menu-specific theme overrides.
    $element['#theme'] = array(
      'menu_link__menu_block__' . $hook_delta,
      'menu_link__menu_block__' . $hook_menu_name,
      'menu_link__menu_block',
      'menu_link__' . $hook_menu_name,
      'menu_link',
    );
    $element['#attributes']['class'] = $class;
    $element['#title'] = $data['link']['title'];
    $element['#href'] = $data['link']['href'];
    $element['#localized_options'] = !empty($data['link']['localized_options']) ? $data['link']['localized_options'] : array();
    $element['#below'] = $data['below'] ? menu_block_tree_output($data['below'], $config) : $data['below'];
    $element['#original_link'] = $data['link'];
881
    $element['#bid'] = array('module' => 'menu_block', 'delta' => $config['delta']);
882 883
    // Index using the link's unique mlid.
    $build[$data['link']['mlid']] = $element;
884
  }
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
  if ($build) {
    // Make sure drupal_render() does not re-order the links.
    $build['#sorted'] = TRUE;
    // Add the theme wrapper for outer markup.
    // Allow menu-specific theme overrides.
    $build['#theme_wrappers'][] = array(
      'menu_tree__menu_block__' . $hook_delta,
      'menu_tree__menu_block__' . $hook_menu_name,
      'menu_tree__menu_block',
      'menu_tree__' . $hook_menu_name,
      'menu_tree',
    );
  }

  return $build;
900
}
901 902 903 904 905 906

/**
 * Implements hook_menu_block_get_menus() on behalf of book.module.
 */
function book_menu_block_get_menus() {
  $menus = array();
907
  foreach (book_get_books() as $book) {
908 909 910 911 912 913 914 915 916 917 918 919 920
    $menus[$book['menu_name']] = $book['title'];
  }
  return $menus;
}

/**
 * Implements hook_menu_block_get_sort_menus() on behalf of book.module.
 */
function book_menu_block_get_sort_menus() {
  return array(
    '/^book\-toc\-.+/' => t('Book navigation'),
  );
}
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935

/**
 * Implements hook_get_pane_links_alter().
 */
function menu_block_get_pane_links_alter(&$links, $pane, $content_type) {
  if ($pane->type === 'menu_tree') {
    if (in_array($pane->subtype, array_keys(menu_get_menus()))) {
      $links['top'][] = array(
        'title' => t('Edit menu links'),
        'href' => url('admin/structure/menu/manage/' . $pane->subtype, array('absolute' => TRUE)),
        'attributes' => array('target' => array('_blank')),
      );
    }
  }
}
936

937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
/**
 * Implements hook_menu_insert().
 */
function menu_block_menu_insert($menu) {
  if (!empty($menu['menu_block_menu_order'])) {
    menu_block_menu_order_set_menu($menu['menu_name'], TRUE);
  }
}

/**
 * Implements hook_menu_update().
 */
function menu_block_menu_update($menu) {
  if (isset($menu['menu_block_menu_order'])) {
    menu_block_menu_order_set_menu($menu['menu_name'], $menu['menu_block_menu_order']);
  }
}

955 956 957 958 959 960 961 962 963 964 965
/**
 * Implements hook_menu_delete().
 */
function menu_block_menu_delete($menu) {
  // Delete menu block variables.
  foreach (variable_get('menu_block_ids', array()) as $delta) {
    $config = menu_block_get_config($delta);
    if ($config['menu_name'] === $menu['menu_name']) {
      menu_block_delete($delta);
    }
  }
966 967

  menu_block_menu_order_set_menu($menu['menu_name'], FALSE);
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
}

/**
 * Delete a menu block.
 *
 * @param string $delta
 *   The delta of the menu block.
 */
function menu_block_delete($delta) {
  // Since this used to be a form callback, prevent unintentional uses.
  if (is_array($delta)) {
    variable_set('menu_rebuild_needed', TRUE);
    return;
  }

  $block_ids = variable_get('menu_block_ids', array());
  $index = array_search($delta, $block_ids);
  if ($index !== FALSE && $config = menu_block_get_config($delta)) {
    module_invoke_all('menu_block_delete', $config);

    // Remove the delta from the list of custom IDs.
    unset($block_ids[$index]);
    sort($block_ids);
    variable_set('menu_block_ids', $block_ids);

    // Remove all the individual variables.
994 995 996 997
    $variable_keys = array_keys(menu_block_default_config());
    foreach ($variable_keys as $key) {
      variable_del("menu_block_{$delta}_{$key}");
    }
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
  }
}

/**
 * Implements hook_menu_block_delete() on behalf of block.module.
 */
function block_menu_block_delete(array $config) {
  db_delete('block')
    ->condition('module', 'menu_block')
    ->condition('delta', $config['delta'])
    ->execute();
  db_delete('block_role')
    ->condition('module', 'menu_block')
    ->condition('delta', $config['delta'])
    ->execute();
}

/**
 * Implements hook_menu_block_delete() on behalf of node.module.
 */
function node_menu_block_delete(array $config) {
  db_delete('block_node_type')
    ->condition('module', 'menu_block')
    ->condition('delta', $config['delta'])
    ->execute();
}
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

/**
 * Implements hook_form_FORM_ID_alter().
 */
function menu_block_form_menu_edit_menu_alter(&$form, &$form_state) {
  $menus = variable_get('menu_block_menu_order', array('main-menu' => '', 'user-menu' => ''));
  $form['menu_block_menu_order'] = array(
    '#type' => 'checkbox',
    '#title' => t('Include this menu in the <em>"the menu selected by the page"</em> menu available to menu blocks.'),
    '#default_value' => isset($menus[$form['old_name']['#value']]),
  );
}

/**
 * Add or remove a menu from the menu_block_menu_order variable.
 *
 * @param string $menu_name
 *   A menu machine name.
 * @param mixed $status
 *   If $status evaluates to TRUE, the menu will be added. If $status evaluates
 *   to FALSE, the menu will be removed.
 */
function menu_block_menu_order_set_menu($menu_name, $status) {
  $menus = variable_get('menu_block_menu_order', array('main-menu' => '', 'user-menu' => ''));
  if ($status && !isset($menus[$menu_name])) {
    $menus[$menu_name] = '';
    variable_set('menu_block_menu_order', $menus);
  }
  elseif (!$status && isset($menus[$menu_name])) {
    unset($menus[$menu_name]);
    variable_set('menu_block_menu_order', $menus);
  }
}
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083

/**
 * Implements hook_menu_link_insert().
 */
function menu_block_menu_link_insert($link) {
  // If a book is being created, updated, or deleted, clear the
  // menu_block_get_all_menus() cache since it means a change to a book "menu"
  // that would need to be picked up by book_menu_block_get_menus().
  if (strpos($link['menu_name'], 'book-toc-') === 0 && !$link['plid']) {
    cache_clear_all('menu_block_menus:', 'cache_menu', TRUE);
    drupal_static_reset('menu_block_get_all_menus');
  }
}

/**
 * Implements hook_menu_link_update().
 */
function menu_block_menu_link_update($link) {
  menu_block_menu_link_insert($link);
}

/**
 * Implements hook_menu_link_delete().
 */
function menu_block_menu_link_delete($link) {
  menu_block_menu_link_insert($link);
}