5 * API for the Drupal menu system.
9 * @defgroup menu Menu system
11 * Define the navigation menus, and route page requests to code based on URLs.
13 * The Drupal menu system drives both the navigation system from a user
14 * perspective and the callback system that Drupal uses to respond to URLs
15 * passed from the browser. For this reason, a good understanding of the
16 * menu system is fundamental to the creation of complex modules.
18 * Drupal's menu system follows a simple hierarchy defined by paths.
19 * Implementations of hook_menu() define menu items and assign them to
20 * paths (which should be unique). The menu system aggregates these items
21 * and determines the menu hierarchy from the paths. For example, if the
22 * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
23 * would form the structure:
30 * Note that the number of elements in the path does not necessarily
31 * determine the depth of the menu item in the tree.
33 * When responding to a page request, the menu system looks to see if the
34 * path requested by the browser is registered as a menu item with a
35 * callback. If not, the system searches up the menu tree for the most
36 * complete match with a callback it can find. If the path a/b/i is
37 * requested in the tree above, the callback for a/b would be used.
39 * The found callback function is called with any arguments specified
40 * in the "page arguments" attribute of its menu item. The
41 * attribute must be an array. After these arguments, any remaining
42 * components of the path are appended as further arguments. In this
43 * way, the callback for a/b above could respond to a request for
44 * a/b/i differently than a request for a/b/j.
46 * For an illustration of this process, see page_example.module.
48 * Access to the callback functions is also protected by the menu system.
49 * The "access callback" with an optional "access arguments" of each menu
50 * item is called before the page callback proceeds. If this returns TRUE,
51 * then access is granted; if FALSE, then access is denied. Menu items may
52 * omit this attribute to use the value provided by an ancestor item.
54 * In the default Drupal interface, you will notice many links rendered as
55 * tabs. These are known in the menu system as "local tasks", and they are
56 * rendered as tabs by default, though other presentations are possible.
57 * Local tasks function just as other menu items in most respects. It is
58 * convention that the names of these tasks should be short verbs if
59 * possible. In addition, a "default" local task should be provided for
60 * each set. When visiting a local task's parent menu item, the default
61 * local task will be rendered as if it is selected; this provides for a
62 * normal tab user experience. This default task is special in that it
63 * links not to its provided path, but to its parent item's path instead.
64 * The default task's path is only used to place it appropriately in the
67 * Everything described so far is stored in the menu_router table. The
68 * menu_links table holds the visible menu links. By default these are
69 * derived from the same hook_menu definitions, however you are free to
70 * add more with menu_link_save().
74 * @defgroup menu_flags Menu flags
76 * Flags for use in the "type" attribute of menu items.
79 define('MENU_IS_ROOT', 0x0001);
80 define('MENU_VISIBLE_IN_TREE', 0x0002);
81 define('MENU_VISIBLE_IN_BREADCRUMB', 0x0004);
82 define('MENU_LINKS_TO_PARENT', 0x0008);
83 define('MENU_MODIFIED_BY_ADMIN', 0x0020);
84 define('MENU_CREATED_BY_ADMIN', 0x0040);
85 define('MENU_IS_LOCAL_TASK', 0x0080);
88 * @} End of "Menu flags".
92 * @defgroup menu_item_types Menu item types
94 * Definitions for various menu item types.
96 * Menu item definitions provide one of these constants, which are shortcuts for
97 * combinations of the above flags.
101 * Normal menu items show up in the menu tree and can be moved/hidden by
102 * the administrator. Use this for most menu items. It is the default value if
103 * no menu item type is specified.
105 define('MENU_NORMAL_ITEM', MENU_VISIBLE_IN_TREE
| MENU_VISIBLE_IN_BREADCRUMB
);
108 * Callbacks simply register a path so that the correct function is fired
109 * when the URL is accessed. They are not shown in the menu.
111 define('MENU_CALLBACK', MENU_VISIBLE_IN_BREADCRUMB
);
114 * Modules may "suggest" menu items that the administrator may enable. They act
115 * just as callbacks do until enabled, at which time they act like normal items.
116 * Note for the value: 0x0010 was a flag which is no longer used, but this way
117 * the values of MENU_CALLBACK and MENU_SUGGESTED_ITEM are separate.
119 define('MENU_SUGGESTED_ITEM', MENU_VISIBLE_IN_BREADCRUMB
| 0x0010);
122 * Local tasks are rendered as tabs by default. Use this for menu items that
123 * describe actions to be performed on their parent item. An example is the path
124 * "node/52/edit", which performs the "edit" task on "node/52".
126 define('MENU_LOCAL_TASK', MENU_IS_LOCAL_TASK
);
129 * Every set of local tasks should provide one "default" task, that links to the
130 * same path as its parent when clicked.
132 define('MENU_DEFAULT_LOCAL_TASK', MENU_IS_LOCAL_TASK
| MENU_LINKS_TO_PARENT
);
135 * @} End of "Menu item types".
139 * @defgroup menu_status_codes Menu status codes
141 * Status codes for menu callbacks.
144 define('MENU_FOUND', 1);
145 define('MENU_NOT_FOUND', 2);
146 define('MENU_ACCESS_DENIED', 3);
147 define('MENU_SITE_OFFLINE', 4);
150 * @} End of "Menu status codes".
154 * @defgroup menu_tree_parameters Menu tree parameters
156 * Parameters for a menu tree.
160 * The maximum number of path elements for a menu callback
162 define('MENU_MAX_PARTS', 7);
166 * The maximum depth of a menu links tree - matches the number of p columns.
168 define('MENU_MAX_DEPTH', 9);
172 * @} End of "Menu tree parameters".
176 * Returns the ancestors (and relevant placeholders) for any given path.
178 * For example, the ancestors of node/12345/edit are:
187 * To generate these, we will use binary numbers. Each bit represents a
188 * part of the path. If the bit is 1, then it represents the original
189 * value while 0 means wildcard. If the path is node/12/edit/foo
190 * then the 1011 bitstring represents node/%/edit/foo where % means that
191 * any argument matches that part. We limit ourselves to using binary
192 * numbers that correspond the patterns of wildcards of router items that
193 * actually exists. This list of 'masks' is built in menu_rebuild().
196 * An array of path parts, for the above example
197 * array('node', '12345', 'edit').
199 * An array which contains the ancestors and placeholders. Placeholders
200 * simply contain as many '%s' as the ancestors.
202 function menu_get_ancestors($parts) {
203 $number_parts = count($parts);
204 $placeholders = array();
205 $ancestors = array();
206 $length = $number_parts - 1;
207 $end = (1 << $number_parts) - 1;
208 $masks = variable_get('menu_masks', array());
209 // Only examine patterns that actually exist as router items (the masks).
210 foreach ($masks as
$i) {
212 // Only look at masks that are not longer than the path of interest.
215 elseif ($i < (1 << $length)) {
216 // We have exhausted the masks of a given length, so decrease the length.
220 for ($j = $length; $j >= 0; $j--) {
221 if ($i & (1 << $j)) {
222 $current .
= $parts[$length - $j];
231 $placeholders[] = "'%s'";
232 $ancestors[] = $current;
234 return array($ancestors, $placeholders);
238 * The menu system uses serialized arrays stored in the database for
239 * arguments. However, often these need to change according to the
240 * current path. This function unserializes such an array and does the
243 * Integer values are mapped according to the $map parameter. For
244 * example, if unserialize($data) is array('view', 1) and $map is
245 * array('node', '12345') then 'view' will not be changed because
246 * it is not an integer, but 1 will as it is an integer. As $map[1]
247 * is '12345', 1 will be replaced with '12345'. So the result will
248 * be array('node_load', '12345').
251 * A serialized array.
253 * An array of potential replacements.
255 * The $data array unserialized and mapped.
257 function menu_unserialize($data, $map) {
258 if ($data = unserialize($data)) {
259 foreach ($data as
$k => $v) {
261 $data[$k] = isset($map[$v]) ?
$map[$v] : '';
274 * Replaces the statically cached item for a given path.
278 * @param $router_item
279 * The router item. Usually you take a router entry from menu_get_item and
280 * set it back either modified or to a different path. This lets you modify the
281 * navigation block, the page title, the breadcrumb and the page help in one
284 function menu_set_item($path, $router_item) {
285 menu_get_item($path, $router_item);
292 * The path, for example node/5. The function will find the corresponding
293 * node/% item and return that.
294 * @param $router_item
297 * The router item, an associate array corresponding to one row in the
298 * menu_router table. The value of key map holds the loaded objects. The
299 * value of key access is TRUE if the current user can access this page.
300 * The values for key title, page_arguments, access_arguments will be
301 * filled in based on the database values and the objects loaded.
303 function menu_get_item($path = NULL
, $router_item = NULL
) {
304 static
$router_items;
308 if (isset($router_item)) {
309 $router_items[$path] = $router_item;
311 if (!isset($router_items[$path])) {
312 $original_map = arg(NULL
, $path);
313 $parts = array_slice($original_map, 0, MENU_MAX_PARTS
);
314 list($ancestors, $placeholders) = menu_get_ancestors($parts);
316 if ($router_item = db_fetch_array(db_query_range('SELECT * FROM {menu_router} WHERE path IN ('.
implode (',', $placeholders) .
') ORDER BY fit DESC', $ancestors, 0, 1))) {
317 $map = _menu_translate($router_item, $original_map);
318 if ($map === FALSE
) {
319 $router_items[$path] = FALSE
;
322 if ($router_item['access']) {
323 $router_item['map'] = $map;
324 $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
327 $router_items[$path] = $router_item;
329 return $router_items[$path];
333 * Execute the page callback associated with the current path
335 function menu_execute_active_handler($path = NULL
) {
336 if (_menu_site_is_offline()) {
337 return MENU_SITE_OFFLINE
;
339 // Rebuild if we know it's needed, or if the menu masks are missing which
340 // occurs rarely, likely due to a race condition of multiple rebuilds.
341 if (variable_get('menu_rebuild_needed', FALSE
) || !variable_get('menu_masks', array())) {
344 if ($router_item = menu_get_item($path)) {
345 if ($router_item['access']) {
346 if ($router_item['file']) {
347 require_once($router_item['file']);
349 return call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
352 return MENU_ACCESS_DENIED
;
355 return MENU_NOT_FOUND
;
359 * Loads objects into the map as defined in the $item['load_functions'].
362 * A menu router or menu link item
364 * An array of path arguments (ex: array('node', '5'))
366 * Returns TRUE for success, FALSE if an object cannot be loaded.
367 * Names of object loading functions are placed in $item['load_functions'].
368 * Loaded objects are placed in $map[]; keys are the same as keys in the
369 * $item['load_functions'] array.
370 * $item['access'] is set to FALSE if an object cannot be loaded.
372 function _menu_load_objects(&$item, &$map) {
373 if ($load_functions = $item['load_functions']) {
374 // If someone calls this function twice, then unserialize will fail.
375 if ($load_functions_unserialized = unserialize($load_functions)) {
376 $load_functions = $load_functions_unserialized;
379 foreach ($load_functions as
$index => $function) {
381 $value = isset($path_map[$index]) ?
$path_map[$index] : '';
382 if (is_array($function)) {
383 // Set up arguments for the load function. These were pulled from
384 // 'load arguments' in the hook_menu() entry, but they need
385 // some processing. In this case the $function is the key to the
386 // load_function array, and the value is the list of arguments.
387 list($function, $args) = each($function);
388 $load_functions[$index] = $function;
390 // Some arguments are placeholders for dynamic items to process.
391 foreach ($args as
$i => $arg) {
392 if ($arg === '%index') {
393 // Pass on argument index to the load function, so multiple
394 // occurances of the same placeholder can be identified.
397 if ($arg === '%map') {
398 // Pass on menu map by reference. The accepting function must
399 // also declare this as a reference if it wants to modify
404 $args[$i] = isset($path_map[$arg]) ?
$path_map[$arg] : '';
407 array_unshift($args, $value);
408 $return = call_user_func_array($function, $args);
411 $return = $function($value);
413 // If callback returned an error or there is no callback, trigger 404.
414 if ($return === FALSE
) {
415 $item['access'] = FALSE
;
419 $map[$index] = $return;
422 $item['load_functions'] = $load_functions;
428 * Check access to a menu item using the access callback
431 * A menu router or menu link item
433 * An array of path arguments (ex: array('node', '5'))
435 * $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
437 function _menu_check_access(&$item, $map) {
438 // Determine access callback, which will decide whether or not the current
439 // user has access to this path.
440 $callback = empty($item['access_callback']) ?
0 : trim($item['access_callback']);
441 // Check for a TRUE or FALSE value.
442 if (is_numeric($callback)) {
443 $item['access'] = (bool
)$callback;
446 $arguments = menu_unserialize($item['access_arguments'], $map);
447 // As call_user_func_array is quite slow and user_access is a very common
448 // callback, it is worth making a special case for it.
449 if ($callback == 'user_access') {
450 $item['access'] = (count($arguments) == 1) ?
user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
453 $item['access'] = call_user_func_array($callback, $arguments);
459 * Localize the router item title using t() or another callback.
461 * Translate the title and description to allow storage of English title
462 * strings in the database, yet display of them in the language required
463 * by the current user.
466 * A menu router item or a menu link item.
468 * The path as an array with objects already replaced. E.g., for path
469 * node/123 $map would be array('node', $node) where $node is the node
470 * object for node 123.
471 * @param $link_translate
472 * TRUE if we are translating a menu link item; FALSE if we are
473 * translating a menu router item.
476 * $item['title'] is localized according to $item['title_callback'].
477 * If an item's callback is check_plain(), $item['options']['html'] becomes
479 * $item['description'] is translated using t().
480 * When doing link translation and the $item['options']['attributes']['title']
481 * (link title attribute) matches the description, it is translated as well.
483 function _menu_item_localize(&$item, $map, $link_translate = FALSE
) {
484 $callback = $item['title_callback'];
485 $item['localized_options'] = $item['options'];
486 // If we are translating the title of a menu link, and its title is the same
487 // as the corresponding router item, then we can use the title information
488 // from the router. If it's customized, then we need to use the link title
489 // itself; can't localize.
490 // If we are translating a router item (tabs, page, breadcrumb), then we
491 // can always use the information from the router item.
492 if (!$link_translate || ($item['title'] == $item['link_title'])) {
493 // t() is a special case. Since it is used very close to all the time,
494 // we handle it directly instead of using indirect, slower methods.
495 if ($callback == 't') {
496 if (empty($item['title_arguments'])) {
497 $item['title'] = t($item['title']);
500 $item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));
504 if (empty($item['title_arguments'])) {
505 $item['title'] = $callback($item['title']);
508 $item['title'] = call_user_func_array($callback, menu_unserialize($item['title_arguments'], $map));
510 // Avoid calling check_plain again on l() function.
511 if ($callback == 'check_plain') {
512 $item['localized_options']['html'] = TRUE
;
516 elseif ($link_translate) {
517 $item['title'] = $item['link_title'];
520 // Translate description, see the motivation above.
521 if (!empty($item['description'])) {
522 $original_description = $item['description'];
523 $item['description'] = t($item['description']);
524 if ($link_translate && isset($item['options']['attributes']['title']) && $item['options']['attributes']['title'] == $original_description) {
525 $item['localized_options']['attributes']['title'] = $item['description'];
531 * Handles dynamic path translation and menu access control.
533 * When a user arrives on a page such as node/5, this function determines
534 * what "5" corresponds to, by inspecting the page's menu path definition,
535 * node/%node. This will call node_load(5) to load the corresponding node
538 * It also works in reverse, to allow the display of tabs and menu items which
539 * contain these dynamic arguments, translating node/%node to node/5.
541 * Translation of menu item titles and descriptions are done here to
542 * allow for storage of English strings in the database, and translation
543 * to the language required to generate the current page
545 * @param $router_item
548 * An array of path arguments (ex: array('node', '5'))
550 * Execute $item['to_arg_functions'] or not. Use only if you want to render a
551 * path from the menu table, for example tabs.
553 * Returns the map with objects loaded as defined in the
554 * $item['load_functions']. $item['access'] becomes TRUE if the item is
555 * accessible, FALSE otherwise. $item['href'] is set according to the map.
556 * If an error occurs during calling the load_functions (like trying to load
557 * a non existing node) then this function return FALSE.
559 function _menu_translate(&$router_item, $map, $to_arg = FALSE
) {
561 // Fill in missing path elements, such as the current uid.
562 _menu_link_map_translate($map, $router_item['to_arg_functions']);
564 // The $path_map saves the pieces of the path as strings, while elements in
565 // $map may be replaced with loaded objects.
567 if (!_menu_load_objects($router_item, $map)) {
568 // An error occurred loading an object.
569 $router_item['access'] = FALSE
;
573 // Generate the link path for the page request or local tasks.
574 $link_map = explode('/', $router_item['path']);
575 for ($i = 0; $i < $router_item['number_parts']; $i++) {
576 if ($link_map[$i] == '%') {
577 $link_map[$i] = $path_map[$i];
580 $router_item['href'] = implode('/', $link_map);
581 $router_item['options'] = array();
582 _menu_check_access($router_item, $map);
584 // For performance, don't localize an item the user can't access.
585 if ($router_item['access']) {
586 _menu_item_localize($router_item, $map);
593 * This function translates the path elements in the map using any to_arg
594 * helper function. These functions take an argument and return an object.
595 * See http://drupal.org/node/109153 for more information.
598 * An array of path arguments (ex: array('node', '5'))
599 * @param $to_arg_functions
600 * An array of helper function (ex: array(2 => 'menu_tail_to_arg'))
602 function _menu_link_map_translate(&$map, $to_arg_functions) {
603 if ($to_arg_functions) {
604 $to_arg_functions = unserialize($to_arg_functions);
605 foreach ($to_arg_functions as
$index => $function) {
606 // Translate place-holders into real values.
607 $arg = $function(!empty($map[$index]) ?
$map[$index] : '', $map, $index);
608 if (!empty($map[$index]) || isset($arg)) {
618 function menu_tail_to_arg($arg, $map, $index) {
619 return implode('/', array_slice($map, $index));
623 * This function is similar to _menu_translate() but does link-specific
624 * preparation such as always calling to_arg functions.
629 * Returns the map of path arguments with objects loaded as defined in the
630 * $item['load_functions']:
631 * - $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
632 * - $item['href'] is generated from link_path, possibly by to_arg functions.
633 * - $item['title'] is generated from link_title, and may be localized.
634 * - $item['options'] is unserialized; it is also changed within the call
635 * here to $item['localized_options'] by _menu_item_localize().
637 function _menu_link_translate(&$item) {
638 $item['options'] = unserialize($item['options']);
639 if ($item['external']) {
642 $item['href'] = $item['link_path'];
643 $item['title'] = $item['link_title'];
644 $item['localized_options'] = $item['options'];
647 $map = explode('/', $item['link_path']);
648 _menu_link_map_translate($map, $item['to_arg_functions']);
649 $item['href'] = implode('/', $map);
651 // Note - skip callbacks without real values for their arguments.
652 if (strpos($item['href'], '%') !== FALSE
) {
653 $item['access'] = FALSE
;
656 // menu_tree_check_access() may set this ahead of time for links to nodes.
657 if (!isset($item['access'])) {
658 if (!_menu_load_objects($item, $map)) {
659 // An error occurred loading an object.
660 $item['access'] = FALSE
;
663 _menu_check_access($item, $map);
665 // For performance, don't localize a link the user can't access.
666 if ($item['access']) {
667 _menu_item_localize($item, $map, TRUE
);
671 // Allow other customizations - e.g. adding a page-specific query string to the
672 // options array. For performance reasons we only invoke this hook if the link
673 // has the 'alter' flag set in the options array.
674 if (!empty($item['options']['alter'])) {
675 drupal_alter('translated_menu_link', $item, $map);
682 * Get a loaded object from a router item.
684 * menu_get_object() will provide you the current node on paths like node/5,
685 * node/5/revisions/48 etc. menu_get_object('user') will give you the user
686 * account on user/5 etc. Note - this function should never be called within a
687 * _to_arg function (like user_current_to_arg()) since this may result in an
688 * infinite recursion.
691 * Type of the object. These appear in hook_menu definitons as %type. Core
692 * provides aggregator_feed, aggregator_category, contact, filter_format,
693 * forum_term, menu, menu_link, node, taxonomy_vocabulary, user. See the
694 * relevant {$type}_load function for more on each. Defaults to node.
696 * The expected position for $type object. For node/%node this is 1, for
697 * comment/reply/%node this is 2. Defaults to 1.
699 * See menu_get_item() for more on this. Defaults to the current path.
701 function menu_get_object($type = 'node', $position = 1, $path = NULL
) {
702 $router_item = menu_get_item($path);
703 if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type .
'_load') {
704 return $router_item['map'][$position];
709 * Render a menu tree based on the current path.
711 * The tree is expanded based on the current path and dynamic paths are also
712 * changed according to the defined to_arg functions (for example the 'My account'
713 * link is changed from user/% to a link with the current user's uid).
716 * The name of the menu.
718 * The rendered HTML of that menu on the current page.
720 function menu_tree($menu_name = 'navigation') {
721 static
$menu_output = array();
723 if (!isset($menu_output[$menu_name])) {
724 $tree = menu_tree_page_data($menu_name);
725 $menu_output[$menu_name] = menu_tree_output($tree);
727 return $menu_output[$menu_name];
731 * Returns a rendered menu tree.
734 * A data structure representing the tree as returned from menu_tree_data.
736 * The rendered HTML of that data structure.
738 function menu_tree_output($tree) {
742 // Pull out just the menu items we are going to render so that we
743 // get an accurate count for the first/last classes.
744 foreach ($tree as
$data) {
745 if (!$data['link']['hidden']) {
750 $num_items = count($items);
751 foreach ($items as
$i => $data) {
752 $extra_class = array();
754 $extra_class[] = 'first';
756 if ($i == $num_items - 1) {
757 $extra_class[] = 'last';
759 $extra_class = implode(' ', $extra_class);
760 $link = theme('menu_item_link', $data['link']);
761 if ($data['below']) {
762 $output .
= theme('menu_item', $link, $data['link']['has_children'], menu_tree_output($data['below']), $data['link']['in_active_trail'], $extra_class);
765 $output .
= theme('menu_item', $link, $data['link']['has_children'], '', $data['link']['in_active_trail'], $extra_class);
768 return $output ?
theme('menu_tree', $output) : '';
772 * Get the data structure representing a named menu tree.
774 * Since this can be the full tree including hidden items, the data returned
775 * may be used for generating an an admin interface or a select.
778 * The named menu links to return
780 * A fully loaded menu link, or NULL. If a link is supplied, only the
781 * path to root will be included in the returned tree- as if this link
782 * represented the current page in a visible menu.
784 * An tree of menu links in an array, in the order they should be rendered.
786 function menu_tree_all_data($menu_name = 'navigation', $item = NULL
) {
787 static
$tree = array();
789 // Use $mlid as a flag for whether the data being loaded is for the whole tree.
790 $mlid = isset($item['mlid']) ?
$item['mlid'] : 0;
791 // Generate a cache ID (cid) specific for this $menu_name and $item.
792 $cid = 'links:'.
$menu_name .
':all-cid:'.
$mlid;
794 if (!isset($tree[$cid])) {
795 // If the static variable doesn't have the data, check {cache_menu}.
796 $cache = cache_get($cid, 'cache_menu');
797 if ($cache && isset($cache->data
)) {
798 // If the cache entry exists, it will just be the cid for the actual data.
799 // This avoids duplication of large amounts of data.
800 $cache = cache_get($cache->data
, 'cache_menu');
801 if ($cache && isset($cache->data
)) {
802 $data = $cache->data
;
805 // If the tree data was not in the cache, $data will be NULL.
807 // Build and run the query, and build the tree.
809 // The tree is for a single item, so we need to match the values in its
810 // p columns and 0 (the top level) with the plid values of other links.
812 for ($i = 1; $i < MENU_MAX_DEPTH
; $i++) {
813 $args[] = $item["p$i"];
815 $args = array_unique($args);
816 $placeholders = implode(', ', array_fill(0, count($args), '%d'));
817 $where = ' AND ml.plid IN ('.
$placeholders .
')';
819 $parents[] = $item['mlid'];
822 // Get all links in this menu.
827 array_unshift($args, $menu_name);
828 // Select the links from the table, and recursively build the tree. We
829 // LEFT JOIN since there is no match in {menu_router} for an external
831 $data['tree'] = menu_tree_data(db_query("
832 SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.*
833 FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
834 WHERE ml.menu_name = '%s'".
$where .
"
835 ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC", $args), $parents);
836 $data['node_links'] = array();
837 menu_tree_collect_node_links($data['tree'], $data['node_links']);
838 // Cache the data, if it is not already in the cache.
839 $tree_cid = _menu_tree_cid($menu_name, $data);
840 if (!cache_get($tree_cid, 'cache_menu')) {
841 cache_set($tree_cid, $data, 'cache_menu');
843 // Cache the cid of the (shared) data using the menu and item-specific cid.
844 cache_set($cid, $tree_cid, 'cache_menu');
846 // Check access for the current user to each item in the tree.
847 menu_tree_check_access($data['tree'], $data['node_links']);
848 $tree[$cid] = $data['tree'];
855 * Get the data structure representing a named menu tree, based on the current page.
857 * The tree order is maintained by storing each parent in an individual
858 * field, see http://drupal.org/node/141866 for more.
861 * The named menu links to return
863 * An array of menu links, in the order they should be rendered. The array
864 * is a list of associative arrays -- these have two keys, link and below.
865 * link is a menu item, ready for theming as a link. Below represents the
866 * submenu below the link if there is one, and it is a subtree that has the
867 * same structure described for the top-level array.
869 function menu_tree_page_data($menu_name = 'navigation') {
870 static
$tree = array();
872 // Load the menu item corresponding to the current page.
873 if ($item = menu_get_item()) {
874 // Generate a cache ID (cid) specific for this page.
875 $cid = 'links:'.
$menu_name .
':page-cid:'.
$item['href'] .
':'.
(int)$item['access'];
877 if (!isset($tree[$cid])) {
878 // If the static variable doesn't have the data, check {cache_menu}.
879 $cache = cache_get($cid, 'cache_menu');
880 if ($cache && isset($cache->data
)) {
881 // If the cache entry exists, it will just be the cid for the actual data.
882 // This avoids duplication of large amounts of data.
883 $cache = cache_get($cache->data
, 'cache_menu');
884 if ($cache && isset($cache->data
)) {
885 $data = $cache->data
;
888 // If the tree data was not in the cache, $data will be NULL.
890 // Build and run the query, and build the tree.
891 if ($item['access']) {
892 // Check whether a menu link exists that corresponds to the current path.
893 $args = array($menu_name, $item['href']);
894 $placeholders = "'%s'";
895 if (drupal_is_front_page()) {
897 $placeholders .
= ", '%s'";
899 $parents = db_fetch_array(db_query("SELECT p1, p2, p3, p4, p5, p6, p7, p8 FROM {menu_links} WHERE menu_name = '%s' AND link_path IN (".
$placeholders .
")", $args));
901 if (empty($parents)) {
902 // If no link exists, we may be on a local task that's not in the links.
903 // TODO: Handle the case like a local task on a specific node in the menu.
904 $parents = db_fetch_array(db_query("SELECT p1, p2, p3, p4, p5, p6, p7, p8 FROM {menu_links} WHERE menu_name = '%s' AND link_path = '%s'", $menu_name, $item['tab_root']));
906 // We always want all the top-level links with plid == 0.
909 // Use array_values() so that the indices are numeric for array_merge().
910 $args = $parents = array_unique(array_values($parents));
911 $placeholders = implode(', ', array_fill(0, count($args), '%d'));
912 $expanded = variable_get('menu_expanded', array());
913 // Check whether the current menu has any links set to be expanded.
914 if (in_array($menu_name, $expanded)) {
915 // Collect all the links set to be expanded, and then add all of
916 // their children to the list as well.
918 $result = db_query("SELECT mlid FROM {menu_links} WHERE menu_name = '%s' AND expanded = 1 AND has_children = 1 AND plid IN (".
$placeholders .
') AND mlid NOT IN ('.
$placeholders .
')', array_merge(array($menu_name), $args, $args));
920 while ($item = db_fetch_array($result)) {
921 $args[] = $item['mlid'];
924 $placeholders = implode(', ', array_fill(0, count($args), '%d'));
927 array_unshift($args, $menu_name);
930 // Show only the top-level menu items when access is denied.
931 $args = array($menu_name, '0');
932 $placeholders = '%d';
935 // Select the links from the table, and recursively build the tree. We
936 // LEFT JOIN since there is no match in {menu_router} for an external
938 $data['tree'] = menu_tree_data(db_query("
939 SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.*
940 FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
941 WHERE ml.menu_name = '%s' AND ml.plid IN (".
$placeholders .
")
942 ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC", $args), $parents);
943 $data['node_links'] = array();
944 menu_tree_collect_node_links($data['tree'], $data['node_links']);
945 // Cache the data, if it is not already in the cache.
946 $tree_cid = _menu_tree_cid($menu_name, $data);
947 if (!cache_get($tree_cid, 'cache_menu')) {
948 cache_set($tree_cid, $data, 'cache_menu');
950 // Cache the cid of the (shared) data using the page-specific cid.
951 cache_set($cid, $tree_cid, 'cache_menu');
953 // Check access for the current user to each item in the tree.
954 menu_tree_check_access($data['tree'], $data['node_links']);
955 $tree[$cid] = $data['tree'];
964 * Helper function - compute the real cache ID for menu tree data.
966 function _menu_tree_cid($menu_name, $data) {
967 return 'links:'.
$menu_name .
':tree-data:'.
md5(serialize($data));
971 * Recursive helper function - collect node links.
974 * The menu tree you wish to collect node links from.
976 * An array in which to store the collected node links.
978 function menu_tree_collect_node_links(&$tree, &$node_links) {
979 foreach ($tree as
$key => $v) {
980 if ($tree[$key]['link']['router_path'] == 'node/%') {
981 $nid = substr($tree[$key]['link']['link_path'], 5);
982 if (is_numeric($nid)) {
983 $node_links[$nid][$tree[$key]['link']['mlid']] = &$tree[$key]['link'];
984 $tree[$key]['link']['access'] = FALSE
;
987 if ($tree[$key]['below']) {
988 menu_tree_collect_node_links($tree[$key]['below'], $node_links);
994 * Check access and perform other dynamic operations for each link in the tree.
997 * The menu tree you wish to operate on.
999 * A collection of node link references generated from $tree by
1000 * menu_tree_collect_node_links().
1002 function menu_tree_check_access(&$tree, $node_links = array()) {
1005 // Use db_rewrite_sql to evaluate view access without loading each full node.
1006 $nids = array_keys($node_links);
1007 $placeholders = '%d'.
str_repeat(', %d', count($nids) - 1);
1008 $result = db_query(db_rewrite_sql("SELECT n.nid FROM {node} n WHERE n.status = 1 AND n.nid IN (".
$placeholders .
")"), $nids);
1009 while ($node = db_fetch_array($result)) {
1010 $nid = $node['nid'];
1011 foreach ($node_links[$nid] as
$mlid => $link) {
1012 $node_links[$nid][$mlid]['access'] = TRUE
;
1016 _menu_tree_check_access($tree);
1021 * Recursive helper function for menu_tree_check_access()
1023 function _menu_tree_check_access(&$tree) {
1024 $new_tree = array();
1025 foreach ($tree as
$key => $v) {
1026 $item = &$tree[$key]['link'];
1027 _menu_link_translate($item);
1028 if ($item['access']) {
1029 if ($tree[$key]['below']) {
1030 _menu_tree_check_access($tree[$key]['below']);
1032 // The weights are made a uniform 5 digits by adding 50000 as an offset.
1033 // After _menu_link_translate(), $item['title'] has the localized link title.
1034 // Adding the mlid to the end of the index insures that it is unique.
1035 $new_tree[(50000 + $item['weight']) .
' '.
$item['title'] .
' '.
$item['mlid']] = $tree[$key];
1038 // Sort siblings in the tree based on the weights and localized titles.
1044 * Build the data representing a menu tree.
1047 * The database result.
1049 * An array of the plid values that represent the path from the current page
1050 * to the root of the menu tree.
1052 * The depth of the current menu tree.
1054 * See menu_tree_page_data for a description of the data structure.
1056 function menu_tree_data($result = NULL
, $parents = array(), $depth = 1) {
1057 list(, $tree) = _menu_tree_data($result, $parents, $depth);
1062 * Recursive helper function to build the data representing a menu tree.
1064 * The function is a bit complex because the rendering of an item depends on
1065 * the next menu item. So we are always rendering the element previously
1066 * processed not the current one.
1068 function _menu_tree_data($result, $parents, $depth, $previous_element = '') {
1071 while ($item = db_fetch_array($result)) {
1072 // We need to determine if we're on the path to root so we can later build
1073 // the correct active trail and breadcrumb.
1074 $item['in_active_trail'] = in_array($item['mlid'], $parents);
1075 // The current item is the first in a new submenu.
1076 if ($item['depth'] > $depth) {
1077 // _menu_tree returns an item and the menu tree structure.
1078 list($item, $below) = _menu_tree_data($result, $parents, $item['depth'], $item);
1079 if ($previous_element) {
1080 $tree[$previous_element['mlid']] = array(
1081 'link' => $previous_element,
1088 // We need to fall back one level.
1089 if (!isset($item) || $item['depth'] < $depth) {
1090 return array($item, $tree);
1092 // This will be the link to be output in the next iteration.
1093 $previous_element = $item;
1095 // We are at the same depth, so we use the previous element.
1096 elseif ($item['depth'] == $depth) {
1097 if ($previous_element) {
1098 // Only the first time.
1099 $tree[$previous_element['mlid']] = array(
1100 'link' => $previous_element,
1104 // This will be the link to be output in the next iteration.
1105 $previous_element = $item;
1107 // The submenu ended with the previous item, so pass back the current item.
1113 if ($previous_element) {
1114 // We have one more link dangling.
1115 $tree[$previous_element['mlid']] = array(
1116 'link' => $previous_element,
1120 return array($remnant, $tree);
1124 * Generate the HTML output for a single menu link.
1126 * @ingroup themeable
1128 function theme_menu_item_link($link) {
1129 if (empty($link['localized_options'])) {
1130 $link['localized_options'] = array();
1133 return l($link['title'], $link['href'], $link['localized_options']);
1137 * Generate the HTML output for a menu tree
1139 * @ingroup themeable
1141 function theme_menu_tree($tree) {
1142 return '<ul class="menu">'.
$tree .
'</ul>';
1146 * Generate the HTML output for a menu item and submenu.
1148 * @ingroup themeable
1150 function theme_menu_item($link, $has_children, $menu = '', $in_active_trail = FALSE
, $extra_class = NULL
) {
1151 $class = ($menu ?
'expanded' : ($has_children ?
'collapsed' : 'leaf'));
1152 if (!empty($extra_class)) {
1153 $class .
= ' '.
$extra_class;
1155 if ($in_active_trail) {
1156 $class .
= ' active-trail';
1158 return '<li class="'.
$class .
'">'.
$link .
$menu .
"</li>\n";
1162 * Generate the HTML output for a single local task link.
1164 * @ingroup themeable
1166 function theme_menu_local_task($link, $active = FALSE
) {
1167 return '<li '.
($active ?
'class="active" ' : '') .
'>'.
$link .
"</li>\n";
1171 * Generates elements for the $arg array in the help hook.
1173 function drupal_help_arg($arg = array()) {
1174 // Note - the number of empty elements should be > MENU_MAX_PARTS.
1175 return $arg + array('', '', '', '', '', '', '', '', '', '', '', '');
1179 * Returns the help associated with the active menu item.
1181 function menu_get_active_help() {
1183 $router_path = menu_tab_root_path();
1184 // We will always have a path unless we are on a 403 or 404.
1185 if (!$router_path) {
1189 $arg = drupal_help_arg(arg(NULL
));
1190 $empty_arg = drupal_help_arg();
1192 foreach (module_list() as
$name) {
1193 if (module_hook($name, 'help')) {
1194 // Lookup help for this path.
1195 if ($help = module_invoke($name, 'help', $router_path, $arg)) {
1196 $output .
= $help .
"\n";
1198 // Add "more help" link on admin pages if the module provides a
1199 // standalone help page.
1200 if ($arg[0] == "admin" && module_exists('help') && module_invoke($name, 'help', 'admin/help#'.
$arg[2], $empty_arg) && $help) {
1201 $output .
= theme("more_help_link", url('admin/help/'.
$arg[2]));
1209 * Build a list of named menus.
1211 function menu_get_names($reset = FALSE
) {
1214 if ($reset || empty($names)) {
1216 $result = db_query("SELECT DISTINCT(menu_name) FROM {menu_links} ORDER BY menu_name");
1217 while ($name = db_fetch_array($result)) {
1218 $names[] = $name['menu_name'];
1225 * Return an array containing the names of system-defined (default) menus.
1227 function menu_list_system_menus() {
1228 return array('navigation', 'primary-links', 'secondary-links');
1232 * Return an array of links to be rendered as the Primary links.
1234 function menu_primary_links() {
1235 return menu_navigation_links(variable_get('menu_primary_links_source', 'primary-links'));
1239 * Return an array of links to be rendered as the Secondary links.
1241 function menu_secondary_links() {
1243 // If the secondary menu source is set as the primary menu, we display the
1244 // second level of the primary menu.
1245 if (variable_get('menu_secondary_links_source', 'secondary-links') == variable_get('menu_primary_links_source', 'primary-links')) {
1246 return menu_navigation_links(variable_get('menu_primary_links_source', 'primary-links'), 1);
1249 return menu_navigation_links(variable_get('menu_secondary_links_source', 'secondary-links'), 0);
1254 * Return an array of links for a navigation menu.
1257 * The name of the menu.
1259 * Optional, the depth of the menu to be returned.
1261 * An array of links of the specified menu and level.
1263 function menu_navigation_links($menu_name, $level = 0) {
1264 // Don't even bother querying the menu table if no menu is specified.
1265 if (empty($menu_name)) {
1269 // Get the menu hierarchy for the current page.
1270 $tree = menu_tree_page_data($menu_name);
1272 // Go down the active trail until the right level is reached.
1273 while ($level-- > 0 && $tree) {
1274 // Loop through the current level's items until we find one that is in trail.
1275 while ($item = array_shift($tree)) {
1276 if ($item['link']['in_active_trail']) {
1277 // If the item is in the active trail, we continue in the subtree.
1278 $tree = empty($item['below']) ?
array() : $item['below'];
1284 // Create a single level of links.
1286 foreach ($tree as
$item) {
1287 if (!$item['link']['hidden']) {
1289 $l = $item['link']['localized_options'];
1290 $l['href'] = $item['link']['href'];
1291 $l['title'] = $item['link']['title'];
1292 if ($item['link']['in_active_trail']) {
1293 $class = ' active-trail';
1295 // Keyed with the unique mlid to generate classes in theme_links().
1296 $links['menu-'.
$item['link']['mlid'] .
$class] = $l;
1303 * Collects the local tasks (tabs) for a given level.
1306 * The level of tasks you ask for. Primary tasks are 0, secondary are 1.
1307 * @param $return_root
1308 * Whether to return the root path for the current page.
1310 * Themed output corresponding to the tabs of the requested level, or
1311 * router path if $return_root == TRUE. This router path corresponds to
1312 * a parent tab, if the current page is a default local task.
1314 function menu_local_tasks($level = 0, $return_root = FALSE
) {
1318 if (!isset($tabs)) {
1321 $router_item = menu_get_item();
1322 if (!$router_item || !$router_item['access']) {
1325 // Get all tabs and the root page.
1326 $result = db_query("SELECT * FROM {menu_router} WHERE tab_root = '%s' ORDER BY weight, title", $router_item['tab_root']);
1328 $children = array();
1330 $root_path = $router_item['path'];
1332 while ($item = db_fetch_array($result)) {
1333 _menu_translate($item, $map, TRUE
);
1334 if ($item['tab_parent']) {
1335 // All tabs, but not the root page.
1336 $children[$item['tab_parent']][$item['path']] = $item;
1338 // Store the translated item for later use.
1339 $tasks[$item['path']] = $item;
1342 // Find all tabs below the current path.
1343 $path = $router_item['path'];
1344 // Tab parenting may skip levels, so the number of parts in the path may not
1345 // equal the depth. Thus we use the $depth counter (offset by 1000 for ksort).
1347 while (isset($children[$path])) {
1351 foreach ($children[$path] as
$item) {
1352 if ($item['access']) {
1354 // The default task is always active.
1355 if ($item['type'] == MENU_DEFAULT_LOCAL_TASK
) {
1356 // Find the first parent which is not a default local task.
1357 for ($p = $item['tab_parent']; $tasks[$p]['type'] == MENU_DEFAULT_LOCAL_TASK
; $p = $tasks[$p]['tab_parent']);
1358 $link = theme('menu_item_link', array('href' => $tasks[$p]['href']) + $item);
1359 $tabs_current .
= theme('menu_local_task', $link, TRUE
);
1360 $next_path = $item['path'];
1363 $link = theme('menu_item_link', $item);
1364 $tabs_current .
= theme('menu_local_task', $link);
1369 $tabs[$depth]['count'] = $count;
1370 $tabs[$depth]['output'] = $tabs_current;
1374 // Find all tabs at the same level or above the current one.
1375 $parent = $router_item['tab_parent'];
1376 $path = $router_item['path'];
1377 $current = $router_item;
1379 while (isset($children[$parent])) {
1384 foreach ($children[$parent] as
$item) {
1385 if ($item['access']) {
1387 if ($item['type'] == MENU_DEFAULT_LOCAL_TASK
) {
1388 // Find the first parent which is not a default local task.
1389 for ($p = $item['tab_parent']; $tasks[$p]['type'] == MENU_DEFAULT_LOCAL_TASK
; $p = $tasks[$p]['tab_parent']);
1390 $link = theme('menu_item_link', array('href' => $tasks[$p]['href']) + $item);
1391 if ($item['path'] == $router_item['path']) {
1392 $root_path = $tasks[$p]['path'];
1396 $link = theme('menu_item_link', $item);
1398 // We check for the active tab.
1399 if ($item['path'] == $path) {
1400 $tabs_current .
= theme('menu_local_task', $link, TRUE
);
1401 $next_path = $item['tab_parent'];
1402 if (isset($tasks[$next_path])) {
1403 $next_parent = $tasks[$next_path]['tab_parent'];
1407 $tabs_current .
= theme('menu_local_task', $link);
1412 $parent = $next_parent;
1413 $tabs[$depth]['count'] = $count;
1414 $tabs[$depth]['output'] = $tabs_current;
1419 // Remove the depth, we are interested only in their relative placement.
1420 $tabs = array_values($tabs);
1427 // We do not display single tabs.
1428 return (isset($tabs[$level]) && $tabs[$level]['count'] > 1) ?
$tabs[$level]['output'] : '';
1433 * Returns the rendered local tasks at the top level.
1435 function menu_primary_local_tasks() {
1436 return menu_local_tasks(0);
1440 * Returns the rendered local tasks at the second level.
1442 function menu_secondary_local_tasks() {
1443 return menu_local_tasks(1);
1447 * Returns the router path, or the path of the parent tab of a default local task.
1449 function menu_tab_root_path() {
1450 return menu_local_tasks(0, TRUE
);
1454 * Returns the rendered local tasks. The default implementation renders them as tabs.
1456 * @ingroup themeable
1458 function theme_menu_local_tasks() {
1461 if ($primary = menu_primary_local_tasks()) {
1462 $output .
= "<ul class=\"tabs primary\">\n".
$primary .
"</ul>\n";
1464 if ($secondary = menu_secondary_local_tasks()) {
1465 $output .
= "<ul class=\"tabs secondary\">\n".
$secondary .
"</ul>\n";
1472 * Set (or get) the active menu for the current page - determines the active trail.
1474 function menu_set_active_menu_name($menu_name = NULL
) {
1477 if (isset($menu_name)) {
1478 $active = $menu_name;
1480 elseif (!isset($active)) {
1481 $active = 'navigation';
1487 * Get the active menu for the current page - determines the active trail.
1489 function menu_get_active_menu_name() {
1490 return menu_set_active_menu_name();
1494 * Set the active path, which determines which page is loaded.
1497 * A Drupal path - not a path alias.
1499 * Note that this may not have the desired effect unless invoked very early
1500 * in the page load, such as during hook_boot, or unless you call
1501 * menu_execute_active_handler() to generate your page output.
1503 function menu_set_active_item($path) {
1508 * Sets or gets the active trail (path to root menu root) of the current page.
1511 * Menu trail to set, or NULL to use previously-set or calculated trail. If
1512 * supplying a trail, use the same format as the return value (see below).
1515 * Path to menu root of the current page, as an array of menu link items,
1516 * starting with the site's home page. Each link item is an associative array
1517 * with the following components:
1518 * - title: Title of the item.
1519 * - href: Drupal path of the item.
1520 * - localized_options: Options for passing into the l() function.
1521 * - type: A menu type constant, such as MENU_DEFAULT_LOCAL_TASK, or 0 to
1522 * indicate it's not really in the menu (used for the home page item).
1523 * If $new_trail is supplied, the value is saved in a static variable and
1524 * returned. If $new_trail is not supplied, and there is a saved value from
1525 * a previous call, the saved value is returned. If $new_trail is not supplied
1526 * and there is no saved value, the path to the current page is calculated,
1527 * saved as the static value, and returned.
1529 function menu_set_active_trail($new_trail = NULL
) {
1532 if (isset($new_trail)) {
1533 $trail = $new_trail;
1535 elseif (!isset($trail)) {
1537 $trail[] = array('title' => t('Home'), 'href' => '<front>', 'localized_options' => array(), 'type' => 0);
1538 $item = menu_get_item();
1540 // Check whether the current item is a local task (displayed as a tab).
1541 if ($item['tab_parent']) {
1542 // The title of a local task is used for the tab, never the page title.
1543 // Thus, replace it with the item corresponding to the root path to get
1544 // the relevant href and title. For example, the menu item corresponding
1545 // to 'admin' is used when on the 'By module' tab at 'admin/by-module'.
1546 $parts = explode('/', $item['tab_root']);
1548 // Replace wildcards in the root path using the current path.
1549 foreach ($parts as
$index => $part) {
1551 $parts[$index] = $args[$index];
1554 // Retrieve the menu item using the root path after wildcard replacement.
1555 $root_item = menu_get_item(implode('/', $parts));
1556 if ($root_item && $root_item['access']) {
1561 $tree = menu_tree_page_data(menu_get_active_menu_name());
1562 list($key, $curr) = each($tree);
1565 // Terminate the loop when we find the current path in the active trail.
1566 if ($curr['link']['href'] == $item['href']) {
1567 $trail[] = $curr['link'];
1571 // Add the link if it's in the active trail, then move to the link below.
1572 if ($curr['link']['in_active_trail']) {
1573 $trail[] = $curr['link'];
1574 $tree = $curr['below'] ?
$curr['below'] : array();
1576 list($key, $curr) = each($tree);
1579 // Make sure the current page is in the trail (needed for the page title),
1580 // but exclude tabs and the front page.
1581 $last = count($trail) - 1;
1582 if ($trail[$last]['href'] != $item['href'] && !(bool
)($item['type'] & MENU_IS_LOCAL_TASK
) && !drupal_is_front_page()) {
1590 * Gets the active trail (path to root menu root) of the current page.
1592 * See menu_set_active_trail() for details of return value.
1594 function menu_get_active_trail() {
1595 return menu_set_active_trail();
1599 * Get the breadcrumb for the current page, as determined by the active trail.
1601 function menu_get_active_breadcrumb() {
1602 $breadcrumb = array();
1604 // No breadcrumb for the front page.
1605 if (drupal_is_front_page()) {
1609 $item = menu_get_item();
1610 if ($item && $item['access']) {
1611 $active_trail = menu_get_active_trail();
1613 foreach ($active_trail as
$parent) {
1614 $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
1616 $end = end($active_trail);
1618 // Don't show a link to the current page in the breadcrumb trail.
1619 if ($item['href'] == $end['href'] || ($item['type'] == MENU_DEFAULT_LOCAL_TASK
&& $end['href'] != '<front>')) {
1620 array_pop($breadcrumb);
1627 * Get the title of the current page, as determined by the active trail.
1629 function menu_get_active_title() {
1630 $active_trail = menu_get_active_trail();
1632 foreach (array_reverse($active_trail) as
$item) {
1633 if (!(bool
)($item['type'] & MENU_IS_LOCAL_TASK
)) {
1634 return $item['title'];
1640 * Get a menu link by its mlid, access checked and link translated for rendering.
1642 * This function should never be called from within node_load() or any other
1643 * function used as a menu object load function since an infinite recursion may
1647 * The mlid of the menu item.
1649 * A menu link, with $item['access'] filled and link translated for
1652 function menu_link_load($mlid) {
1653 if (is_numeric($mlid) && $item = db_fetch_array(db_query("SELECT m.*, ml.* FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path WHERE ml.mlid = %d", $mlid))) {
1654 _menu_link_translate($item);
1661 * Clears the cached cached data for a single named menu.
1663 function menu_cache_clear($menu_name = 'navigation') {
1664 static
$cache_cleared = array();
1666 if (empty($cache_cleared[$menu_name])) {
1667 cache_clear_all('links:'.
$menu_name .
':', 'cache_menu', TRUE
);
1668 $cache_cleared[$menu_name] = 1;
1670 elseif ($cache_cleared[$menu_name] == 1) {
1671 register_shutdown_function('cache_clear_all', 'links:'.
$menu_name .
':', 'cache_menu', TRUE
);
1672 $cache_cleared[$menu_name] = 2;
1677 * Clears all cached menu data. This should be called any time broad changes
1678 * might have been made to the router items or menu links.
1680 function menu_cache_clear_all() {
1681 cache_clear_all('*', 'cache_menu', TRUE
);
1685 * (Re)populate the database tables used by various menu functions.
1687 * This function will clear and populate the {menu_router} table, add entries
1688 * to {menu_links} for new router items, then remove stale items from
1689 * {menu_links}. If called from update.php or install.php, it will also
1690 * schedule a call to itself on the first real page load from
1691 * menu_execute_active_handler(), because the maintenance page environment
1692 * is different and leaves stale data in the menu tables.
1694 function menu_rebuild() {
1695 if (!lock_acquire('menu_rebuild')) {
1696 // Wait for another request that is already doing this work.
1697 // We choose to block here since otherwise the router item may not
1698 // be avaiable in menu_execute_active_handler() resulting in a 404.
1699 lock_wait('menu_rebuild');
1703 $menu = menu_router_build(TRUE
);
1704 _menu_navigation_links_rebuild($menu);
1705 // Clear the menu, page and block caches.
1706 menu_cache_clear_all();
1707 _menu_clear_page_cache();
1709 if (defined('MAINTENANCE_MODE')) {
1710 variable_set('menu_rebuild_needed', TRUE
);
1713 variable_del('menu_rebuild_needed');
1715 lock_release('menu_rebuild');
1720 * Collect, alter and store the menu definitions.
1722 function menu_router_build($reset = FALSE
) {
1725 if (!isset($menu) || $reset) {
1726 // We need to manually call each module so that we can know which module
1727 // a given item came from.
1728 $callbacks = array();
1729 foreach (module_implements('menu') as
$module) {
1730 $router_items = call_user_func($module .
'_menu');
1731 if (isset($router_items) && is_array($router_items)) {
1732 foreach (array_keys($router_items) as
$path) {
1733 $router_items[$path]['module'] = $module;
1735 $callbacks = array_merge($callbacks, $router_items);
1738 // Alter the menu as defined in modules, keys are like user/%user.
1739 drupal_alter('menu', $callbacks);
1740 $menu = _menu_router_build($callbacks);
1741 _menu_router_cache($menu);
1747 * Helper function to store the menu router if we have it in memory.
1749 function _menu_router_cache($new_menu = NULL
) {
1750 static
$menu = NULL
;
1752 if (isset($new_menu)) {
1759 * Builds a link from a router item.
1761 function _menu_link_build($item) {
1762 if ($item['type'] == MENU_CALLBACK
) {
1763 $item['hidden'] = -1;
1765 elseif ($item['type'] == MENU_SUGGESTED_ITEM
) {
1766 $item['hidden'] = 1;
1768 // Note, we set this as 'system', so that we can be sure to distinguish all
1769 // the menu links generated automatically from entries in {menu_router}.
1770 $item['module'] = 'system';
1772 'menu_name' => 'navigation',
1773 'link_title' => $item['title'],
1774 'link_path' => $item['path'],
1776 'options' => empty($item['description']) ?
array() : array('attributes' => array('title' => $item['description'])),
1782 * Helper function to build menu links for the items in the menu router.
1784 function _menu_navigation_links_rebuild($menu) {
1785 // Add normal and suggested items as links.
1786 $menu_links = array();
1787 foreach ($menu as
$path => $item) {
1788 if ($item['_visible']) {
1789 $item = _menu_link_build($item);
1790 $menu_links[$path] = $item;
1791 $sort[$path] = $item['_number_parts'];
1795 // Make sure no child comes before its parent.
1796 array_multisort($sort, SORT_NUMERIC
, $menu_links);
1798 foreach ($menu_links as
$item) {
1799 $existing_item = db_fetch_array(db_query("SELECT mlid, menu_name, plid, customized, has_children, updated FROM {menu_links} WHERE link_path = '%s' AND module = '%s'", $item['link_path'], 'system'));
1800 if ($existing_item) {
1801 $item['mlid'] = $existing_item['mlid'];
1802 // A change in hook_menu may move the link to a different menu
1803 if (empty($item['menu_name']) || ($item['menu_name'] == $existing_item['menu_name'])) {
1804 $item['menu_name'] = $existing_item['menu_name'];
1805 $item['plid'] = $existing_item['plid'];
1807 $item['has_children'] = $existing_item['has_children'];
1808 $item['updated'] = $existing_item['updated'];
1810 if (!$existing_item || !$existing_item['customized']) {
1811 menu_link_save($item);
1815 $placeholders = db_placeholders($menu, 'varchar');
1816 $paths = array_keys($menu);
1817 // Updated and customized items whose router paths are gone need new ones.
1818 $result = db_query("SELECT ml.link_path, ml.mlid, ml.router_path, ml.updated FROM {menu_links} ml WHERE ml.updated = 1 OR (router_path NOT IN ($placeholders) AND external = 0 AND customized = 1)", $paths);
1819 while ($item = db_fetch_array($result)) {
1820 $router_path = _menu_find_router_path($item['link_path']);
1821 if (!empty($router_path) && ($router_path != $item['router_path'] || $item['updated'])) {
1822 // If the router path and the link path matches, it's surely a working
1823 // item, so we clear the updated flag.
1824 $updated = $item['updated'] && $router_path != $item['link_path'];
1825 db_query("UPDATE {menu_links} SET router_path = '%s', updated = %d WHERE mlid = %d", $router_path, $updated, $item['mlid']);
1828 // Find any item whose router path does not exist any more.
1829 $result = db_query("SELECT * FROM {menu_links} WHERE router_path NOT IN ($placeholders) AND external = 0 AND updated = 0 AND customized = 0 ORDER BY depth DESC", $paths);
1830 // Remove all such items. Starting from those with the greatest depth will
1831 // minimize the amount of re-parenting done by menu_link_delete().
1832 while ($item = db_fetch_array($result)) {
1833 _menu_delete_item($item, TRUE
);
1838 * Delete one or several menu links.
1841 * A valid menu link mlid or NULL. If NULL, $path is used.
1843 * The path to the menu items to be deleted. $mlid must be NULL.
1845 function menu_link_delete($mlid, $path = NULL
) {
1847 _menu_delete_item(db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d", $mlid)));
1850 $result = db_query("SELECT * FROM {menu_links} WHERE link_path = '%s'", $path);
1851 while ($link = db_fetch_array($result)) {
1852 _menu_delete_item($link);
1858 * Helper function for menu_link_delete; deletes a single menu link.
1861 * Item to be deleted.
1863 * Forces deletion. Internal use only, setting to TRUE is discouraged.
1865 function _menu_delete_item($item, $force = FALSE
) {
1866 if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) {
1867 // Children get re-attached to the item's parent.
1868 if ($item['has_children']) {
1869 $result = db_query("SELECT mlid FROM {menu_links} WHERE plid = %d", $item['mlid']);
1870 while ($m = db_fetch_array($result)) {
1871 $child = menu_link_load($m['mlid']);
1872 $child['plid'] = $item['plid'];
1873 menu_link_save($child);
1876 db_query('DELETE FROM {menu_links} WHERE mlid = %d', $item['mlid']);
1878 // Update the has_children status of the parent.
1879 _menu_update_parental_status($item);
1880 menu_cache_clear($item['menu_name']);
1881 _menu_clear_page_cache();
1889 * An array representing a menu link item. The only mandatory keys are
1890 * link_path and link_title. Possible keys are:
1891 * - menu_name: Default is navigation.
1892 * - weight: Default is 0.
1893 * - expanded: Whether the item is expanded.
1894 * - options: An array of options, see l() for more.
1895 * - mlid: Set to an existing value, or 0 or NULL to insert a new link.
1896 * - plid: The mlid of the parent.
1897 * - router_path: The path of the relevant router item.
1900 * The mlid of the saved menu link, or FALSE if the menu link could not be
1903 function menu_link_save(&$item) {
1905 // Get the router if it's already in memory. $menu will be NULL, unless this
1906 // is during a menu rebuild
1907 $menu = _menu_router_cache();
1908 drupal_alter('menu_link', $item, $menu);
1910 // This is the easiest way to handle the unique internal path '<front>',
1911 // since a path marked as external does not need to match a router path.
1912 $item['_external'] = menu_path_is_external($item['link_path']) || $item['link_path'] == '<front>';
1915 'menu_name' => 'navigation',
1919 'has_children' => 0,
1921 'options' => array(),
1926 $existing_item = FALSE
;
1927 if (isset($item['mlid'])) {
1928 $existing_item = db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d", $item['mlid']));
1931 if (isset($item['plid'])) {
1932 $parent = db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d", $item['plid']));
1935 // Find the parent - it must be unique.
1936 $parent_path = $item['link_path'];
1937 $where = "WHERE link_path = '%s'";
1938 // Only links derived from router items should have module == 'system', and
1939 // we want to find the parent even if it's in a different menu.
1940 if ($item['module'] == 'system') {
1941 $where .
= " AND module = '%s'";
1945 // If not derived from a router item, we respect the specified menu name.
1946 $where .
= " AND menu_name = '%s'";
1947 $arg2 = $item['menu_name'];
1951 $parent_path = substr($parent_path, 0, strrpos($parent_path, '/'));
1952 $result = db_query("SELECT COUNT(*) FROM {menu_links} ".
$where, $parent_path, $arg2);
1953 // Only valid if we get a unique result.
1954 if (db_result($result) == 1) {
1955 $parent = db_fetch_array(db_query("SELECT * FROM {menu_links} ".
$where, $parent_path, $arg2));
1957 } while ($parent === FALSE
&& $parent_path);
1959 if ($parent !== FALSE
) {
1960 $item['menu_name'] = $parent['menu_name'];
1962 $menu_name = $item['menu_name'];
1963 // Menu callbacks need to be in the links table for breadcrumbs, but can't
1964 // be parents if they are generated directly from a router item.
1965 if (empty($parent['mlid']) || $parent['hidden'] < 0) {
1969 $item['plid'] = $parent['mlid'];
1972 if (!$existing_item) {
1973 db_query("INSERT INTO {menu_links} (
1974 menu_name, plid, link_path,
1975 hidden, external, has_children,
1977 module, link_title, options,
1978 customized, updated) VALUES (
1982 '%s', '%s', '%s', %d, %d)",
1983 $item['menu_name'], $item['plid'], $item['link_path'],
1984 $item['hidden'], $item['_external'], $item['has_children'],
1985 $item['expanded'], $item['weight'],
1986 $item['module'], $item['link_title'], serialize($item['options']),
1987 $item['customized'], $item['updated']);
1988 $item['mlid'] = db_last_insert_id('menu_links', 'mlid');
1991 if (!$item['plid']) {
1992 $item['p1'] = $item['mlid'];
1993 for ($i = 2; $i <= MENU_MAX_DEPTH
; $i++) {
1999 // Cannot add beyond the maximum depth.
2000 if ($item['has_children'] && $existing_item) {
2001 $limit = MENU_MAX_DEPTH
- menu_link_children_relative_depth($existing_item) - 1;
2004 $limit = MENU_MAX_DEPTH
- 1;
2006 if ($parent['depth'] > $limit) {
2009 $item['depth'] = $parent['depth'] + 1;
2010 _menu_link_parents_set($item, $parent);
2012 // Need to check both plid and menu_name, since plid can be 0 in any menu.
2013 if ($existing_item && ($item['plid'] != $existing_item['plid'] || $menu_name != $existing_item['menu_name'])) {
2014 _menu_link_move_children($item, $existing_item);
2016 // Find the callback. During the menu update we store empty paths to be
2017 // fixed later, so we skip this.
2018 if (!isset($_SESSION['system_update_6021']) && (empty($item['router_path']) || !$existing_item || ($existing_item['link_path'] != $item['link_path']))) {
2019 if ($item['_external']) {
2020 $item['router_path'] = '';
2023 // Find the router path which will serve this path.
2024 $item['parts'] = explode('/', $item['link_path'], MENU_MAX_PARTS
);
2025 $item['router_path'] = _menu_find_router_path($item['link_path']);
2028 db_query("UPDATE {menu_links} SET menu_name = '%s', plid = %d, link_path = '%s',
2029 router_path = '%s', hidden = %d, external = %d, has_children = %d,
2030 expanded = %d, weight = %d, depth = %d,
2031 p1 = %d, p2 = %d, p3 = %d, p4 = %d, p5 = %d, p6 = %d, p7 = %d, p8 = %d, p9 = %d,
2032 module = '%s', link_title = '%s', options = '%s', customized = %d WHERE mlid = %d",
2033 $item['menu_name'], $item['plid'], $item['link_path'],
2034 $item['router_path'], $item['hidden'], $item['_external'], $item['has_children'],
2035 $item['expanded'], $item['weight'], $item['depth'],
2036 $item['p1'], $item['p2'], $item['p3'], $item['p4'], $item['p5'], $item['p6'], $item['p7'], $item['p8'], $item['p9'],
2037 $item['module'], $item['link_title'], serialize($item['options']), $item['customized'], $item['mlid']);
2038 // Check the has_children status of the parent.
2039 _menu_update_parental_status($item);
2040 menu_cache_clear($menu_name);
2041 if ($existing_item && $menu_name != $existing_item['menu_name']) {
2042 menu_cache_clear($existing_item['menu_name']);
2045 _menu_clear_page_cache();
2046 return $item['mlid'];
2050 * Helper function to clear the page and block caches at most twice per page load.
2052 function _menu_clear_page_cache() {
2053 static
$cache_cleared = 0;
2055 // Clear the page and block caches, but at most twice, including at
2056 // the end of the page load when there are multple links saved or deleted.
2057 if (empty($cache_cleared)) {
2059 // Keep track of which menus have expanded items.
2060 _menu_set_expanded_menus();
2063 elseif ($cache_cleared == 1) {
2064 register_shutdown_function('cache_clear_all');
2065 // Keep track of which menus have expanded items.
2066 register_shutdown_function('_menu_set_expanded_menus');
2072 * Helper function to update a list of menus with expanded items
2074 function _menu_set_expanded_menus() {
2076 $result = db_query("SELECT menu_name FROM {menu_links} WHERE expanded != 0 GROUP BY menu_name");
2077 while ($n = db_fetch_array($result)) {
2078 $names[] = $n['menu_name'];
2080 variable_set('menu_expanded', $names);
2084 * Find the router path which will serve this path.
2087 * The path for we are looking up its router path.
2089 * A path from $menu keys or empty if $link_path points to a nonexisting
2092 function _menu_find_router_path($link_path) {
2093 // $menu will only have data during a menu rebuild.
2094 $menu = _menu_router_cache();
2096 $router_path = $link_path;
2097 $parts = explode('/', $link_path, MENU_MAX_PARTS
);
2098 list($ancestors, $placeholders) = menu_get_ancestors($parts);
2101 // Not during a menu rebuild, so look up in the database.
2102 $router_path = (string)db_result(db_query_range('SELECT path FROM {menu_router} WHERE path IN ('.
implode (',', $placeholders) .
') ORDER BY fit DESC', $ancestors, 0, 1));
2104 elseif (!isset($menu[$router_path])) {
2105 // Add an empty path as a fallback.
2107 foreach ($ancestors as
$key => $router_path) {
2108 if (isset($menu[$router_path])) {
2109 // Exit the loop leaving $router_path as the first match.
2113 // If we did not find the path, $router_path will be the empty string
2114 // at the end of $ancestors.
2116 return $router_path;
2120 * Insert, update or delete an uncustomized menu link related to a module.
2123 * The name of the module.
2125 * Operation to perform: insert, update or delete.
2127 * The path this link points to.
2128 * @param $link_title
2129 * Title of the link to insert or new title to update the link to.
2130 * Unused for delete.
2132 * The insert op returns the mlid of the new item. Others op return NULL.
2134 function menu_link_maintain($module, $op, $link_path, $link_title) {
2138 'link_title' => $link_title,
2139 'link_path' => $link_path,
2140 'module' => $module,
2142 return menu_link_save($menu_link);
2145 db_query("UPDATE {menu_links} SET link_title = '%s' WHERE link_path = '%s' AND customized = 0 AND module = '%s'", $link_title, $link_path, $module);
2146 $result = db_query("SELECT menu_name FROM {menu_links} WHERE link_path = '%s' AND customized = 0 AND module = '%s'", $link_path, $module);
2147 while ($item = db_fetch_array($result)) {
2148 menu_cache_clear($item['menu_name']);
2152 menu_link_delete(NULL
, $link_path);
2158 * Find the depth of an item's children relative to its depth.
2160 * For example, if the item has a depth of 2, and the maximum of any child in
2161 * the menu link tree is 5, the relative depth is 3.
2164 * An array representing a menu link item.
2166 * The relative depth, or zero.
2169 function menu_link_children_relative_depth($item) {
2172 $args[] = $item['menu_name'];
2174 while ($i <= MENU_MAX_DEPTH
&& $item[$p]) {
2175 $match .
= " AND $p = %d";
2176 $args[] = $item[$p];
2180 $max_depth = db_result(db_query_range("SELECT depth FROM {menu_links} WHERE menu_name = '%s'".
$match .
" ORDER BY depth DESC", $args, 0, 1));
2182 return ($max_depth > $item['depth']) ?
$max_depth - $item['depth'] : 0;
2186 * Update the children of a menu link that's being moved.
2188 * The menu name, parents (p1 - p6), and depth are updated for all children of
2189 * the link, and the has_children status of the previous parent is updated.
2191 function _menu_link_move_children($item, $existing_item) {
2193 $args[] = $item['menu_name'];
2194 $set[] = "menu_name = '%s'";
2197 while ($i <= $item['depth']) {
2200 $args[] = $item[$p];
2202 $j = $existing_item['depth'] + 1;
2203 while ($i <= MENU_MAX_DEPTH
&& $j <= MENU_MAX_DEPTH
) {
2204 $set[] = 'p'.
$i++ .
' = p'.
$j++;
2206 while ($i <= MENU_MAX_DEPTH
) {
2207 $set[] = 'p'.
$i++ .
' = 0';
2210 $shift = $item['depth'] - $existing_item['depth'];
2213 $set[] = 'depth = depth - %d';
2215 elseif ($shift > 0) {
2216 // The order of $set must be reversed so the new values don't overwrite the
2217 // old ones before they can be used because "Single-table UPDATE
2218 // assignments are generally evaluated from left to right"
2219 // see: http://dev.mysql.com/doc/refman/5.0/en/update.html
2220 $set = array_reverse($set);
2221 $args = array_reverse($args);
2224 $set[] = 'depth = depth + %d';
2226 $where[] = "menu_name = '%s'";
2227 $args[] = $existing_item['menu_name'];
2229 for ($i = 1; $i <= MENU_MAX_DEPTH
&& $existing_item[$p]; $p = 'p'.
++$i) {
2230 $where[] = "$p = %d";
2231 $args[] = $existing_item[$p];
2234 db_query("UPDATE {menu_links} SET ".
implode(', ', $set) .
" WHERE ".
implode(' AND ', $where), $args);
2235 // Check the has_children status of the parent, while excluding this item.
2236 _menu_update_parental_status($existing_item, TRUE
);
2240 * Check and update the has_children status for the parent of a link.
2242 function _menu_update_parental_status($item, $exclude = FALSE
) {
2243 // If plid == 0, there is nothing to update.
2244 if ($item['plid']) {
2245 // We may want to exclude the passed link as a possible child.
2246 $where = $exclude ?
" AND mlid != %d" : '';
2247 // Check if at least one visible child exists in the table.
2248 $parent_has_children = (bool
)db_result(db_query_range("SELECT mlid FROM {menu_links} WHERE menu_name = '%s' AND plid = %d AND hidden = 0".
$where, $item['menu_name'], $item['plid'], $item['mlid'], 0, 1));
2249 db_query("UPDATE {menu_links} SET has_children = %d WHERE mlid = %d", $parent_has_children, $item['plid']);
2254 * Helper function that sets the p1..p9 values for a menu link being saved.
2256 function _menu_link_parents_set(&$item, $parent) {
2258 while ($i < $item['depth']) {
2260 $item[$p] = $parent[$p];
2263 // The parent (p1 - p9) corresponding to the depth always equals the mlid.
2264 $item[$p] = $item['mlid'];
2265 while ($i <= MENU_MAX_DEPTH
) {
2272 * Helper function to build the router table based on the data from hook_menu.
2274 function _menu_router_build($callbacks) {
2275 // First pass: separate callbacks from paths, making paths ready for
2276 // matching. Calculate fitness, and fill some default values.
2278 foreach ($callbacks as
$path => $item) {
2279 $load_functions = array();
2280 $to_arg_functions = array();
2284 $parts = explode('/', $path, MENU_MAX_PARTS
);
2285 $number_parts = count($parts);
2286 // We store the highest index of parts here to save some work in the fit
2287 // calculation loop.
2288 $slashes = $number_parts - 1;
2289 // Extract load and to_arg functions.
2290 foreach ($parts as
$k => $part) {
2292 // Look for wildcards in the form allowed to be used in PHP functions,
2293 // because we are using these to construct the load function names.
2294 // See http://php.net/manual/en/language.functions.php for reference.
2295 if (preg_match('/^%(|[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$/', $part, $matches)) {
2296 if (empty($matches[1])) {
2298 $load_functions[$k] = NULL
;
2301 if (function_exists($matches[1] .
'_to_arg')) {
2302 $to_arg_functions[$k] = $matches[1] .
'_to_arg';
2303 $load_functions[$k] = NULL
;
2306 if (function_exists($matches[1] .
'_load')) {
2307 $function = $matches[1] .
'_load';
2308 // Create an array of arguments that will be passed to the _load
2309 // function when this menu path is checked, if 'load arguments'
2311 $load_functions[$k] = isset($item['load arguments']) ?
array($function => $item['load arguments']) : $function;
2320 $fit |= 1 << ($slashes - $k);
2327 // If there is no %, it fits maximally.
2328 $fit = (1 << $number_parts) - 1;
2331 $item['load_functions'] = empty($load_functions) ?
'' : serialize($load_functions);
2332 $item['to_arg_functions'] = empty($to_arg_functions) ?
'' : serialize($to_arg_functions);
2336 'type' => MENU_NORMAL_ITEM
,
2337 '_number_parts' => $number_parts,
2342 '_visible' => (bool
)($item['type'] & MENU_VISIBLE_IN_BREADCRUMB
),
2343 '_tab' => (bool
)($item['type'] & MENU_IS_LOCAL_TASK
),
2346 $new_path = implode('/', $item['_parts']);
2347 $menu[$new_path] = $item;
2348 $sort[$new_path] = $number_parts;
2351 $menu[$path] = $item;
2352 $sort[$path] = $number_parts;
2355 array_multisort($sort, SORT_NUMERIC
, $menu);
2358 // We must have a serious error - there is no data to save.
2359 watchdog('php', 'Menu router rebuild failed - some paths may not work correctly.', array(), WATCHDOG_ERROR
);
2362 // Delete the existing router since we have some data to replace it.
2363 db_query('DELETE FROM {menu_router}');
2364 // Apply inheritance rules.
2365 foreach ($menu as
$path => $v) {
2366 $item = &$menu[$path];
2367 if (!$item['_tab']) {
2369 $item['tab_parent'] = '';
2370 $item['tab_root'] = $path;
2372 for ($i = $item['_number_parts'] - 1; $i; $i--) {
2373 $parent_path = implode('/', array_slice($item['_parts'], 0, $i));
2374 if (isset($menu[$parent_path])) {
2376 $parent = $menu[$parent_path];
2378 if (!isset($item['tab_parent'])) {
2379 // Parent stores the parent of the path.
2380 $item['tab_parent'] = $parent_path;
2382 if (!isset($item['tab_root']) && !$parent['_tab']) {
2383 $item['tab_root'] = $parent_path;
2385 // If an access callback is not found for a default local task we use
2386 // the callback from the parent, since we expect them to be identical.
2387 // In all other cases, the access parameters must be specified.
2388 if (($item['type'] == MENU_DEFAULT_LOCAL_TASK
) && !isset($item['access callback']) && isset($parent['access callback'])) {
2389 $item['access callback'] = $parent['access callback'];
2390 if (!isset($item['access arguments']) && isset($parent['access arguments'])) {
2391 $item['access arguments'] = $parent['access arguments'];
2394 // Same for page callbacks.
2395 if (!isset($item['page callback']) && isset($parent['page callback'])) {
2396 $item['page callback'] = $parent['page callback'];
2397 if (!isset($item['page arguments']) && isset($parent['page arguments'])) {
2398 $item['page arguments'] = $parent['page arguments'];
2400 if (!isset($item['file']) && isset($parent['file'])) {
2401 $item['file'] = $parent['file'];
2403 if (!isset($item['file path']) && isset($parent['file path'])) {
2404 $item['file path'] = $parent['file path'];
2409 if (!isset($item['access callback']) && isset($item['access arguments'])) {
2410 // Default callback.
2411 $item['access callback'] = 'user_access';
2413 if (!isset($item['access callback']) || empty($item['page callback'])) {
2414 $item['access callback'] = 0;
2416 if (is_bool($item['access callback'])) {
2417 $item['access callback'] = intval($item['access callback']);
2421 'access arguments' => array(),
2422 'access callback' => '',
2423 'page arguments' => array(),
2424 'page callback' => '',
2425 'block callback' => '',
2426 'title arguments' => array(),
2427 'title callback' => 't',
2428 'description' => '',
2431 'tab_root' => $path,
2435 'include file' => '',
2439 // Calculate out the file to be included for each callback, if any.
2440 if ($item['file']) {
2441 $file_path = $item['file path'] ?
$item['file path'] : drupal_get_path('module', $item['module']);
2442 $item['include file'] = $file_path .
'/'.
$item['file'];
2445 $title_arguments = $item['title arguments'] ?
serialize($item['title arguments']) : '';
2446 db_query("INSERT INTO {menu_router}
2447 (path, load_functions, to_arg_functions, access_callback,
2448 access_arguments, page_callback, page_arguments, fit,
2449 number_parts, tab_parent, tab_root,
2450 title, title_callback, title_arguments,
2451 type, block_callback, description, position, weight, file)
2452 VALUES ('%s', '%s', '%s', '%s',
2453 '%s', '%s', '%s', %d,
2456 %d, '%s', '%s', '%s', %d, '%s')",
2457 $path, $item['load_functions'], $item['to_arg_functions'], $item['access callback'],
2458 serialize($item['access arguments']), $item['page callback'], serialize($item['page arguments']), $item['_fit'],
2459 $item['_number_parts'], $item['tab_parent'], $item['tab_root'],
2460 $item['title'], $item['title callback'], $title_arguments,
2461 $item['type'], $item['block callback'], $item['description'], $item['position'], $item['weight'], $item['include file']);
2463 // Sort the masks so they are in order of descending fit, and store them.
2464 $masks = array_keys($masks);
2466 variable_set('menu_masks', $masks);
2472 * Returns TRUE if a path is external (e.g. http://example.com).
2474 function menu_path_is_external($path) {
2475 $colonpos = strpos($path, ':');
2476 return $colonpos !== FALSE
&& !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE
) == check_plain($path);
2480 * Checks whether the site is off-line for maintenance.
2482 * This function will log the current user out and redirect to front page
2483 * if the current user has no 'administer site configuration' permission.
2486 * FALSE if the site is not off-line or its the login page or the user has
2487 * 'administer site configuration' permission.
2488 * TRUE for anonymous users not on the login page if the site is off-line.
2490 function _menu_site_is_offline() {
2491 // Check if site is set to off-line mode.
2492 if (variable_get('site_offline', 0)) {
2493 // Check if the user has administration privileges.
2494 if (user_access('administer site configuration')) {
2495 // Ensure that the off-line message is displayed only once [allowing for
2496 // page redirects], and specifically suppress its display on the site
2497 // maintenance page.
2498 if (drupal_get_normal_path($_GET['q']) != 'admin/settings/site-maintenance') {
2499 drupal_set_message(l(t('Operating in off-line mode.'), 'admin/settings/site-maintenance'), 'status', FALSE
);
2503 // Anonymous users get a FALSE at the login prompt, TRUE otherwise.
2504 if (user_is_anonymous()) {
2505 return $_GET['q'] != 'user' && $_GET['q'] != 'user/login';
2507 // Logged in users are unprivileged here, so they are logged out.
2508 require_once
drupal_get_path('module', 'user') .
'/user.pages.inc';
2516 * Validates the path of a menu link being created or edited.
2519 * TRUE if it is a valid path AND the current user has access permission,
2522 function menu_valid_path($form_item) {
2525 $path = $form_item['link_path'];
2526 // We indicate that a menu administrator is running the menu access check.
2528 if ($path == '<front>' || menu_path_is_external($path)) {
2529 $item = array('access' => TRUE
);
2531 elseif (preg_match('/\/\%/', $path)) {
2532 // Path is dynamic (ie 'user/%'), so check directly against menu_router table.
2533 if ($item = db_fetch_array(db_query("SELECT * FROM {menu_router} where path = '%s' ", $path))) {
2534 $item['link_path'] = $form_item['link_path'];
2535 $item['link_title'] = $form_item['link_title'];
2536 $item['external'] = FALSE
;
2537 $item['options'] = '';
2538 _menu_link_translate($item);
2542 $item = menu_get_item($path);
2544 $menu_admin = FALSE
;
2545 return $item && $item['access'];
2549 * @} End of "defgroup menu".