menu.inc 30.1 KB
Newer Older
Dries's avatar
 
Dries committed
1
<?php
2
// $Id$
Kjartan's avatar
Kjartan committed
3

4 5 6 7 8
/**
 * @file
 * API for the Drupal menu system.
 */

Dries's avatar
 
Dries committed
9 10 11
/**
 * @defgroup menu Menu system
 * @{
Dries's avatar
 
Dries committed
12
 * Define the navigation menus, and route page requests to code based on URLs.
Dries's avatar
 
Dries committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 *
 * The Drupal menu system drives both the navigation system from a user
 * perspective and the callback system that Drupal uses to respond to URLs
 * passed from the browser. For this reason, a good understanding of the
 * menu system is fundamental to the creation of complex modules.
 *
 * Drupal's menu system follows a simple hierarchy defined by paths.
 * Implementations of hook_menu() define menu items and assign them to
 * paths (which should be unique). The menu system aggregates these items
 * and determines the menu hierarchy from the paths. For example, if the
 * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
 * would form the structure:
 * - a
 *   - a/b
 *     - a/b/c/d
 *     - a/b/h
 * - e
 * - f/g
 * Note that the number of elements in the path does not necessarily
 * determine the depth of the menu item in the tree.
 *
 * When responding to a page request, the menu system looks to see if the
 * path requested by the browser is registered as a menu item with a
 * callback. If not, the system searches up the menu tree for the most
 * complete match with a callback it can find. If the path a/b/i is
 * requested in the tree above, the callback for a/b would be used.
 *
Steven Wittens's avatar
Steven Wittens committed
40 41 42 43 44 45
 * The found callback function is called with any arguments specified
 * in the "callback arguments" attribute of its menu item. The
 * attribute must be an array. After these arguments, any remaining
 * components of the path are appended as further arguments. In this
 * way, the callback for a/b above could respond to a request for
 * a/b/i differently than a request for a/b/j.
Dries's avatar
 
Dries committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
 *
 * For an illustration of this process, see page_example.module.
 *
 * Access to the callback functions is also protected by the menu system.
 * The "access" attribute of each menu item is checked as the search for a
 * callback proceeds. If this attribute is TRUE, then access is granted; if
 * FALSE, then access is denied. The first found "access" attribute
 * determines the accessibility of the target. Menu items may omit this
 * attribute to use the value provided by an ancestor item.
 *
 * In the default Drupal interface, you will notice many links rendered as
 * tabs. These are known in the menu system as "local tasks", and they are
 * rendered as tabs by default, though other presentations are possible.
 * Local tasks function just as other menu items in most respects. It is
 * convention that the names of these tasks should be short verbs if
 * possible. In addition, a "default" local task should be provided for
 * each set. When visiting a local task's parent menu item, the default
 * local task will be rendered as if it is selected; this provides for a
 * normal tab user experience. This default task is special in that it
 * links not to its provided path, but to its parent item's path instead.
 * The default task's path is only used to place it appropriately in the
 * menu hierarchy.
Dries's avatar
 
Dries committed
68 69
 */

Dries's avatar
 
Dries committed
70
/**
Dries's avatar
 
Dries committed
71
 * @name Menu flags
Dries's avatar
 
Dries committed
72
 * @{
Dries's avatar
 
Dries committed
73 74
 * Flags for use in the "type" attribute of menu items.
 */
Dries's avatar
 
Dries committed
75

Dries's avatar
 
Dries committed
76 77 78
define('MENU_IS_ROOT', 0x0001);
define('MENU_VISIBLE_IN_TREE', 0x0002);
define('MENU_VISIBLE_IN_BREADCRUMB', 0x0004);
79
define('MENU_MODIFIED_BY_ADMIN', 0x0008);
Dries's avatar
 
Dries committed
80
define('MENU_MODIFIABLE_BY_ADMIN', 0x0010);
81 82 83 84
define('MENU_CREATED_BY_ADMIN', 0x0020);
define('MENU_IS_LOCAL_TASK', 0x0040);
define('MENU_EXPANDED', 0x0080);
define('MENU_LINKS_TO_PARENT', 0x00100);
Dries's avatar
 
Dries committed
85

Dries's avatar
 
Dries committed
86
/**
Dries's avatar
 
Dries committed
87
 * @} End of "Menu flags".
Dries's avatar
 
Dries committed
88 89 90
 */

/**
Dries's avatar
 
Dries committed
91
 * @name Menu item types
Dries's avatar
 
Dries committed
92 93 94 95
 * @{
 * Menu item definitions provide one of these constants, which are shortcuts for
 * combinations of the above flags.
 */
Dries's avatar
 
Dries committed
96

Dries's avatar
 
Dries committed
97 98
/**
 * Normal menu items show up in the menu tree and can be moved/hidden by
Dries's avatar
 
Dries committed
99 100
 * the administrator. Use this for most menu items. It is the default value if
 * no menu item type is specified.
Dries's avatar
 
Dries committed
101 102
 */
define('MENU_NORMAL_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB | MENU_MODIFIABLE_BY_ADMIN);
103

Dries's avatar
 
Dries committed
104 105
/**
 * Callbacks simply register a path so that the correct function is fired
Dries's avatar
 
Dries committed
106
 * when the URL is accessed. They are not shown in the menu.
Dries's avatar
 
Dries committed
107 108
 */
define('MENU_CALLBACK', MENU_VISIBLE_IN_BREADCRUMB);
Dries's avatar
 
Dries committed
109

Dries's avatar
 
Dries committed
110
/**
Dries's avatar
 
Dries committed
111 112
 * Modules may "suggest" menu items that the administrator may enable. They act
 * just as callbacks do until enabled, at which time they act like normal items.
Dries's avatar
 
Dries committed
113
 */
114
define('MENU_SUGGESTED_ITEM', MENU_MODIFIABLE_BY_ADMIN | MENU_VISIBLE_IN_BREADCRUMB);
Dries's avatar
 
Dries committed
115 116

/**
Dries's avatar
 
Dries committed
117 118 119
 * Local tasks are rendered as tabs by default. Use this for menu items that
 * describe actions to be performed on their parent item. An example is the path
 * "node/52/edit", which performs the "edit" task on "node/52".
Dries's avatar
 
Dries committed
120 121 122
 */
define('MENU_LOCAL_TASK', MENU_IS_LOCAL_TASK);

Dries's avatar
 
Dries committed
123 124 125 126 127 128
/**
 * Every set of local tasks should provide one "default" task, that links to the
 * same path as its parent when clicked.
 */
define('MENU_DEFAULT_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT);

Dries's avatar
 
Dries committed
129
/**
Dries's avatar
 
Dries committed
130 131
 * Custom items are those defined by the administrator. Reserved for internal
 * use; do not return from hook_menu() implementations.
Dries's avatar
 
Dries committed
132 133 134 135
 */
define('MENU_CUSTOM_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB | MENU_CREATED_BY_ADMIN | MENU_MODIFIABLE_BY_ADMIN);

/**
Dries's avatar
 
Dries committed
136 137
 * Custom menus are those defined by the administrator. Reserved for internal
 * use; do not return from hook_menu() implementations.
Dries's avatar
 
Dries committed
138 139 140 141
 */
define('MENU_CUSTOM_MENU', MENU_IS_ROOT | MENU_VISIBLE_IN_TREE | MENU_CREATED_BY_ADMIN | MENU_MODIFIABLE_BY_ADMIN);

/**
Dries's avatar
 
Dries committed
142
 * @} End of "Menu item types".
Dries's avatar
 
Dries committed
143 144 145 146 147
 */

/**
 * @name Menu status codes
 * @{
Dries's avatar
 
Dries committed
148 149
 * Status codes for menu callbacks.
 */
Dries's avatar
 
Dries committed
150

Dries's avatar
 
Dries committed
151 152 153
define('MENU_FOUND', 1);
define('MENU_NOT_FOUND', 2);
define('MENU_ACCESS_DENIED', 3);
154
define('MENU_SITE_OFFLINE', 4);
Dries's avatar
 
Dries committed
155

Dries's avatar
 
Dries committed
156
/**
Dries's avatar
 
Dries committed
157
 * @} End of "Menu status codes".
Dries's avatar
 
Dries committed
158
 */
159

160 161 162 163 164 165 166 167 168 169 170 171 172
/**
 * @Name Menu operations
 * @{
 * Menu helper possible operations.
 */

define('MENU_HANDLE_REQUEST', 0);
define('MENU_RENDER_LINK', 1);

/**
 * @} End of "Menu helper directions
 */

173
/**
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
 * Returns the ancestors (and relevant placeholders) for any given path.
 *
 * For example, the ancestors of node/12345/edit are:
 *
 * node/12345/edit
 * node/12345/%
 * node/%/edit
 * node/%/%
 * node/12345
 * node/%
 * node
 *
 * To generate these, we will use binary numbers. Each bit represents a
 * part of the path. If the bit is 1, then it represents the original
 * value while 0 means wildcard. If the path is node/12/edit/foo
 * then the 1011 bitstring represents node/%/edit/foo where % means that
 * any argument matches that part.
 *
 * @param $parts
 *   An array of path parts, for the above example
 *   array('node', '12345', 'edit').
 * @return
 *   An array which contains the ancestors and placeholders. Placeholders
197
 *   simply contain as many '%s' as the ancestors.
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
 */
function menu_get_ancestors($parts) {
  $n1 = count($parts);
  $placeholders = array();
  $ancestors = array();
  $end = (1 << $n1) - 1;
  $length = $n1 - 1;
  for ($i = $end; $i > 0; $i--) {
    $current = '';
    $count = 0;
    for ($j = $length; $j >= 0; $j--) {
      if ($i & (1 << $j)) {
        $count++;
        $current .= $parts[$length - $j];
      }
      else {
        $current .= '%';
      }
      if ($j) {
        $current .= '/';
      }
Dries's avatar
 
Dries committed
219
    }
220 221 222 223
    // If the number was like 10...0 then the next number will be 11...11,
    // one bit less wide.
    if ($count == 1) {
      $length--;
Dries's avatar
 
Dries committed
224
    }
225 226
    $placeholders[] = "'%s'";
    $ancestors[] = $current;
227
  }
228
  return array($ancestors, $placeholders);
Dries's avatar
 
Dries committed
229 230 231
}

/**
232 233 234 235
 * The menu system uses serialized arrays stored in the database for
 * arguments. However, often these need to change according to the
 * current path. This function unserializes such an array and does the
 * necessary change.
Dries's avatar
 
Dries committed
236
 *
237 238 239 240 241 242
 * Integer values are mapped according to the $map parameter. For
 * example, if unserialize($data) is array('node_load', 1) and $map is
 * array('node', '12345') then 'node_load' will not be changed
 * because it is not an integer, but 1 will as it is an integer. As
 * $map[1] is '12345', 1 will be replaced with '12345'. So the result
 * will be array('node_load', '12345').
243
 *
244 245 246 247
 * @param @data
 *   A serialized array.
 * @param @map
 *   An array of potential replacements.
248
 * @return
249
 *   The $data array unserialized and mapped.
250
 */
251 252 253 254 255 256 257 258
function menu_unserialize($data, $map) {
  if ($data = unserialize($data)) {
    foreach ($data as $k => $v) {
      if (is_int($v)) {
        $data[$k] = isset($map[$v]) ? $map[$v] : '';
      }
    }
    return $data;
259
  }
260 261
  else {
    return array();
262 263 264 265
  }
}

/**
266
 * Replaces the statically cached item for a given path.
267
 *
268 269 270 271 272
 * @param $path
 *   The path
 * @param $item
 *   The menu item. This is a menu entry, an associative array,
 *   with keys like title, access callback, access arguments etc.
273
 */
274
function menu_set_item($path, $item) {
275
  menu_get_item($path, $item);
276 277
}

278
function menu_get_item($path = NULL, $item = NULL) {
279 280 281 282 283 284 285 286
  static $items;
  if (!isset($path)) {
    $path = $_GET['q'];
  }
  if (isset($item)) {
    $items[$path] = $item;
  }
  if (!isset($items[$path])) {
287 288
    $original_map = arg(NULL, $path);
    $parts = array_slice($original_map, 0, 6);
289 290
    list($ancestors, $placeholders) = menu_get_ancestors($parts);
    if ($item = db_fetch_object(db_query_range('SELECT * FROM {menu} WHERE path IN ('. implode (',', $placeholders) .') ORDER BY fit DESC', $ancestors, 0, 1))) {
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
      // We need to access check the parents to match the navigation tree
      // behaviour. The last parent is always the item itself.
      $result = db_query('SELECT * FROM {menu} WHERE mid IN ('. $item->parents .') ORDER BY mleft');
      $item->access = TRUE;
      while ($item->access && ($parent = db_fetch_object($result)))  {
        $map = _menu_translate($parent, $original_map);
        if ($map === FALSE) {
          $items[$path] = FALSE;
          return FALSE;
        }
        $item->access = $item->access && $parent->access;
        $item->active_trail[] = $parent;
      }
      if ($item->access) {
        $item->map = $map;
        $item->page_arguments = array_merge(menu_unserialize($item->page_arguments, $map), array_slice($parts, $item->number_parts));
Dries's avatar
 
Dries committed
307 308
      }
    }
309
    $items[$path] = $item;
Dries's avatar
 
Dries committed
310
  }
311
  return $items[$path];
Dries's avatar
 
Dries committed
312 313 314 315 316 317
}

/**
 * Execute the handler associated with the active menu item.
 */
function menu_execute_active_handler() {
318 319
  if ($item = menu_get_item()) {
    return $item->access ? call_user_func_array($item->page_callback, $item->page_arguments) : MENU_ACCESS_DENIED;
Dries's avatar
 
Dries committed
320
  }
321 322
  return MENU_NOT_FOUND;
}
Dries's avatar
 
Dries committed
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
/**
 * Handles dynamic path translation and menu access control.
 *
 * When a user arrives on a page such as node/5, this function determines
 * what "5" corresponds to, by inspecting the page's menu path definition,
 * node/%node. This will call node_load(5) to load the corresponding node
 * object.
 *
 * It also works in reverse, to allow the display of tabs and menu items which
 * contain these dynamic arguments, translating node/%node to node/5.
 * This operation is called MENU_RENDER_LINK.
 *
 * @param $item
 *   A menu item object
 * @param $map
 *   An array of path arguments (ex: array('node', '5'))
 * @param $operation
 *   The path translation operation to perform:
 *   - MENU_HANDLE_REQUEST: An incoming page reqest; map with appropriate callback.
 *   - MENU_RENDER_LINK: Render an internal path as a link.
 * @return
345 346 347 348 349 350 351
 *   Returns the map with objects loaded as defined in the
 *   $item->load_functions. Also, $item->link_path becomes the path ready
 *   for printing, aliased. $item->alias becomes TRUE to mark this, so you can
 *   just pass (array)$item to l() as the third parameter.
 *   $item->access becomes TRUE if the item is accessible, FALSE otherwise.
  */
function _menu_translate(&$item, $map, $operation = MENU_HANDLE_REQUEST) {
352
  // Check if there are dynamic arguments in the path that need to be calculated.
353 354 355 356
  // If there are to_arg_functions, then load_functions is also not empty
  // because it was built so in menu_rebuild. Therefore, it's enough to test
  // load_functions.
  if ($item->load_functions) {
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    $load_functions = unserialize($item->load_functions);
    $to_arg_functions = unserialize($item->to_arg_functions);
    $path_map = ($operation == MENU_HANDLE_REQUEST) ? $map : explode('/', $item->path);
    foreach ($load_functions as $index => $load_function) {
      // Translate place-holders into real values.
      if ($operation == MENU_RENDER_LINK) {
        if (isset($to_arg_functions[$index])) {
          $to_arg_function = $to_arg_functions[$index];
          $return = $to_arg_function(!empty($map[$index]) ? $map[$index] : '');
          if (!empty($map[$index]) || isset($return)) {
            $path_map[$index] = $return;
          }
          else {
            unset($path_map[$index]);
          }
        }
        else {
          $path_map[$index] = isset($map[$index]) ? $map[$index] : '';
        }
      }
      // We now have a real path regardless of operation, map it.
      if ($load_function) {
        $return = $load_function(isset($path_map[$index]) ? $path_map[$index] : '');
        // If callback returned an error or there is no callback, trigger 404.
        if ($return === FALSE) {
          return array(FALSE, FALSE, '');
        }
        $map[$index] = $return;
      }
    }
387 388
    // Re-join the path with the new replacement value and alias it.
    $item->link_path = drupal_get_path_alias(implode('/', $path_map));
389 390 391
  }
  // Determine access callback, which will decide whether or not the current user has
  // access to this path.
392
  $callback = $item->access_callback;
393
  // Check for a TRUE or FALSE value.
394
  if (is_numeric($callback)) {
395
    $item->access = $callback;
Dries's avatar
 
Dries committed
396
  }
397 398 399 400 401
  else {
    $arguments = menu_unserialize($item->access_arguments, $map);
    // As call_user_func_array is quite slow and user_access is a very common
    // callback, it is worth making a special case for it.
    if ($callback == 'user_access') {
402
      $item->access = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
403 404
    }
    else {
405
      $item->access = call_user_func_array($callback, $arguments);
406
    }
Dries's avatar
 
Dries committed
407
  }
408 409
  $item->alias = TRUE;
  return $map;
Dries's avatar
 
Dries committed
410 411
}

Dries's avatar
 
Dries committed
412
/**
413
 * Returns a rendered menu tree.
Dries's avatar
 
Dries committed
414
 */
415
function menu_tree() {
416
  if ($item = menu_get_item()) {
417
    list(, $menu) = _menu_tree(db_query('SELECT * FROM {menu} WHERE pid IN ('. $item->parents .') AND visible = 1 ORDER BY mleft'));
418 419
    return $menu;
  }
Dries's avatar
 
Dries committed
420 421
}

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
/**
 * Renders a menu tree from a database result resource.
 *
 * The function is a bit complex because the rendering of an item depends on
 * the next menu item. So we are always rendering the element previously
 * processed not the current one.
 *
 * @param $result
 *   The database result.
 * @param $depth
 *   The depth of the current menu tree.
 * @param $link
 *   The first link in the current menu tree.
 * @param $has_children
 *  Whether the first link has children.
 * @return
 *   A list, the first element is the first item after the submenu, the second
 *   is the rendered HTML of the children.
 */
function _menu_tree($result = NULL, $depth = 0, $link = '', $has_children = FALSE) {
442
  static $map;
443
  $remnant = NULL;
444
  $tree = '';
445
  // Fetch the current path and cache it.
446 447 448
  if (!isset($map)) {
    $map = arg(NULL);
  }
449
  while ($item = db_fetch_object($result)) {
450 451 452
    // Access check and handle dynamic path translation.
    _menu_translate($item, $map, MENU_RENDER_LINK);
    if (!$item->access) {
453
      continue;
Dries's avatar
 
Dries committed
454
    }
455 456 457 458
    if ($item->attributes) {
      $item->attributes = unserialize($item->attributes);
    }
    // The current item is the first in a new submenu.
459
    if ($item->depth > $depth) {
460 461 462 463 464 465 466 467 468
      // _menu_tree returns an item and the HTML of the rendered menu tree.
      list($item, $menu) = _menu_tree($result, $item->depth, theme('menu_item_link', $item), $item->has_children);
      // Theme the menu.
      $menu = $menu ? theme('menu_tree', $menu) : '';
      // $link is the previous element.
      $tree .= $link ? theme('menu_item', $link, $has_children, $menu) : $menu;
      // This will be the link to be output in the next iteration.
      $link = $item ? theme('menu_item_link', $item) : '';
      $has_children = $item ? $item->has_children : FALSE;
Dries's avatar
 
Dries committed
469
    }
470
    // We are in the same menu. We render the previous element.
471
    elseif ($item->depth == $depth) {
472 473 474 475 476
      // $link is the previous element.
      $tree .= theme('menu_item', $link, $has_children);
      // This will be the link to be output in the next iteration.
      $link = theme('menu_item_link', $item);
      $has_children = $item->has_children;
Dries's avatar
 
Dries committed
477
    }
478 479
    // The submenu ended with the previous item, we need to pass back the
    // current element.
480
    else {
481
      $remnant = $item;
482
      break;
Dries's avatar
 
Dries committed
483
    }
Dries's avatar
 
Dries committed
484
  }
485 486 487
  if ($link) {
    // We have one more link dangling.
    $tree .= theme('menu_item', $link, $has_children);
488 489
  }
  return array($remnant, $tree);
Dries's avatar
 
Dries committed
490 491
}

Dries's avatar
 
Dries committed
492
/**
493
 * Generate the HTML output for a single menu link.
Dries's avatar
 
Dries committed
494
 */
495 496 497
function theme_menu_item_link($item) {
  $link = (array)$item;
  return l($link['title'], $link['link_path'], $link);
Dries's avatar
 
Dries committed
498 499
}

Dries's avatar
 
Dries committed
500
/**
501
 * Generate the HTML output for a menu tree
Dries's avatar
 
Dries committed
502
 */
503 504 505 506 507 508 509 510 511
function theme_menu_tree($tree) {
  return '<ul class="menu">'. $tree .'</ul>';
}

/**
 * Generate the HTML output for a menu item and submenu.
 */
function theme_menu_item($link, $has_children, $menu = '') {
  return '<li class="'. ($menu ? 'expanded' : ($has_children ? 'collapsed' : 'leaf')) .'">'. $link . $menu .'</li>' . "\n";
512 513 514 515
}

function theme_menu_local_task($link, $active = FALSE) {
  return '<li '. ($active ? 'class="active" ' : ''). '>'. $link .'</li>';
516
}
Dries's avatar
 
Dries committed
517

Dries's avatar
 
Dries committed
518
/**
Dries's avatar
 
Dries committed
519 520
 * Returns the help associated with the active menu item.
 */
521
function menu_get_active_help() {
Dries's avatar
 
Dries committed
522 523
  $path = $_GET['q'];
  $output = '';
524
  $item = menu_get_item();
Dries's avatar
 
Dries committed
525

526
  if (!$item->access) {
Dries's avatar
 
Dries committed
527 528 529
    // Don't return help text for areas the user cannot access.
    return;
  }
Dries's avatar
 
Dries committed
530

Dries's avatar
 
Dries committed
531 532 533
  foreach (module_list() as $name) {
    if (module_hook($name, 'help')) {
      if ($temp = module_invoke($name, 'help', $path)) {
534
        $output .= $temp ."\n";
Dries's avatar
 
Dries committed
535
      }
536
      if (module_hook('help', 'page')) {
537
        if (arg(0) == "admin") {
538 539
          if (module_invoke($name, 'help', 'admin/help#'. arg(2)) && !empty($output)) {
            $output .= theme("more_help_link", url('admin/help/'. arg(2)));
540
          }
Dries's avatar
 
Dries committed
541 542
        }
      }
Dries's avatar
 
Dries committed
543
    }
Dries's avatar
 
Dries committed
544
  }
Dries's avatar
 
Dries committed
545
  return $output;
546 547
}

548
/**
Dries's avatar
 
Dries committed
549
 * Populate the database representation of the menu.
550
 */
Dries's avatar
 
Dries committed
551
function menu_rebuild() {
552
  // TODO: split menu and menu links storage.
553 554
  db_query('DELETE FROM {menu}');
  $menu = module_invoke_all('menu');
555
  drupal_alter('menu', $menu);
556
  $mid = 1;
557 558
  // First pass: separate callbacks from pathes, making pathes ready for
  // matching. Calculate fitness, and fill some default values.
559 560 561
  foreach ($menu as $path => $item) {
    $parts = explode('/', $path, 6);
    $number_parts = count($parts);
562
    // We store the highest index of parts here to save some work in the fit
563 564
    // calculation loop.
    $slashes = $number_parts - 1;
565 566 567 568 569 570 571 572 573
    $fit = 0;
    $load_functions = array();
    $to_arg_functions = array();
    // extract functions
    foreach ($parts as $k => $part) {
      $match = FALSE;
      if (preg_match('/^%([a-z_]*)$/', $part, $matches)) {
        if (empty($matches[1])) {
          $match = TRUE;
Dries's avatar
Dries committed
574
          $load_functions[$k] = NULL;
575 576 577 578
        }
        else {
          if (function_exists($matches[1] .'_to_arg')) {
            $to_arg_functions[$k] = $matches[1].'_to_arg';
Dries's avatar
Dries committed
579
            $load_functions[$k] = NULL;
580 581
            $match = TRUE;
          }
Dries's avatar
Dries committed
582 583 584
          if (function_exists($matches[1] .'_load')) {
            $load_functions[$k] = $matches[1] .'_load';
            $match = TRUE;
585 586 587 588 589 590 591 592 593 594 595 596
          }
        }
      }
      if ($match) {
        $parts[$k] = '%';
      }
      else {
        $fit |=  1 << ($slashes - $k);
      }
    }
    $item['load_functions'] = empty($load_functions) ? '' : serialize($load_functions);
    $item['to_arg_functions'] = empty($to_arg_functions) ? '' : serialize($to_arg_functions);
597
    // If there is no %, it fits maximally.
598
    if (!$fit) {
599
      $fit = (1 << $number_parts) - 1;
600
      $move = FALSE;
601
    }
602
    else {
603
      $move = TRUE;
604
    }
605 606 607 608 609 610 611 612
    $item += array(
      'title' => '',
      'weight' => 0,
      'type' => MENU_NORMAL_ITEM,
      '_number_parts' => $number_parts,
      '_parts' => $parts,
      '_fit' => $fit,
      '_mid' => $mid++,
613
      '_children' => array(),
614 615 616 617 618 619 620 621
    );
    $item += array(
      '_visible' => (bool)($item['type'] & MENU_VISIBLE_IN_TREE),
      '_tab' => (bool)($item['type'] & MENU_IS_LOCAL_TASK),
    );
    if ($move) {
      $new_path = implode('/', $item['_parts']);
      unset($menu[$path]);
622
    }
623 624
    else {
      $new_path = $path;
625
    }
626
    $menu_path_map[$path] = $new_path;
627 628
    $menu[$new_path] = $item;
  }
629 630
  $menu_path_map[''] = '';
  // Second pass: prepare for sorting and find parents.
631 632 633
  foreach ($menu as $path => $item) {
    $item = &$menu[$path];
    $number_parts = $item['_number_parts'];
634 635
    if (isset($item['parent'])) {
      $parent_parts = explode('/', $menu_path_map[$item['parent']], 6);
636 637 638 639
      $slashes = count($parent_parts) - 1;
    }
    else {
      $parent_parts = $item['_parts'];
640
      $slashes = $number_parts - 1;
641 642
    }
    $depth = 1;
643
    $parents = array($item['_mid']);
644
    for ($i = $slashes; $i; $i--) {
645
      $parent_path = implode('/', array_slice($parent_parts, 0, $i));
646 647 648 649 650 651 652
      if (isset($menu[$parent_path]) && $menu[$parent_path]['_visible']) {
        $parent = $menu[$parent_path];
        $parents[] = $parent['_mid'];
        $depth++;
        if (!isset($item['_pid'])) {
          $item['_pid'] = $parent['_mid'];
          $item['_visible_parent_path'] = $parent_path;
Dries's avatar
 
Dries committed
653
        }
654 655 656 657 658 659 660
      }
    }
    $parents[] = 0;
    $parents = implode(',', array_reverse($parents));
    // Store variables and set defaults.
    $item += array(
      '_pid' => 0,
661
      '_depth' => ($item['_visible'] ? $depth : $number_parts),
662
      '_parents' => $parents,
663 664
      '_parent_parts' => $parent_parts,
      '_slashes' => $slashes,
665
    );
666 667 668
    // This sorting works correctly only with positive numbers,
    // so we shift negative weights to be positive.
    $sort[$path] = $item['_depth'] . sprintf('%05d', $item['weight'] + 50000) . $item['title'];
669 670 671
    unset($item);
  }
  array_multisort($sort, $menu);
672 673 674 675 676 677 678 679 680
  // We are now sorted, so let's build the tree.
  $children = array();
  foreach ($menu as $path => $item) {
    if ($item['_pid']) {
      $menu[$item['_visible_parent_path']]['_children'][] = $path;
    }
  }
  menu_renumber($menu);
  // Apply inheritance rules.
681 682 683 684 685 686 687 688 689
  foreach ($menu as $path => $item) {
    $item = &$menu[$path];
    for ($i = $item['_number_parts'] - 1; $i; $i--) {
      $parent_path = implode('/', array_slice($item['_parts'], 0, $i));
      if (isset($menu[$parent_path])) {
        $parent = $menu[$parent_path];
        // If a callback is not found, we try to find the first parent that
        // has this callback. When found, its callback argument will also be
        // copied but only if there is none in the current item.
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

        // Because access is checked for each parent as well, we only inherit
        // if arguments were given without a callback. Otherwise the inherited
        // check would be identical to that of the parent.
        if (!isset($item['access callback']) && isset($parent['access callback']) && !isset($parent['access inherited'])) {
          if (isset($item['access arguments'])) {
            $item['access callback'] = $parent['access callback'];
          }
          else {
            $item['access callback'] = 1;
            // If a children of this element has an argument, we need to pair
            // that with a real callback, not the 1 we set above.
            $item['access inherited'] = TRUE;
          }
        }

        // Unlike access callbacks, there are no shortcuts for page callbacks.
        if (!isset($item['page callback']) && isset($parent['page callback'])) {
          $item['page callback'] = $parent['page callback'];
          if (!isset($item['page arguments']) && isset($parent['page arguments'])) {
            $item['page arguments'] = $parent['page arguments'];
711
          }
Dries's avatar
 
Dries committed
712 713 714
        }
      }
    }
715
    if (!isset($item['access callback'])) {
716
      $item['access callback'] = isset($item['access arguments']) ? 'user_access' : 0;
717
    }
718 719
    if (is_bool($item['access callback'])) {
      $item['access callback'] = intval($item['access callback']);
Dries's avatar
 
Dries committed
720
    }
721 722
    if ($item['_tab']) {
      if (!isset($item['parent'])) {
723 724
        $item['parent'] = implode('/', array_slice($item['_parts'], 0, $item['_number_parts'] - 1));
      }
Dries's avatar
Dries committed
725
      else {
726
        $item['_depth'] = $item['parent'] ? $menu[$menu_path_map[$item['parent']]]['_depth'] + 1 : 1;
Dries's avatar
Dries committed
727
      }
728 729 730 731 732
    }
    else {
      // Non-tab items specified the parent for visible links, and it's
      // stored in parents, parent stores the tab parent.
      $item['parent'] = $path;
733
    }
734 735 736
    $insert_item = $item;
    unset($item);
    $item = $insert_item + array(
737 738 739 740
      'access arguments' => array(),
      'access callback' => '',
      'page arguments' => array(),
      'page callback' => '',
741 742
      '_mleft' => 0,
      '_mright' => 0,
743 744
      'block callback' => '',
      'description' => '',
745
      'position' => '',
746 747 748 749 750
      'attributes' => '',
      'query' => '',
      'fragment' => '',
      'absolute' => '',
      'html' => '',
751
    );
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
    $link_path = $item['to_arg_functions'] ? $path : drupal_get_path_alias($path);

    if ($item['attributes']) {
      $item['attributes'] = serialize($item['attributes']);
    }

    // Check for children that are visible in the menu
    $has_children = FALSE;
    foreach ($item['_children'] as $child) {
      if ($menu[$child]['_visible']) {
        $has_children = TRUE;
        break;
      }
    }

767
    db_query("INSERT INTO {menu} (
768 769
      mid, pid, path, load_functions, to_arg_functions,
      access_callback, access_arguments, page_callback, page_arguments, fit,
770
      number_parts, visible, parents, depth, has_children, tab, title, parent,
771
      type, mleft, mright, block_callback, description, position,
772
      link_path, attributes, query, fragment, absolute, html)
773
      VALUES (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d,
774
      '%s', %d, %d, %d, '%s', '%s', '%s', %d, %d, '%s', '%s', '%s',
775
      '%s', '%s', '%s', '%s', %d, %d)",
776 777 778 779 780
      $item['_mid'], $item['_pid'], $path, $item['load_functions'],
      $item['to_arg_functions'], $item['access callback'],
      serialize($item['access arguments']), $item['page callback'],
      serialize($item['page arguments']), $item['_fit'],
      $item['_number_parts'], $item['_visible'], $item['_parents'],
781
      $item['_depth'], $has_children, $item['_tab'],
782
      $item['title'], $item['parent'], $item['type'], $item['_mleft'],
783
      $item['_mright'], $item['block callback'], $item['description'],
784 785
      $item['position'], $link_path,
      $item['attributes'], $item['query'], $item['fragment'],
786
      $item['absolute'], $item['html']);
787 788 789
  }
}

790 791


792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
function menu_renumber(&$tree) {
  foreach ($tree as $key => $element) {
    if (!isset($tree[$key]['_mleft'])) {
      _menu_renumber($tree, $key);
    }
  }
}

function _menu_renumber(&$tree, $key) {
  static $counter = 1;
  if (!isset($tree[$key]['_mleft'])) {
    $tree[$key]['_mleft'] = $counter++;
    foreach ($tree[$key]['_children'] as $child_key) {
      _menu_renumber($tree, $child_key);
    }
    $tree[$key]['_mright'] = $counter++;
  }
Dries's avatar
 
Dries committed
809 810
}

811 812
// Placeholders.
function menu_primary_links() {
Dries's avatar
 
Dries committed
813 814
}

815
function menu_secondary_links() {
Dries's avatar
 
Dries committed
816 817
}

818 819 820 821
/**
 * Collects the local tasks (tabs) for a given level.
 *
 * @param $level
822
 *   The level of tasks you ask for. Primary tasks are 0, secondary are 1...
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
 * @return
 *   An array of links to the tabs.
 */
function menu_local_tasks($level = 0) {
  static $tabs = array(), $parents = array(), $parents_done = array();
  if (empty($tabs)) {
    $router_item = menu_get_item();
    $map = arg(NULL);
    do {
      // Tabs are router items that have the same parent. If there is a new
      // parent, let's add it the queue.
      if (!empty($router_item->parent)) {
        $parents[] = $router_item->parent;
        // Do not add the same item twice.
        $router_item->parent = '';
838
      }
839 840 841 842
      $parent = array_shift($parents);
      // Do not process the same parent twice.
      if (isset($parents_done[$parent])) {
        continue;
843
      }
844
      // This loads all the tabs.
845
      $result = db_query("SELECT * FROM {menu} WHERE parent = '%s' AND tab = 1 ORDER BY mleft", $parent);
846 847 848 849
      $tabs_current = '';
      while ($item = db_fetch_object($result)) {
        // This call changes the path from for example user/% to user/123 and
        // also determines whether we are allowed to access it.
850 851
         _menu_translate($item, $map, MENU_RENDER_LINK);
        if ($item->access) {
852
          $depth = $item->depth;
853
          $link = l($item->title, $item->link_path, (array)$item);
854
          // We check for the active tab.
855
          if ($item->path == $router_item->path || (!$router_item->tab && $item->type == MENU_DEFAULT_LOCAL_TASK)) {
856 857 858 859 860 861 862 863 864 865
            $tabs_current .= theme('menu_local_task', $link, TRUE);
            // Let's try to find the router item one level up.
            $next_router_item = db_fetch_object(db_query("SELECT path, tab, parent FROM {menu} WHERE path = '%s'", $item->parent));
            // We will need to inspect one level down.
            $parents[] = $item->path;
          }
          else {
            $tabs_current .= theme('menu_local_task', $link);
          }
        }
866
      }
867 868 869 870 871 872 873 874 875 876 877 878 879 880
      // If there are tabs, let's add them
      if ($tabs_current) {
        $tabs[$depth] = $tabs_current;
      }
      $parents_done[$parent] = TRUE;
      if (isset($next_router_item)) {
        $router_item = $next_router_item;
      }
      unset($next_router_item);
    } while ($parents);
    // Sort by depth
    ksort($tabs);
    // Remove the depth, we are interested only in their relative placement.
    $tabs = array_values($tabs);
881
  }
882 883 884 885 886
  return isset($tabs[$level]) ? $tabs[$level] : array();
}

function menu_primary_local_tasks() {
  return menu_local_tasks();
887
}
888

889
function menu_secondary_local_tasks() {
890
  return menu_local_tasks(1);
Dries's avatar
 
Dries committed
891 892
}

893
function menu_set_active_item() {
Dries's avatar
 
Dries committed
894 895
}

896
function menu_set_location() {
Dries's avatar
 
Dries committed
897 898
}

899
function menu_get_active_breadcrumb() {
900 901 902 903 904 905
  $breadcrumb = array(l(t('Home'), ''));
  $item = menu_get_item();
  foreach ($item->active_trail as $parent) {
    $breadcrumb[] = l($parent->title, $parent->link_path, (array)$parent);
  }
  return $breadcrumb;
906
}
907

908 909
function menu_get_active_title() {
  $item = menu_get_item();
910 911 912 913 914
  foreach (array_reverse($item->active_trail) as $item) {
    if (!($item->type & MENU_IS_LOCAL_TASK)) {
      return $item->title;
    }
  }
915
}