includes.menu.inc

  1. <?php
  2. // $Id: menu.inc,v 1.255.2.11 2008/04/09 21:11:44 goba Exp $
  3. /**
  4.  * @file
  5.  * API for the Drupal menu system.
  6.  */
  7. /**
  8.  * @defgroup menu Menu system
  9.  * @{
  10.  * Define the navigation menus, and route page requests to code based on URLs.
  11.  *
  12.  * The Drupal menu system drives both the navigation system from a user
  13.  * perspective and the callback system that Drupal uses to respond to URLs
  14.  * passed from the browser. For this reason, a good understanding of the
  15.  * menu system is fundamental to the creation of complex modules.
  16.  *
  17.  * Drupal's menu system follows a simple hierarchy defined by paths.
  18.  * Implementations of hook_menu() define menu items and assign them to
  19.  * paths (which should be unique). The menu system aggregates these items
  20.  * and determines the menu hierarchy from the paths. For example, if the
  21.  * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
  22.  * would form the structure:
  23.  * - a
  24.  *   - a/b
  25.  *     - a/b/c/d
  26.  *     - a/b/h
  27.  * - e
  28.  * - f/g
  29.  * Note that the number of elements in the path does not necessarily
  30.  * determine the depth of the menu item in the tree.
  31.  *
  32.  * When responding to a page request, the menu system looks to see if the
  33.  * path requested by the browser is registered as a menu item with a
  34.  * callback. If not, the system searches up the menu tree for the most
  35.  * complete match with a callback it can find. If the path a/b/i is
  36.  * requested in the tree above, the callback for a/b would be used.
  37.  *
  38.  * The found callback function is called with any arguments specified
  39.  * in the "page arguments" attribute of its menu item. The
  40.  * attribute must be an array. After these arguments, any remaining
  41.  * components of the path are appended as further arguments. In this
  42.  * way, the callback for a/b above could respond to a request for
  43.  * a/b/i differently than a request for a/b/j.
  44.  *
  45.  * For an illustration of this process, see page_example.module.
  46.  *
  47.  * Access to the callback functions is also protected by the menu system.
  48.  * The "access callback" with an optional "access arguments" of each menu
  49.  * item is called before the page callback proceeds. If this returns TRUE,
  50.  * then access is granted; if FALSE, then access is denied. Menu items may
  51.  * omit this attribute to use the value provided by an ancestor item.
  52.  *
  53.  * In the default Drupal interface, you will notice many links rendered as
  54.  * tabs. These are known in the menu system as "local tasks", and they are
  55.  * rendered as tabs by default, though other presentations are possible.
  56.  * Local tasks function just as other menu items in most respects. It is
  57.  * convention that the names of these tasks should be short verbs if
  58.  * possible. In addition, a "default" local task should be provided for
  59.  * each set. When visiting a local task's parent menu item, the default
  60.  * local task will be rendered as if it is selected; this provides for a
  61.  * normal tab user experience. This default task is special in that it
  62.  * links not to its provided path, but to its parent item's path instead.
  63.  * The default task's path is only used to place it appropriately in the
  64.  * menu hierarchy.
  65.  *
  66.  * Everything described so far is stored in the menu_router table. The
  67.  * menu_links table holds the visible menu links. By default these are
  68.  * derived from the same hook_menu definitions, however you are free to
  69.  * add more with menu_link_save().
  70.  */
  71. /**
  72.  * @name Menu flags
  73.  * @{
  74.  * Flags for use in the "type" attribute of menu items.
  75.  */
  76. define('MENU_IS_ROOT'0x0001);
  77. define('MENU_VISIBLE_IN_TREE'0x0002);
  78. define('MENU_VISIBLE_IN_BREADCRUMB'0x0004);
  79. define('MENU_LINKS_TO_PARENT'0x0008);
  80. define('MENU_MODIFIED_BY_ADMIN'0x0020);
  81. define('MENU_CREATED_BY_ADMIN'0x0040);
  82. define('MENU_IS_LOCAL_TASK'0x0080);
  83. /**
  84.  * @} End of "Menu flags".
  85.  */
  86. /**
  87.  * @name Menu item types
  88.  * @{
  89.  * Menu item definitions provide one of these constants, which are shortcuts for
  90.  * combinations of the above flags.
  91.  */
  92. /**
  93.  * Normal menu items show up in the menu tree and can be moved/hidden by
  94.  * the administrator. Use this for most menu items. It is the default value if
  95.  * no menu item type is specified.
  96.  */
  97. define('MENU_NORMAL_ITEM'MENU_VISIBLE_IN_TREE MENU_VISIBLE_IN_BREADCRUMB);
  98. /**
  99.  * Callbacks simply register a path so that the correct function is fired
  100.  * when the URL is accessed. They are not shown in the menu.
  101.  */
  102. define('MENU_CALLBACK'MENU_VISIBLE_IN_BREADCRUMB);
  103. /**
  104.  * Modules may "suggest" menu items that the administrator may enable. They act
  105.  * just as callbacks do until enabled, at which time they act like normal items.
  106.  * Note for the value: 0x0010 was a flag which is no longer used, but this way
  107.  * the values of MENU_CALLBACK and MENU_SUGGESTED_ITEM are separate.
  108.  */
  109. define('MENU_SUGGESTED_ITEM'MENU_VISIBLE_IN_BREADCRUMB 0x0010);
  110. /**
  111.  * Local tasks are rendered as tabs by default. Use this for menu items that
  112.  * describe actions to be performed on their parent item. An example is the path
  113.  * "node/52/edit", which performs the "edit" task on "node/52".
  114.  */
  115. define('MENU_LOCAL_TASK'MENU_IS_LOCAL_TASK);
  116. /**
  117.  * Every set of local tasks should provide one "default" task, that links to the
  118.  * same path as its parent when clicked.
  119.  */
  120. define('MENU_DEFAULT_LOCAL_TASK'MENU_IS_LOCAL_TASK MENU_LINKS_TO_PARENT);
  121. /**
  122.  * @} End of "Menu item types".
  123.  */
  124. /**
  125.  * @name Menu status codes
  126.  * @{
  127.  * Status codes for menu callbacks.
  128.  */
  129. define('MENU_FOUND'1);
  130. define('MENU_NOT_FOUND'2);
  131. define('MENU_ACCESS_DENIED'3);
  132. define('MENU_SITE_OFFLINE'4);
  133. /**
  134.  * @} End of "Menu status codes".
  135.  */
  136. /**
  137.  * @Name Menu tree parameters
  138.  * @{
  139.  * Menu tree
  140.  */
  141.  /**
  142.  * The maximum number of path elements for a menu callback
  143.  */
  144. define('MENU_MAX_PARTS'7);
  145. /**
  146.  * The maximum depth of a menu links tree - matches the number of p columns.
  147.  */
  148. define('MENU_MAX_DEPTH'9);
  149. /**
  150.  * @} End of "Menu tree parameters".
  151.  */
  152. /**
  153.  * Returns the ancestors (and relevant placeholders) for any given path.
  154.  *
  155.  * For example, the ancestors of node/12345/edit are:
  156.  * - node/12345/edit
  157.  * - node/12345/%
  158.  * - node/%/edit
  159.  * - node/%/%
  160.  * - node/12345
  161.  * - node/%
  162.  * - node
  163.  *
  164.  * To generate these, we will use binary numbers. Each bit represents a
  165.  * part of the path. If the bit is 1, then it represents the original
  166.  * value while 0 means wildcard. If the path is node/12/edit/foo
  167.  * then the 1011 bitstring represents node/%/edit/foo where % means that
  168.  * any argument matches that part.  We limit ourselves to using binary
  169.  * numbers that correspond the patterns of wildcards of router items that
  170.  * actually exists.  This list of 'masks' is built in menu_rebuild().
  171.  *
  172.  * @param $parts
  173.  *   An array of path parts, for the above example
  174.  *   array('node', '12345', 'edit').
  175.  * @return
  176.  *   An array which contains the ancestors and placeholders. Placeholders
  177.  *   simply contain as many '%s' as the ancestors.
  178.  */
  179. function menu_get_ancestors($parts) {
  180.   $number_parts count($parts);
  181.   $placeholders = array();
  182.   $ancestors = array();
  183.   $length =  $number_parts 1;
  184.   $end = (<< $number_parts) - 1;
  185.   $masks variable_get('menu_masks', array());
  186.   // Only examine patterns that actually exist as router items (the masks).
  187.   foreach ($masks as $i) {
  188.     if ($i $end) {
  189.       // Only look at masks that are not longer than the path of interest.
  190.       continue;
  191.     }
  192.     elseif ($i < (<< $length)) {
  193.       // We have exhausted the masks of a given length, so decrease the length.
  194.       --$length;
  195.     }
  196.     $current '';
  197.     for ($j $length$j >= 0$j--) {
  198.       if ($i & (<< $j)) {
  199.         $current .= $parts[$length $j];
  200.       }
  201.       else {
  202.         $current .= '%';
  203.       }
  204.       if ($j) {
  205.         $current .= '/';
  206.       }
  207.     }
  208.     $placeholders[] = "'%s'";
  209.     $ancestors[] = $current;
  210.   }
  211.   return array($ancestors$placeholders);
  212. }
  213. /**
  214.  * The menu system uses serialized arrays stored in the database for
  215.  * arguments. However, often these need to change according to the
  216.  * current path. This function unserializes such an array and does the
  217.  * necessary change.
  218.  *
  219.  * Integer values are mapped according to the $map parameter. For
  220.  * example, if unserialize($data) is array('view', 1) and $map is
  221.  * array('node', '12345') then 'view' will not be changed because
  222.  * it is not an integer, but 1 will as it is an integer. As $map[1]
  223.  * is '12345', 1 will be replaced with '12345'. So the result will
  224.  * be array('node_load', '12345').
  225.  *
  226.  * @param @data
  227.  *   A serialized array.
  228.  * @param @map
  229.  *   An array of potential replacements.
  230.  * @return
  231.  *   The $data array unserialized and mapped.
  232.  */
  233. function menu_unserialize($data$map) {
  234.   if ($data unserialize($data)) {
  235.     foreach ($data as $k => $v) {
  236.       if (is_int($v)) {
  237.         $data[$k] = isset($map[$v]) ? $map[$v] : '';
  238.       }
  239.     }
  240.     return $data;
  241.   }
  242.   else {
  243.     return array();
  244.   }
  245. }
  246. /**
  247.  * Replaces the statically cached item for a given path.
  248.  *
  249.  * @param $path
  250.  *   The path.
  251.  * @param $router_item
  252.  *   The router item. Usually you take a router entry from menu_get_item and
  253.  *   set it back either modified or to a different path. This lets you modify the
  254.  *   navigation block, the page title, the breadcrumb and the page help in one
  255.  *   call.
  256.  */
  257. function menu_set_item($path$router_item) {
  258.   menu_get_item($path$router_item);
  259. }
  260. /**
  261.  * Get a router item.
  262.  *
  263.  * @param $path
  264.  *   The path, for example node/5. The function will find the corresponding
  265.  *   node/% item and return that.
  266.  * @param $router_item
  267.  *   Internal use only.
  268.  * @return
  269.  *   The router item, an associate array corresponding to one row in the
  270.  *   menu_router table. The value of key map holds the loaded objects. The
  271.  *   value of key access is TRUE if the current user can access this page.
  272.  *   The values for key title, page_arguments, access_arguments will be
  273.  *   filled in based on the database values and the objects loaded.
  274.  */
  275. function menu_get_item($path NULL$router_item NULL) {
  276.   static $router_items;
  277.   if (!isset($path)) {
  278.     $path $_GET['q'];
  279.   }
  280.   if (isset($router_item)) {
  281.     $router_items[$path] = $router_item;
  282.   }
  283.   if (!isset($router_items[$path])) {
  284.     $original_map arg(NULL$path);
  285.     $parts array_slice($original_map0MENU_MAX_PARTS);
  286.     list($ancestors$placeholders) = menu_get_ancestors($parts);
  287.     if ($router_item db_fetch_array(db_query_range('SELECT * FROM {menu_router} WHERE path IN ('implode (','$placeholders) .') ORDER BY fit DESC'$ancestors01))) {
  288.       $map _menu_translate($router_item$original_map);
  289.       if ($map === FALSE) {
  290.         $router_items[$path] = FALSE;
  291.         return FALSE;
  292.       }
  293.       if ($router_item['access']) {
  294.         $router_item['map'] = $map;
  295.         $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map$router_item['number_parts']));
  296.       }
  297.     }
  298.     $router_items[$path] = $router_item;
  299.   }
  300.   return $router_items[$path];
  301. }
  302. /**
  303.  * Execute the page callback associated with the current path
  304.  */
  305. function menu_execute_active_handler($path NULL) {
  306.   if (_menu_site_is_offline()) {
  307.     return MENU_SITE_OFFLINE;
  308.   }
  309.   if (variable_get('menu_rebuild_needed'FALSE)) {
  310.     menu_rebuild();
  311.   }
  312.   if ($router_item menu_get_item($path)) {
  313.     if ($router_item['access']) {
  314.       if ($router_item['file']) {
  315.         require_once($router_item['file']);
  316.       }
  317.       return call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
  318.     }
  319.     else {
  320.       return MENU_ACCESS_DENIED;
  321.     }
  322.   }
  323.   return MENU_NOT_FOUND;
  324. }
  325. /**
  326.  * Loads objects into the map as defined in the $item['load_functions'].
  327.  *
  328.  * @param $item
  329.  *   A menu router or menu link item
  330.  * @param $map
  331.  *   An array of path arguments (ex: array('node', '5'))
  332.  * @return
  333.  *   Returns TRUE for success, FALSE if an object cannot be loaded.
  334.  *   Names of object loading functions are placed in $item['load_functions'].
  335.  *   Loaded objects are placed in $map[]; keys are the same as keys in the 
  336.  *   $item['load_functions'] array.
  337.  *   $item['access'] is set to FALSE if an object cannot be loaded.
  338.  */
  339. function _menu_load_objects(&$item, &$map) {
  340.   if ($load_functions $item['load_functions']) {
  341.     // If someone calls this function twice, then unserialize will fail.
  342.     if ($load_functions_unserialized unserialize($load_functions)) {
  343.       $load_functions $load_functions_unserialized;
  344.     }
  345.     $path_map $map;
  346.     foreach ($load_functions as $index => $function) {
  347.       if ($function) {
  348.         $value = isset($path_map[$index]) ? $path_map[$index] : '';
  349.         if (is_array($function)) {
  350.           // Set up arguments for the load function. These were pulled from
  351.           // 'load arguments' in the hook_menu() entry, but they need
  352.           // some processing. In this case the $function is the key to the
  353.           // load_function array, and the value is the list of arguments.
  354.           list($function$args) = each($function);
  355.           $load_functions[$index] = $function;
  356.           // Some arguments are placeholders for dynamic items to process.
  357.           foreach ($args as $i => $arg) {
  358.             if ($arg === '%index') {
  359.               // Pass on argument index to the load function, so multiple
  360.               // occurances of the same placeholder can be identified.
  361.               $args[$i] = $index;
  362.             }
  363.             if ($arg === '%map') {
  364.               // Pass on menu map by reference. The accepting function must
  365.               // also declare this as a reference if it wants to modify
  366.               // the map.
  367.               $args[$i] = &$map;
  368.             }
  369.             if (is_int($arg)) {
  370.               $args[$i] = isset($path_map[$arg]) ? $path_map[$arg] : '';
  371.             }
  372.           }
  373.           array_unshift($args$value);
  374.           $return call_user_func_array($function$args);
  375.         }
  376.         else {
  377.           $return $function($value);
  378.         }
  379.         // If callback returned an error or there is no callback, trigger 404.
  380.         if ($return === FALSE) {
  381.           $item['access'] = FALSE;
  382.           $map FALSE;
  383.           return FALSE;
  384.         }
  385.         $map[$index] = $return;
  386.       }
  387.     }
  388.     $item['load_functions'] = $load_functions;
  389.   }
  390.   return TRUE;
  391. }
  392. /**
  393.  * Check access to a menu item using the access callback
  394.  *
  395.  * @param $item
  396.  *   A menu router or menu link item
  397.  * @param $map
  398.  *   An array of path arguments (ex: array('node', '5'))
  399.  * @return
  400.  *   $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
  401.  */
  402. function _menu_check_access(&$item$map) {
  403.   // Determine access callback, which will decide whether or not the current
  404.   // user has access to this path.
  405.   $callback = empty($item['access_callback']) ? trim($item['access_callback']);
  406.   // Check for a TRUE or FALSE value.
  407.   if (is_numeric($callback)) {
  408.     $item['access'] = (bool)$callback;
  409.   }
  410.   else {
  411.     $arguments menu_unserialize($item['access_arguments'], $map);
  412.     // As call_user_func_array is quite slow and user_access is a very common
  413.     // callback, it is worth making a special case for it.
  414.     if ($callback == 'user_access') {
  415.       $item['access'] = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
  416.     }
  417.     else {
  418.       $item['access'] = call_user_func_array($callback$arguments);
  419.     }
  420.   }
  421. }
  422. /**
  423.  * Localize the router item title using t() or another callback.
  424.  *
  425.  * Translate the title and description to allow storage of English title
  426.  * strings in the database, yet display of them in the language required
  427.  * by the current user.
  428.  *
  429.  * @param $item
  430.  *   A menu router item or a menu link item.
  431.  * @param $map
  432.  *   The path as an array with objects already replaced. E.g., for path
  433.  *   node/123 $map would be array('node', $node) where $node is the node
  434.  *   object for node 123.
  435.  * @param $link_translate
  436.  *   TRUE if we are translating a menu link item; FALSE if we are
  437.  *   translating a menu router item.
  438.  * @return
  439.  *   No return value.
  440.  *   $item['title'] is localized according to $item['title_callback'].
  441.  *   If an item's callback is check_plain(), $item['options']['html'] becomes 
  442.  *   TRUE.
  443.  *   $item['description'] is translated using t().
  444.  *   When doing link translation and the $item['options']['attributes']['title'] 
  445.  *   (link title attribute) matches the description, it is translated as well.
  446.  */
  447. function _menu_item_localize(&$item$map$link_translate FALSE) {
  448.   $callback $item['title_callback'];
  449.   $item['localized_options'] = $item['options'];
  450.   // If we are not doing link translation or if the title matches the
  451.   // link title of its router item, localize it.
  452.   if (!$link_translate || (!empty($item['title']) && ($item['title'] == $item['link_title']))) {
  453.     // t() is a special case. Since it is used very close to all the time,
  454.     // we handle it directly instead of using indirect, slower methods.
  455.     if ($callback == 't') {
  456.       if (empty($item['title_arguments'])) {
  457.         $item['title'] = t($item['title']);
  458.       }
  459.       else {
  460.         $item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));
  461.       }
  462.     }
  463.     elseif ($callback) {
  464.       if (empty($item['title_arguments'])) {
  465.         $item['title'] = $callback($item['title']);
  466.       }
  467.       else {
  468.         $item['title'] = call_user_func_array($callbackmenu_unserialize($item['title_arguments'], $map));
  469.       }
  470.       // Avoid calling check_plain again on l() function.
  471.       if ($callback == 'check_plain') {
  472.         $item['localized_options']['html'] = TRUE;
  473.       }
  474.     }
  475.   }
  476.   elseif ($link_translate) {
  477.     $item['title'] = $item['link_title'];
  478.   }
  479.   // Translate description, see the motivation above.
  480.   if (!empty($item['description'])) {
  481.     $original_description $item['description'];
  482.     $item['description'] = t($item['description']);
  483.     if ($link_translate && $item['options']['attributes']['title'] == $original_description) {
  484.       $item['localized_options']['attributes']['title'] = $item['description'];
  485.     }
  486.   }
  487. }
  488. /**
  489.  * Handles dynamic path translation and menu access control.
  490.  *
  491.  * When a user arrives on a page such as node/5, this function determines
  492.  * what "5" corresponds to, by inspecting the page's menu path definition,
  493.  * node/%node. This will call node_load(5) to load the corresponding node
  494.  * object.
  495.  *
  496.  * It also works in reverse, to allow the display of tabs and menu items which
  497.  * contain these dynamic arguments, translating node/%node to node/5.
  498.  *
  499.  * Translation of menu item titles and descriptions are done here to
  500.  * allow for storage of English strings in the database, and translation
  501.  * to the language required to generate the current page
  502.  *
  503.  * @param $router_item
  504.  *   A menu router item
  505.  * @param $map
  506.  *   An array of path arguments (ex: array('node', '5'))
  507.  * @param $to_arg
  508.  *   Execute $item['to_arg_functions'] or not. Use only if you want to render a
  509.  *   path from the menu table, for example tabs.
  510.  * @return
  511.  *   Returns the map with objects loaded as defined in the
  512.  *   $item['load_functions. $item['access'] becomes TRUE if the item is
  513.  *   accessible, FALSE otherwise. $item['href'] is set according to the map.
  514.  *   If an error occurs during calling the load_functions (like trying to load
  515.  *   a non existing node) then this function return FALSE.
  516.  */
  517. function _menu_translate(&$router_item$map$to_arg FALSE) {
  518.   $path_map $map;
  519.   if (!_menu_load_objects($router_item$map)) {
  520.     // An error occurred loading an object.
  521.     $router_item['access'] = FALSE;
  522.     return FALSE;
  523.   }
  524.   if ($to_arg) {
  525.     _menu_link_map_translate($path_map$router_item['to_arg_functions']);
  526.   }
  527.   // Generate the link path for the page request or local tasks.
  528.   $link_map explode('/'$router_item['path']);
  529.   for ($i 0$i $router_item['number_parts']; $i++) {
  530.     if ($link_map[$i] == '%') {
  531.       $link_map[$i] = $path_map[$i];
  532.     }
  533.   }
  534.   $router_item['href'] = implode('/'$link_map);
  535.   $router_item['options'] = array();
  536.   _menu_check_access($router_item$map);
  537.   _menu_item_localize($router_item$map);
  538.   return $map;
  539. }
  540. /**
  541.  * This function translates the path elements in the map using any to_arg
  542.  * helper function. These functions take an argument and return an object.
  543.  * See http://drupal.org/node/109153 for more information.
  544.  *
  545.  * @param map
  546.  *   An array of path arguments (ex: array('node', '5'))
  547.  * @param $to_arg_functions
  548.  *   An array of helper function (ex: array(2 => 'menu_tail_to_arg'))
  549.  */
  550. function _menu_link_map_translate(&$map$to_arg_functions) {
  551.   if ($to_arg_functions) {
  552.     $to_arg_functions unserialize($to_arg_functions);
  553.     foreach ($to_arg_functions as $index => $function) {
  554.       // Translate place-holders into real values.
  555.       $arg $function(!empty($map[$index]) ? $map[$index] : ''$map$index);
  556.       if (!empty($map[$index]) || isset($arg)) {
  557.         $map[$index] = $arg;
  558.       }
  559.       else {
  560.         unset($map[$index]);
  561.       }
  562.     }
  563.   }
  564. }
  565. function menu_tail_to_arg($arg$map$index) {
  566.   return implode('/'array_slice($map$index));
  567. }
  568. /**
  569.  * This function is similar to _menu_translate() but does link-specific
  570.  * preparation such as always calling to_arg functions.
  571.  *
  572.  * @param $item
  573.  *   A menu link
  574.  * @return
  575.  *   Returns the map of path arguments with objects loaded as defined in the
  576.  *   $item['load_functions']:
  577.  *   - $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
  578.  *   - $item['href'] is generated from link_path, possibly by to_arg functions.
  579.  *   - $item['title'] is generated from link_title, and may be localized.
  580.  *   - $item['options'] is unserialized; it is also changed within the call
  581.  *     here to $item['localized_options'] by _menu_item_localize().
  582.  */
  583. function _menu_link_translate(&$item) {
  584.   $item['options'] = unserialize($item['options']);
  585.   if ($item['external']) {
  586.     $item['access'] = 1;
  587.     $map = array();
  588.     $item['href'] = $item['link_path'];
  589.     $item['title'] = $item['link_title'];
  590.     $item['localized_options'] = $item['options'];
  591.   }
  592.   else {
  593.     $map explode('/'$item['link_path']);
  594.     _menu_link_map_translate($map$item['to_arg_functions']);
  595.     $item['href'] = implode('/'$map);
  596.     // Note - skip callbacks without real values for their arguments.
  597.     if (strpos($item['href'], '%') !== FALSE) {
  598.       $item['access'] = FALSE;
  599.       return FALSE;
  600.     }
  601.     // menu_tree_check_access() may set this ahead of time for links to nodes.
  602.     if (!isset($item['access'])) {
  603.       if (!_menu_load_objects($item$map)) {
  604.         // An error occurred loading an object.
  605.         $item['access'] = FALSE;
  606.         return FALSE;
  607.       }
  608.       _menu_check_access($item$map);
  609.     }
  610.     _menu_item_localize($item$mapTRUE);
  611.   }
  612.   
  613.   // Allow other customizations - e.g. adding a page-specific query string to the
  614.   // options array. For performance reasons we only invoke this hook if the link
  615.   // has the 'alter' flag set in the options array.
  616.   if (!empty($item['options']['alter'])) {
  617.     drupal_alter('translated_menu_link'$item$map);
  618.   }
  619.   
  620.   return $map;
  621. }
  622. /**
  623.  * Get a loaded object from a router item.
  624.  *
  625.  * menu_get_object() will provide you the current node on paths like node/5,
  626.  * node/5/revisions/48 etc. menu_get_object('user') will give you the user
  627.  * account on user/5 etc. Note - this function should never be called within a
  628.  * _to_arg function (like user_current_to_arg()) since this may result in an
  629.  * infinite recursion.
  630.  *
  631.  * @param $type
  632.  *   Type of the object. These appear in hook_menu definitons as %type. Core
  633.  *   provides aggregator_feed, aggregator_category, contact, filter_format,
  634.  *   forum_term, menu, menu_link, node, taxonomy_vocabulary, user. See the
  635.  *   relevant {$type}_load function for more on each. Defaults to node.
  636.  * @param $position
  637.  *   The expected position for $type object. For node/%node this is 1, for
  638.  *   comment/reply/%node this is 2. Defaults to 1.
  639.  * @param $path
  640.  *   See menu_get_item() for more on this. Defaults to the current path.
  641.  */
  642. function menu_get_object($type 'node'$position 1$path NULL) {
  643.   $router_item menu_get_item($path);
  644.   if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type .'_load') {
  645.     return $router_item['map'][$position];
  646.   }
  647. }
  648. /**
  649.  * Render a menu tree based on the current path.
  650.  *
  651.  * The tree is expanded based on the current path and dynamic paths are also
  652.  * changed according to the defined to_arg functions (for example the 'My account'
  653.  * link is changed from user/% to a link with the current user's uid).
  654.  *
  655.  * @param $menu_name
  656.  *   The name of the menu.
  657.  * @return
  658.  *   The rendered HTML of that menu on the current page.
  659.  */
  660. function menu_tree($menu_name 'navigation') {
  661.   static $menu_output = array();
  662.   if (!isset($menu_output[$menu_name])) {
  663.     $tree menu_tree_page_data($menu_name);
  664.     $menu_output[$menu_name] = menu_tree_output($tree);
  665.   }
  666.   return $menu_output[$menu_name];
  667. }
  668. /**
  669.  * Returns a rendered menu tree.
  670.  *
  671.  * @param $tree
  672.  *   A data structure representing the tree as returned from menu_tree_data.
  673.  * @return
  674.  *   The rendered HTML of that data structure.
  675.  */
  676. function menu_tree_output($tree) {
  677.   $output '';
  678.   $items = array();
  679.   // Pull out just the menu items we are going to render so that we
  680.   // get an accurate count for the first/last classes.
  681.   foreach ($tree as $data) {
  682.     if (!$data['link']['hidden']) {
  683.       $items[] = $data;
  684.     }
  685.   }
  686.   $num_items count($items);
  687.   foreach ($items as $i => $data) {
  688.     $extra_class NULL;
  689.     if ($i == 0) {
  690.       $extra_class 'first';
  691.     }
  692.     if ($i == $num_items 1) {
  693.       $extra_class 'last';
  694.     }
  695.     $link theme('menu_item_link'$data['link']);
  696.     if ($data['below']) {
  697.       $output .= theme('menu_item'$link$data['link']['has_children'], menu_tree_output($data['below']), $data['link']['in_active_trail'], $extra_class);
  698.     }
  699.     else {
  700.       $output .= theme('menu_item'$link$data['link']['has_children'], ''$data['link']['in_active_trail'], $extra_class);
  701.     }
  702.   }
  703.   return $output theme('menu_tree'$output) : '';
  704. }
  705. /**
  706.  * Get the data structure representing a named menu tree.
  707.  *
  708.  * Since this can be the full tree including hidden items, the data returned
  709.  * may be used for generating an an admin interface or a select.
  710.  *
  711.  * @param $menu_name
  712.  *   The named menu links to return
  713.  * @param $item
  714.  *   A fully loaded menu link, or NULL.  If a link is supplied, only the
  715.  *   path to root will be included in the returned tree- as if this link
  716.  *   represented the current page in a visible menu.
  717.  * @return
  718.  *   An tree of menu links in an array, in the order they should be rendered.
  719.  */
  720. function menu_tree_all_data($menu_name 'navigation'$item NULL) {
  721.   static $tree = array();
  722.   // Use $mlid as a flag for whether the data being loaded is for the whole tree.
  723.   $mlid = isset($item['mlid']) ? $item['mlid'] : 0;
  724.   // Generate a cache ID (cid) specific for this $menu_name and $item.
  725.   $cid 'links:'$menu_name .':all-cid:'$mlid;
  726.   if (!isset($tree[$cid])) {
  727.     // If the static variable doesn't have the data, check {cache_menu}.
  728.     $cache cache_get($cid'cache_menu');
  729.     if ($cache && isset($cache->data)) {
  730.       // If the cache entry exists, it will just be the cid for the actual data.
  731.       // This avoids duplication of large amounts of data.
  732.       $cache cache_get($cache->data'cache_menu');
  733.       if ($cache && isset($cache->data)) {
  734.         $data $cache->data;
  735.       }
  736.     }
  737.     // If the tree data was not in the cache, $data will be NULL.
  738.     if (!isset($data)) {
  739.       // Build and run the query, and build the tree.
  740.       if ($mlid) {
  741.         // The tree is for a single item, so we need to match the values in its
  742.         // p columns and 0 (the top level) with the plid values of other links.
  743.         $args = array(0);
  744.         for ($i 1$i MENU_MAX_DEPTH$i++) {
  745.           $args[] = $item["p$i"];
  746.         }
  747.         $args array_unique($args);
  748.         $placeholders implode(', 'array_fill(0count($args), '%d'));
  749.         $where ' AND ml.plid IN ('$placeholders .')';
  750.         $parents $args;
  751.         $parents[] = $item['mlid'];
  752.       }
  753.       else {
  754.         // Get all links in this menu.
  755.         $where '';
  756.         $args = array();
  757.         $parents = array();
  758.       }
  759.       array_unshift($args$menu_name);
  760.       // Select the links from the table, and recursively build the tree.  We
  761.       // LEFT JOIN since there is no match in {menu_router} for an external
  762.       // link.
  763.       $data['tree'] = menu_tree_data(db_query("
  764.         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.*
  765.         FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
  766.         WHERE ml.menu_name = '%s'"$where ."
  767.         ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC"$args), $parents);
  768.       $data['node_links'] = array();
  769.       menu_tree_collect_node_links($data['tree'], $data['node_links']);
  770.       // Cache the data, if it is not already in the cache.
  771.       $tree_cid _menu_tree_cid($menu_name$data);
  772.       if (!cache_get($tree_cid'cache_menu')) {
  773.         cache_set($tree_cid$data'cache_menu');
  774.       }
  775.       // Cache the cid of the (shared) data using the menu and item-specific cid.
  776.       cache_set($cid$tree_cid'cache_menu');
  777.     }
  778.     // Check access for the current user to each item in the tree.
  779.     menu_tree_check_access($data['tree'], $data['node_links']);
  780.     $tree[$cid] = $data['tree'];
  781.   }
  782.   return $tree[$cid];
  783. }
  784. /**
  785.  * Get the data structure representing a named menu tree, based on the current page.
  786.  *
  787.  * The tree order is maintained by storing each parent in an individual
  788.  * field, see http://drupal.org/node/141866 for more.
  789.  *
  790.  * @param $menu_name
  791.  *   The named menu links to return
  792.  * @return
  793.  *   An array of menu links, in the order they should be rendered. The array
  794.  *   is a list of associative arrays -- these have two keys, link and below.
  795.  *   link is a menu item, ready for theming as a link. Below represents the
  796.  *   submenu below the link if there is one, and it is a subtree that has the
  797.  *   same structure described for the top-level array.
  798.  */
  799. function menu_tree_page_data($menu_name 'navigation') {
  800.   static $tree = array();
  801.   // Load the menu item corresponding to the current page.
  802.   if ($item menu_get_item()) {
  803.     // Generate a cache ID (cid) specific for this page.
  804.     $cid 'links:'$menu_name .':page-cid:'$item['href'] .':'. (int)$item['access'];
  805.     if (!isset($tree[$cid])) {
  806.       // If the static variable doesn't have the data, check {cache_menu}.
  807.       $cache cache_get($cid'cache_menu');
  808.       if ($cache && isset($cache->data)) {
  809.         // If the cache entry exists, it will just be the cid for the actual data.
  810.         // This avoids duplication of large amounts of data.
  811.         $cache cache_get($cache->data'cache_menu');
  812.         if ($cache && isset($cache->data)) {
  813.           $data $cache->data;
  814.         }
  815.       }
  816.       // If the tree data was not in the cache, $data will be NULL.
  817.       if (!isset($data)) {
  818.         // Build and run the query, and build the tree.
  819.         if ($item['access']) {
  820.           // Check whether a menu link exists that corresponds to the current path.
  821.           $args = array($menu_name$item['href']);
  822.           $placeholders "'%s'";
  823.           if (drupal_is_front_page()) {
  824.             $args[] = '<front>';
  825.             $placeholders .= ", '%s'";
  826.           }
  827.           $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));
  828.           if (empty($parents)) {
  829.             // If no link exists, we may be on a local task that's not in the links.
  830.             // TODO: Handle the case like a local task on a specific node in the menu.
  831.             $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']));
  832.           }
  833.           // We always want all the top-level links with plid == 0.
  834.           $parents[] = '0';
  835.           // Use array_values() so that the indices are numeric for array_merge().
  836.           $args $parents array_unique(array_values($parents));
  837.           $placeholders implode(', 'array_fill(0count($args), '%d'));
  838.           $expanded variable_get('menu_expanded', array());
  839.           // Check whether the current menu has any links set to be expanded.
  840.           if (in_array($menu_name$expanded)) {
  841.             // Collect all the links set to be expanded, and then add all of
  842.             // their children to the list as well.
  843.             do {
  844.               $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));
  845.               $num_rows FALSE;
  846.               while ($item db_fetch_array($result)) {
  847.                 $args[] = $item['mlid'];
  848.                 $num_rows TRUE;
  849.               }
  850.               $placeholders implode(', 'array_fill(0count($args), '%d'));
  851.             } while ($num_rows);
  852.           }
  853.           array_unshift($args$menu_name);
  854.         }
  855.         else {
  856.           // Show only the top-level menu items when access is denied.
  857.           $args = array($menu_name'0');
  858.           $placeholders '%d';
  859.           $parents = array();
  860.         }
  861.         // Select the links from the table, and recursively build the tree. We
  862.         // LEFT JOIN since there is no match in {menu_router} for an external
  863.         // link.
  864.         $data['tree'] = menu_tree_data(db_query("
  865.           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.*
  866.           FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
  867.           WHERE ml.menu_name = '%s' AND ml.plid IN ("$placeholders .")
  868.           ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC"$args), $parents);
  869.         $data['node_links'] = array();
  870.         menu_tree_collect_node_links($data['tree'], $data['node_links']);
  871.         // Cache the data, if it is not already in the cache.
  872.         $tree_cid _menu_tree_cid($menu_name$data);
  873.         if (!cache_get($tree_cid'cache_menu')) {
  874.           cache_set($tree_cid$data'cache_menu');
  875.         }
  876.         // Cache the cid of the (shared) data using the page-specific cid.
  877.         cache_set($cid$tree_cid'cache_menu');
  878.       }
  879.       // Check access for the current user to each item in the tree.
  880.       menu_tree_check_access($data['tree'], $data['node_links']);
  881.       $tree[$cid] = $data['tree'];
  882.     }
  883.     return $tree[$cid];
  884.   }
  885.   return array();
  886. }
  887. /**
  888.  * Helper function - compute the real cache ID for menu tree data.
  889.  */
  890. function _menu_tree_cid($menu_name$data) {
  891.   return 'links:'$menu_name .':tree-data:'md5(serialize($data));
  892. }
  893. /**
  894.  * Recursive helper function - collect node links.
  895.  */
  896. function menu_tree_collect_node_links(&$tree, &$node_links) {
  897.   foreach ($tree as $key => $v) {
  898.     if ($tree[$key]['link']['router_path'] == 'node/%') {
  899.       $nid substr($tree[$key]['link']['link_path'], 5);
  900.       if (is_numeric($nid)) {
  901.         $node_links[$nid][$tree[$key]['link']['mlid']] = &$tree[$key]['link'];
  902.         $tree[$key]['link']['access'] = FALSE;
  903.       }
  904.     }
  905.     if ($tree[$key]['below']) {
  906.       menu_tree_collect_node_links($tree[$key]['below'], $node_links);
  907.     }
  908.   }
  909. }
  910. /**
  911.  * Check access and perform other dynamic operations for each link in the tree.
  912.  */
  913. function menu_tree_check_access(&$tree$node_links = array()) {
  914.   if ($node_links) {
  915.     // Use db_rewrite_sql to evaluate view access without loading each full node.
  916.     $nids array_keys($node_links);
  917.     $placeholders '%d'str_repeat(', %d'count($nids) - 1);
  918.     $result db_query(db_rewrite_sql("SELECT n.nid FROM {node} n WHERE n.status = 1 AND n.nid IN ("$placeholders .")"), $nids);
  919.     while ($node db_fetch_array($result)) {
  920.       $nid $node['nid'];
  921.       foreach ($node_links[$nid] as $mlid => $link) {
  922.         $node_links[$nid][$mlid]['access'] = TRUE;
  923.       }
  924.     }
  925.   }
  926.   _menu_tree_check_access($tree);
  927.   return;
  928. }
  929. /**
  930.  * Recursive helper function for menu_tree_check_access()
  931.  */
  932. function _menu_tree_check_access(&$tree) {
  933.   $new_tree = array();
  934.   foreach ($tree as $key => $v) {
  935.     $item = &$tree[$key]['link'];
  936.     _menu_link_translate($item);
  937.     if ($item['access']) {
  938.       if ($tree[$key]['below']) {
  939.         _menu_tree_check_access($tree[$key]['below']);
  940.       }
  941.       // The weights are made a uniform 5 digits by adding 50000 as an offset.
  942.       // After _menu_link_translate(), $item['title'] has the localized link title.
  943.       // Adding the mlid to the end of the index insures that it is unique.
  944.       $new_tree[(50000 $item['weight']) .' '$item['title'] .' '$item['mlid']] = $tree[$key];
  945.     }
  946.   }
  947.   // Sort siblings in the tree based on the weights and localized titles.
  948.   ksort($new_tree);
  949.   $tree $new_tree;
  950. }
  951. /**
  952.  * Build the data representing a menu tree.
  953.  *
  954.  * @param $result
  955.  *   The database result.
  956.  * @param $parents
  957.  *   An array of the plid values that represent the path from the current page
  958.  *   to the root of the menu tree.
  959.  * @param $depth
  960.  *   The depth of the current menu tree.
  961.  * @return
  962.  *   See menu_tree_page_data for a description of the data structure.
  963.  */
  964. function menu_tree_data($result NULL$parents = array(), $depth 1) {
  965.   list(, $tree) = _menu_tree_data($result$parents$depth);
  966.   return $tree;
  967. }
  968. /**
  969.  * Recursive helper function to build the data representing a menu tree.
  970.  *
  971.  * The function is a bit complex because the rendering of an item depends on
  972.  * the next menu item. So we are always rendering the element previously
  973.  * processed not the current one.
  974.  */
  975. function _menu_tree_data($result$parents$depth$previous_element '') {
  976.   $remnant NULL;
  977.   $tree = array();
  978.   while ($item db_fetch_array($result)) {
  979.     // We need to determine if we're on the path to root so we can later build
  980.     // the correct active trail and breadcrumb.
  981.     $item['in_active_trail'] = in_array($item['mlid'], $parents);
  982.     // The current item is the first in a new submenu.
  983.     if ($item['depth'] > $depth) {
  984.       // _menu_tree returns an item and the menu tree structure.
  985.       list($item$below) = _menu_tree_data($result$parents$item['depth'], $item);
  986.       if ($previous_element) {
  987.         $tree[$previous_element['mlid']] = array(
  988.           'link' => $previous_element,
  989.           'below' => $below,
  990.         );
  991.       }
  992.       else {
  993.         $tree $below;
  994.       }
  995.       // We need to fall back one level.
  996.       if (!isset($item) || $item['depth'] < $depth) {
  997.         return array($item$tree);
  998.       }
  999.       // This will be the link to be output in the next iteration.
  1000.       $previous_element $item;
  1001.     }
  1002.     // We are at the same depth, so we use the previous element.
  1003.     elseif ($item['depth'] == $depth) {
  1004.       if ($previous_element) {
  1005.         // Only the first time.
  1006.         $tree[$previous_element['mlid']] = array(
  1007.           'link' => $previous_element,
  1008.           'below' => FALSE,
  1009.         );
  1010.       }
  1011.       // This will be the link to be output in the next iteration.
  1012.       $previous_element $item;
  1013.     }
  1014.     // The submenu ended with the previous item, so pass back the current item.
  1015.     else {
  1016.       $remnant $item;
  1017.       break;
  1018.     }
  1019.   }
  1020.   if ($previous_element) {
  1021.     // We have one more link dangling.
  1022.     $tree[$previous_element['mlid']] = array(
  1023.       'link' => $previous_element,
  1024.       'below' => FALSE,
  1025.     );
  1026.   }
  1027.   return array($remnant$tree);
  1028. }
  1029. /**
  1030.  * Generate the HTML output for a single menu link.
  1031.  *
  1032.  * @ingroup themeable
  1033.  */
  1034. function theme_menu_item_link($link) {
  1035.   if (empty($link['localized_options'])) {
  1036.     $link['localized_options'] = array();
  1037.   }
  1038.   return l($link['title'], $link['href'], $link['localized_options']);
  1039. }
  1040. /**
  1041.  * Generate the HTML output for a menu tree
  1042.  *
  1043.  * @ingroup themeable
  1044.  */
  1045. function theme_menu_tree($tree) {
  1046.   return '<ul class="menu">'$tree .'</ul>';
  1047. }
  1048. /**
  1049.  * Generate the HTML output for a menu item and submenu.
  1050.  *
  1051.  * @ingroup themeable
  1052.  */
  1053. function theme_menu_item($link$has_children$menu ''$in_active_trail FALSE$extra_class NULL) {
  1054.   $class = ($menu 'expanded' : ($has_children 'collapsed' 'leaf'));
  1055.   if (!empty($extra_class)) {
  1056.     $class .= ' '$extra_class;
  1057.   }
  1058.   if ($in_active_trail) {
  1059.     $class .= ' active-trail';
  1060.   }
  1061.   return '<li class="'$class .'">'$link $menu ."</li>\n";
  1062. }
  1063. /**
  1064.  * Generate the HTML output for a single local task link.
  1065.  *
  1066.  * @ingroup themeable
  1067.  */
  1068. function theme_menu_local_task($link$active FALSE) {
  1069.   return '<li '. ($active 'class="active" ' '') .'>'$link ."</li>\n";
  1070. }
  1071. /**
  1072.  * Generates elements for the $arg array in the help hook.
  1073.  */
  1074. function drupal_help_arg($arg = array()) {
  1075.   // Note - the number of empty elements should be > MENU_MAX_PARTS.
  1076.   return $arg + array('''''''''''''''''''''''');
  1077. }
  1078. /**
  1079.  * Returns the help associated with the active menu item.
  1080.  */
  1081. function menu_get_active_help() {
  1082.   $output '';
  1083.   $router_path menu_tab_root_path();
  1084.   $arg drupal_help_arg(arg(NULL));
  1085.   $empty_arg drupal_help_arg();
  1086.   foreach (module_list() as $name) {
  1087.     if (module_hook($name'help')) {
  1088.       // Lookup help for this path.
  1089.       if ($help module_invoke($name'help'$router_path$arg)) {
  1090.         $output .= $help ."\n";
  1091.       }
  1092.       // Add "more help" link on admin pages if the module provides a
  1093.       // standalone help page.
  1094.       if ($arg[0] == "admin" && module_exists('help') && module_invoke($name'help''admin/help#'$arg[2], $empty_arg) && $help) {
  1095.         $output .= theme("more_help_link"url('admin/help/'$arg[2]));
  1096.       }
  1097.     }
  1098.   }
  1099.   return $output;
  1100. }
  1101. /**
  1102.  * Build a list of named menus.
  1103.  */
  1104. function menu_get_names($reset FALSE) {
  1105.   static $names;
  1106.   if ($reset || empty($names)) {
  1107.     $names = array();
  1108.     $result db_query("SELECT DISTINCT(menu_name) FROM {menu_links} ORDER BY menu_name");
  1109.     while ($name db_fetch_array($result)) {
  1110.       $names[] = $name['menu_name'];
  1111.     }
  1112.   }
  1113.   return $names;
  1114. }
  1115. /**
  1116.  * Return an array containing the names of system-defined (default) menus.
  1117.  */
  1118. function menu_list_system_menus() {
  1119.   return array('navigation''primary-links''secondary-links');
  1120. }
  1121. /**
  1122.  * Return an array of links to be rendered as the Primary links.
  1123.  */
  1124. function menu_primary_links() {
  1125.   return menu_navigation_links(variable_get('menu_primary_links_source''primary-links'));
  1126. }
  1127. /**
  1128.  * Return an array of links to be rendered as the Secondary links.
  1129.  */
  1130. function menu_secondary_links() {
  1131.   // If the secondary menu source is set as the primary menu, we display the
  1132.   // second level of the primary menu.
  1133.   if (variable_get('menu_secondary_links_source''secondary-links') == variable_get('menu_primary_links_source''primary-links')) {
  1134.     return menu_navigation_links(variable_get('menu_primary_links_source''primary-links'), 1);
  1135.   }
  1136.   else {
  1137.     return menu_navigation_links(variable_get('menu_secondary_links_source''secondary-links'), 0);
  1138.   }
  1139. }
  1140. /**
  1141.  * Return an array of links for a navigation menu.
  1142.  *
  1143.  * @param $menu_name
  1144.  *   The name of the menu.
  1145.  * @param $level
  1146.  *   Optional, the depth of the menu to be returned.
  1147.  * @return
  1148.  *   An array of links of the specified menu and level.
  1149.  */
  1150. function menu_navigation_links($menu_name$level 0) {
  1151.   // Don't even bother querying the menu table if no menu is specified.
  1152.   if (empty($menu_name)) {
  1153.     return array();
  1154.   }
  1155.   // Get the menu hierarchy for the current page.
  1156.   $tree menu_tree_page_data($menu_name);
  1157.   // Go down the active trail until the right level is reached.
  1158.   while ($level-- > && $tree) {
  1159.     // Loop through the current level's items until we find one that is in trail.
  1160.     while ($item array_shift($tree)) {
  1161.       if ($item['link']['in_active_trail']) {
  1162.         // If the item is in the active trail, we continue in the subtree.
  1163.         $tree = empty($item['below']) ? array() : $item['below'];
  1164.         break;
  1165.       }
  1166.     }
  1167.   }
  1168.   // Create a single level of links.
  1169.   $links = array();
  1170.   foreach ($tree as $item) {
  1171.     if (!$item['link']['hidden']) {
  1172.       $l $item['link']['localized_options'];
  1173.       $l['href'] = $item['link']['href'];
  1174.       $l['title'] = $item['link']['title'];
  1175.       // Keyed with unique menu id to generate classes from theme_links().
  1176.       $links['menu-'$item['link']['mlid']] = $l;
  1177.     }
  1178.   }
  1179.   return $links;
  1180. }
  1181. /**
  1182.  * Collects the local tasks (tabs) for a given level.
  1183.  *
  1184.  * @param $level
  1185.  *   The level of tasks you ask for. Primary tasks are 0, secondary are 1.
  1186.  * @param $return_root
  1187.  *   Whether to return the root path for the current page.
  1188.  * @return
  1189.  *   Themed output corresponding to the tabs of the requested level, or
  1190.  *   router path if $return_root == TRUE. This router path corresponds to
  1191.  *   a parent tab, if the current page is a default local task.
  1192.  */
  1193. function menu_local_tasks($level 0$return_root FALSE) {
  1194.   static $tabs;
  1195.   static $root_path;
  1196.   if (!isset($tabs)) {
  1197.     $tabs = array();
  1198.     $router_item menu_get_item();
  1199.     if (!$router_item || !$router_item['access']) {
  1200.       return '';
  1201.     }
  1202.     // Get all tabs and the root page.
  1203.     $result db_query("SELECT * FROM {menu_router} WHERE tab_root = '%s' ORDER BY weight, title"$router_item['tab_root']);
  1204.     $map arg();
  1205.     $children = array();
  1206.     $tasks = array();
  1207.     $root_path $router_item['path'];
  1208.     while ($item db_fetch_array($result)) {
  1209.       _menu_translate($item$mapTRUE);
  1210.       if ($item['tab_parent']) {
  1211.         // All tabs, but not the root page.
  1212.         $children[$item['tab_parent']][$item['path']] = $item;
  1213.       }
  1214.       // Store the translated item for later use.
  1215.       $tasks[$item['path']] = $item;
  1216.     }
  1217.     // Find all tabs below the current path.
  1218.     $path $router_item['path'];
  1219.     // Tab parenting may skip levels, so the number of parts in the path may not
  1220.     // equal the depth. Thus we use the $depth counter (offset by 1000 for ksort).
  1221.     $depth 1001;
  1222.     while (isset($children[$path])) {
  1223.       $tabs_current '';
  1224.       $next_path '';
  1225.       $count 0;
  1226.       foreach ($children[$path] as $item) {
  1227.         if ($item['access']) {
  1228.           $count++;
  1229.           // The default task is always active.
  1230.           if ($item['type'] == MENU_DEFAULT_LOCAL_TASK) {
  1231.             // Find the first parent which is not a default local task.
  1232.             for ($p $item['tab_parent']; $tasks[$p]['type'] == MENU_DEFAULT_LOCAL_TASK$p $tasks[$p]['tab_parent']);
  1233.             $link theme('menu_item_link', array('href' => $tasks[$p]['href']) + $item);
  1234.             $tabs_current .= theme('menu_local_task'$linkTRUE);
  1235.             $next_path $item['path'];
  1236.           }
  1237.           else {
  1238.             $link theme('menu_item_link'$item);
  1239.             $tabs_current .= theme('menu_local_task'$link);
  1240.           }
  1241.         }
  1242.       }
  1243.       $path $next_path;
  1244.       $tabs[$depth]['count'] = $count;
  1245.       $tabs[$depth]['output'] = $tabs_current;
  1246.       $depth++;
  1247.     }
  1248.     // Find all tabs at the same level or above the current one.
  1249.     $parent $router_item['tab_parent'];
  1250.     $path $router_item['path'];
  1251.     $current $router_item;
  1252.     $depth 1000;
  1253.     while (isset($children[$parent])) {
  1254.       $tabs_current '';
  1255.       $next_path '';
  1256.       $next_parent '';
  1257.       $count 0;
  1258.       foreach ($children[$parent] as $item) {
  1259.         if ($item['access']) {
  1260.           $count++;
  1261.           if ($item['type'] == MENU_DEFAULT_LOCAL_TASK) {
  1262.             // Find the first parent which is not a default local task.
  1263.             for ($p $item['tab_parent']; $tasks[$p]['type'] == MENU_DEFAULT_LOCAL_TASK$p $tasks[$p]['tab_parent']);
  1264.             $link theme('menu_item_link', array('href' => $tasks[$p]['href']) + $item);
  1265.             if ($item['path'] == $router_item['path']) {
  1266.               $root_path $tasks[$p]['path'];
  1267.             }
  1268.           }
  1269.           else {
  1270.             $link theme('menu_item_link'$item);
  1271.           }
  1272.           // We check for the active tab.
  1273.           if ($item['path'] == $path) {
  1274.             $tabs_current .= theme('menu_local_task'$linkTRUE);
  1275.             $next_path $item['tab_parent'];
  1276.             if (isset($tasks[$next_path])) {
  1277.               $next_parent $tasks[$next_path]['tab_parent'];
  1278.             }
  1279.           }
  1280.           else {
  1281.             $tabs_current .= theme('menu_local_task'$link);
  1282.           }
  1283.         }
  1284.       }
  1285.       $path $next_path;
  1286.       $parent $next_parent;
  1287.       $tabs[$depth]['count'] = $count;
  1288.       $tabs[$depth]['output'] = $tabs_current;
  1289.       $depth--;
  1290.     }
  1291.     // Sort by depth.
  1292.     ksort($tabs);
  1293.     // Remove the depth, we are interested only in their relative placement.
  1294.     $tabs array_values($tabs);
  1295.   }
  1296.   if ($return_root) {
  1297.     return $root_path;
  1298.   }
  1299.   else {
  1300.     // We do not display single tabs.
  1301.     return (isset($tabs[$level]) && $tabs[$level]['count'] > 1) ? $tabs[$level]['output'] : '';
  1302.   }
  1303. }
  1304. /**
  1305.  * Returns the rendered local tasks at the top level.
  1306.  */
  1307. function menu_primary_local_tasks() {
  1308.   return menu_local_tasks(0);
  1309. }
  1310. /**
  1311.  * Returns the rendered local tasks at the second level.
  1312.  */
  1313. function menu_secondary_local_tasks() {
  1314.   return menu_local_tasks(1);
  1315. }
  1316. /**
  1317.  * Returns the router path, or the path of the parent tab of a default local task.
  1318.  */
  1319. function menu_tab_root_path() {
  1320.   return menu_local_tasks(0TRUE);
  1321. }
  1322. /**
  1323.  * Returns the rendered local tasks. The default implementation renders them as tabs.
  1324.  *
  1325.  * @ingroup themeable
  1326.  */
  1327. function theme_menu_local_tasks() {
  1328.   $output '';
  1329.   if ($primary menu_primary_local_tasks()) {
  1330.     $output .= "<ul class=\"tabs primary\">\n"$primary ."</ul>\n";
  1331.   }
  1332.   if ($secondary menu_secondary_local_tasks()) {
  1333.     $output .= "<ul class=\"tabs secondary\">\n"$secondary ."</ul>\n";
  1334.   }
  1335.   return $output;
  1336. }
  1337. /**
  1338.  * Set (or get) the active menu for the current page - determines the active trail.
  1339.  */
  1340. function menu_set_active_menu_name($menu_name NULL) {
  1341.   static $active;
  1342.   if (isset($menu_name)) {
  1343.     $active $menu_name;
  1344.   }
  1345.   elseif (!isset($active)) {
  1346.     $active 'navigation';
  1347.   }
  1348.   return $active;
  1349. }
  1350. /**
  1351.  * Get the active menu for the current page - determines the active trail.
  1352.  */
  1353. function menu_get_active_menu_name() {
  1354.   return menu_set_active_menu_name();
  1355. }
  1356. /**
  1357.  * Set the active path, which determines which page is loaded.
  1358.  *
  1359.  * @param $path
  1360.  *   A Drupal path - not a path alias.
  1361.  *
  1362.  * Note that this may not have the desired effect unless invoked very early
  1363.  * in the page load, such as during hook_boot, or unless you call
  1364.  * menu_execute_active_handler() to generate your page output.
  1365.  */
  1366. function menu_set_active_item($path) {
  1367.   $_GET['q'] = $path;
  1368. }
  1369. /**
  1370.  * Set (or get) the active trail for the current page - the path to root in the menu tree.
  1371.  */
  1372. function menu_set_active_trail($new_trail NULL) {
  1373.   static $trail;
  1374.   if (isset($new_trail)) {
  1375.     $trail $new_trail;
  1376.   }
  1377.   elseif (!isset($trail)) {
  1378.     $trail = array();
  1379.     $trail[] = array('title' => t('Home'), 'href' => '<front>''localized_options' => array(), 'type' => 0);
  1380.     $item menu_get_item();
  1381.     // Check whether the current item is a local task (displayed as a tab).
  1382.     if ($item['tab_parent']) {
  1383.       // The title of a local task is used for the tab, never the page title.
  1384.       // Thus, replace it with the item corresponding to the root path to get
  1385.       // the relevant href and title.  For example, the menu item corresponding
  1386.       // to 'admin' is used when on the 'By module' tab at 'admin/by-module'.
  1387.       $parts explode('/'$item['tab_root']);
  1388.       $args arg();
  1389.       // Replace wildcards in the root path using the current path.
  1390.       foreach ($parts as $index => $part) {
  1391.         if ($part == '%') {
  1392.           $parts[$index] = $args[$index];
  1393.         }
  1394.       }
  1395.       // Retrieve the menu item using the root path after wildcard replacement.
  1396.       $root_item menu_get_item(implode('/'$parts));
  1397.       if ($root_item && $root_item['access']) {
  1398.         $item $root_item;
  1399.       }
  1400.     }
  1401.     $tree menu_tree_page_data(menu_get_active_menu_name());
  1402.     list($key$curr) = each($tree);
  1403.     while ($curr) {
  1404.       // Terminate the loop when we find the current path in the active trail.
  1405.       if ($curr['link']['href'] == $item['href']) {
  1406.         $trail[] = $curr['link'];
  1407.         $curr FALSE;
  1408.       }
  1409.       else {
  1410.         // Move to the child link if it's in the active trail.
  1411.         if ($curr['below'] && $curr['link']['in_active_trail']) {
  1412.           $trail[] = $curr['link'];
  1413.           $tree $curr['below'];
  1414.         }
  1415.         list($key$curr) = each($tree);
  1416.       }
  1417.     }
  1418.     // Make sure the current page is in the trail (needed for the page title),
  1419.     // but exclude tabs and the front page.
  1420.     $last count($trail) - 1;
  1421.     if ($trail[$last]['href'] != $item['href'] && !(bool)($item['type'] & MENU_IS_LOCAL_TASK) && !drupal_is_front_page()) {
  1422.       $trail[] = $item;
  1423.     }
  1424.   }
  1425.   return $trail;
  1426. }
  1427. /**
  1428.  * Get the active trail for the current page - the path to root in the menu tree.
  1429.  */
  1430. function menu_get_active_trail() {
  1431.   return menu_set_active_trail();
  1432. }
  1433. /**
  1434.  * Get the breadcrumb for the current page, as determined by the active trail.
  1435.  */
  1436. function menu_get_active_breadcrumb() {
  1437.   $breadcrumb = array();
  1438.   
  1439.   // No breadcrumb for the front page.
  1440.   if (drupal_is_front_page()) {
  1441.     return $breadcrumb;
  1442.   }
  1443.   $item menu_get_item();
  1444.   if ($item && $item['access']) {
  1445.     $active_trail menu_get_active_trail();
  1446.     foreach ($active_trail as $parent) {
  1447.       $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
  1448.     }
  1449.     $end end($active_trail);
  1450.     // Don't show a link to the current page in the breadcrumb trail.
  1451.     if ($item['href'] == $end['href'] || ($item['type'] == MENU_DEFAULT_LOCAL_TASK && $end['href'] != '<front>')) {
  1452.       array_pop($breadcrumb);
  1453.     }
  1454.   }
  1455.   return $breadcrumb;
  1456. }
  1457. /**
  1458.  * Get the title of the current page, as determined by the active trail.
  1459.  */
  1460. function menu_get_active_title() {
  1461.   $active_trail menu_get_active_trail();
  1462.   foreach (array_reverse($active_trail) as $item) {
  1463.     if (!(bool)($item['type'] & MENU_IS_LOCAL_TASK)) {
  1464.       return $item['title'];
  1465.     }
  1466.   }
  1467. }
  1468. /**
  1469.  * Get a menu link by its mlid, access checked and link translated for rendering.
  1470.  *
  1471.  * This function should never be called from within node_load() or any other
  1472.  * function used as a menu object load function since an infinite recursion may
  1473.  * occur.
  1474.  *
  1475.  * @param $mlid
  1476.  *   The mlid of the menu item.
  1477.  * @return
  1478.  *   A menu link, with $item['access'] filled and link translated for
  1479.  *   rendering.
  1480.  */
  1481. function menu_link_load($mlid) {
  1482.   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))) {
  1483.     _menu_link_translate($item);
  1484.     return $item;
  1485.   }
  1486.   return FALSE;
  1487. }
  1488. /**
  1489.  * Clears the cached cached data for a single named menu.
  1490.  */
  1491. function menu_cache_clear($menu_name 'navigation') {
  1492.   static $cache_cleared = array();
  1493.   if (empty($cache_cleared[$menu_name])) {
  1494.     cache_clear_all('links:'$menu_name .':''cache_menu'TRUE);
  1495.     $cache_cleared[$menu_name] = 1;
  1496.   }
  1497.   elseif ($cache_cleared[$menu_name] == 1) {
  1498.     register_shutdown_function('cache_clear_all''links:'$menu_name .':''cache_menu'TRUE);
  1499.     $cache_cleared[$menu_name] = 2;
  1500.   }
  1501. }
  1502. /**
  1503.  * Clears all cached menu data.  This should be called any time broad changes
  1504.  * might have been made to the router items or menu links.
  1505.  */
  1506. function menu_cache_clear_all() {
  1507.   cache_clear_all('*''cache_menu'TRUE);
  1508. }
  1509. /**
  1510.  * (Re)populate the database tables used by various menu functions.
  1511.  *
  1512.  * This function will clear and populate the {menu_router} table, add entries
  1513.  * to {menu_links} for new router items, then remove stale items from
  1514.  * {menu_links}. If called from update.php or install.php, it will also
  1515.  * schedule a call to itself on the first real page load from
  1516.  * menu_execute_active_handler(), because the maintenance page environment
  1517.  * is different and leaves stale data in the menu tables.
  1518.  */
  1519. function menu_rebuild() {
  1520.   variable_del('menu_rebuild_needed');
  1521.   menu_cache_clear_all();
  1522.   $menu menu_router_build(TRUE);
  1523.   _menu_navigation_links_rebuild($menu);
  1524.   // Clear the page and block caches.
  1525.   _menu_clear_page_cache();
  1526.   if (defined('MAINTENANCE_MODE')) {
  1527.     variable_set('menu_rebuild_needed'TRUE);
  1528.   }
  1529. }
  1530. /**
  1531.  * Collect, alter and store the menu definitions.
  1532.  */
  1533. function menu_router_build($reset FALSE) {
  1534.   static $menu;
  1535.   if (!isset($menu) || $reset) {
  1536.     if (!$reset && ($cache cache_get('router:''cache_menu')) && isset($cache->data)) {
  1537.       $menu $cache->data;
  1538.     }
  1539.     else {
  1540.       db_query('DELETE FROM {menu_router}');
  1541.       // We need to manually call each module so that we can know which module
  1542.       // a given item came from.
  1543.       $callbacks = array();
  1544.       foreach (module_implements('menu') as $module) {
  1545.         $router_items call_user_func($module .'_menu');
  1546.         if (isset($router_items) && is_array($router_items)) {
  1547.           foreach (array_keys($router_items) as $path) {
  1548.             $router_items[$path]['module'] = $module;
  1549.           }
  1550.           $callbacks array_merge($callbacks$router_items);
  1551.         }
  1552.       }
  1553.       // Alter the menu as defined in modules, keys are like user/%user.
  1554.       drupal_alter('menu'$callbacks);
  1555.       $menu _menu_router_build($callbacks);
  1556.       cache_set('router:'$menu'cache_menu');
  1557.     }
  1558.   }
  1559.   return $menu;
  1560. }
  1561. /**
  1562.  * Builds a link from a router item.
  1563.  */
  1564. function _menu_link_build($item) {
  1565.   if ($item['type'] == MENU_CALLBACK) {
  1566.     $item['hidden'] = -1;
  1567.   }
  1568.   elseif ($item['type'] == MENU_SUGGESTED_ITEM) {
  1569.     $item['hidden'] = 1;
  1570.   }
  1571.   // Note, we set this as 'system', so that we can be sure to distinguish all
  1572.   // the menu links generated automatically from entries in {menu_router}.
  1573.   $item['module'] = 'system';
  1574.   $item += array(
  1575.     'menu_name' => 'navigation',
  1576.     'link_title' => $item['title'],
  1577.     'link_path' => $item['path'],
  1578.     'hidden' => 0,
  1579.     'options' => empty($item['description']) ? array() : array('attributes' => array('title' => $item['description'])),
  1580.   );
  1581.   return $item;
  1582. }
  1583. /**
  1584.  * Helper function to build menu links for the items in the menu router.
  1585.  */
  1586. function _menu_navigation_links_rebuild($menu) {
  1587.   // Add normal and suggested items as links.
  1588.   $menu_links = array();
  1589.   foreach ($menu as $path => $item) {
  1590.     if ($item['_visible']) {
  1591.       $item _menu_link_build($item);
  1592.       $menu_links[$path] = $item;
  1593.       $sort[$path] = $item['_number_parts'];
  1594.     }
  1595.   }
  1596.   if ($menu_links) {
  1597.     // Make sure no child comes before its parent.
  1598.     array_multisort($sortSORT_NUMERIC$menu_links);
  1599.     foreach ($menu_links as $item) {
  1600.       $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'));
  1601.       if ($existing_item) {
  1602.         $item['mlid'] = $existing_item['mlid'];
  1603.         $item['menu_name'] = $existing_item['menu_name'];
  1604.         $item['plid'] = $existing_item['plid'];
  1605.         $item['has_children'] = $existing_item['has_children'];
  1606.         $item['updated'] = $existing_item['updated'];
  1607.       }
  1608.       if (!$existing_item || !$existing_item['customized']) {
  1609.         menu_link_save($item);
  1610.       }
  1611.     }
  1612.   }
  1613.   $placeholders db_placeholders($menu'varchar');
  1614.   $paths array_keys($menu);
  1615.   // Updated and customized items whose router paths are gone need new ones.
  1616.   $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);
  1617.   while ($item db_fetch_array($result)) {
  1618.     $router_path _menu_find_router_path($menu$item['link_path']);
  1619.     if (!empty($router_path) && ($router_path != $item['router_path'] || $item['updated'])) {
  1620.       // If the router path and the link path matches, it's surely a working
  1621.       // item, so we clear the updated flag.
  1622.       $updated $item['updated'] && $router_path != $item['link_path'];
  1623.       db_query("UPDATE {menu_links} SET router_path = '%s', updated = %d WHERE mlid = %d"$router_path$updated$item['mlid']);
  1624.     }
  1625.   }
  1626.   // Find any item whose router path does not exist any more.
  1627.   $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);
  1628.   // Remove all such items. Starting from those with the greatest depth will
  1629.   // minimize the amount of re-parenting done by menu_link_delete().
  1630.   while ($item db_fetch_array($result)) {
  1631.     _menu_delete_item($itemTRUE);
  1632.   }
  1633. }
  1634. /**
  1635.  * Delete one or several menu links.
  1636.  *
  1637.  * @param $mlid
  1638.  *   A valid menu link mlid or NULL. If NULL, $path is used.
  1639.  * @param $path
  1640.  *   The path to the menu items to be deleted. $mlid must be NULL.
  1641.  */
  1642. function menu_link_delete($mlid$path NULL) {
  1643.   if (isset($mlid)) {
  1644.     _menu_delete_item(db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d"$mlid)));
  1645.   }
  1646.   else {
  1647.     $result db_query("SELECT * FROM {menu_links} WHERE link_path = '%s'"$path);
  1648.     while ($link db_fetch_array($result)) {
  1649.       _menu_delete_item($link);
  1650.     }
  1651.   }
  1652. }
  1653. /**
  1654.  * Helper function for menu_link_delete; deletes a single menu link.
  1655.  *
  1656.  * @param $item
  1657.  *   Item to be deleted.
  1658.  * @param $force
  1659.  *   Forces deletion. Internal use only, setting to TRUE is discouraged.
  1660.  */
  1661. function _menu_delete_item($item$force FALSE) {
  1662.   if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) {
  1663.     // Children get re-attached to the item's parent.
  1664.     if ($item['has_children']) {
  1665.       $result db_query("SELECT mlid FROM {menu_links} WHERE plid = %d"$item['mlid']);
  1666.       while ($m db_fetch_array($result)) {
  1667.         $child menu_link_load($m['mlid']);
  1668.         $child['plid'] = $item['plid'];
  1669.         menu_link_save($child);
  1670.       }
  1671.     }
  1672.     db_query('DELETE FROM {menu_links} WHERE mlid = %d'$item['mlid']);
  1673.     // Update the has_children status of the parent.
  1674.     _menu_update_parental_status($item);
  1675.     menu_cache_clear($item['menu_name']);
  1676.     _menu_clear_page_cache();
  1677.   }
  1678. }
  1679. /**
  1680.  * Save a menu link.
  1681.  *
  1682.  * @param $item
  1683.  *   An array representing a menu link item. The only mandatory keys are
  1684.  *   link_path and link_title. Possible keys are:
  1685.  *   - menu_name   default is navigation
  1686.  *   - weight      default is 0
  1687.  *   - expanded    whether the item is expanded.
  1688.  *   - options     An array of options, @see l for more.
  1689.  *   - mlid        Set to an existing value, or 0 or NULL to insert a new link.
  1690.  *   - plid        The mlid of the parent.
  1691.  *   - router_path The path of the relevant router item.
  1692.  */
  1693. function menu_link_save(&$item) {
  1694.   $menu menu_router_build();
  1695.   drupal_alter('menu_link'$item$menu);
  1696.   // This is the easiest way to handle the unique internal path '<front>',
  1697.   // since a path marked as external does not need to match a router path.
  1698.   $item['_external'] = menu_path_is_external($item['link_path'])  || $item['link_path'] == '<front>';
  1699.   // Load defaults.
  1700.   $item += array(
  1701.     'menu_name' => 'navigation',
  1702.     'weight' => 0,
  1703.     'link_title' => '',
  1704.     'hidden' => 0,
  1705.     'has_children' => 0,
  1706.     'expanded' => 0,
  1707.     'options' => array(),
  1708.     'module' => 'menu',
  1709.     'customized' => 0,
  1710.     'updated' => 0,
  1711.   );
  1712.   $existing_item FALSE;
  1713.   if (isset($item['mlid'])) {
  1714.     $existing_item db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d"$item['mlid']));
  1715.   }
  1716.   if (isset($item['plid'])) {
  1717.     $parent db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d"$item['plid']));
  1718.   }
  1719.   else {
  1720.     // Find the parent - it must be unique.
  1721.     $parent_path $item['link_path'];
  1722.     $where "WHERE link_path = '%s'";
  1723.     // Only links derived from router items should have module == 'system', and
  1724.     // we want to find the parent even if it's in a different menu.
  1725.     if ($item['module'] == 'system') {
  1726.       $where .= " AND module = '%s'";
  1727.       $arg2 'system';
  1728.     }
  1729.     else {
  1730.       // If not derived from a router item, we respect the specified menu name.
  1731.       $where .= " AND menu_name = '%s'";
  1732.       $arg2 $item['menu_name'];
  1733.     }
  1734.     do {
  1735.       $parent FALSE;
  1736.       $parent_path substr($parent_path0strrpos($parent_path'/'));
  1737.       $result db_query("SELECT COUNT(*) FROM {menu_links} "$where$parent_path$arg2);
  1738.       // Only valid if we get a unique result.
  1739.       if (db_result($result) == 1) {
  1740.         $parent db_fetch_array(db_query("SELECT * FROM {menu_links} "$where$parent_path$arg2));
  1741.       }
  1742.     } while ($parent === FALSE && $parent_path);
  1743.   }
  1744.   if ($parent !== FALSE) {
  1745.     $item['menu_name'] = $parent['menu_name'];
  1746.   }
  1747.   $menu_name $item['menu_name'];
  1748.   // Menu callbacks need to be in the links table for breadcrumbs, but can't
  1749.   // be parents if they are generated directly from a router item.
  1750.   if (empty($parent['mlid']) || $parent['hidden'] < 0) {
  1751.     $item['plid'] =  0;
  1752.   }
  1753.   else {
  1754.     $item['plid'] = $parent['mlid'];
  1755.   }
  1756.   if (!$existing_item) {
  1757.     db_query("INSERT INTO {menu_links} (
  1758.        menu_name, plid, link_path,
  1759.       hidden, external, has_children,
  1760.       expanded, weight,
  1761.       module, link_title, options,
  1762.       customized, updated) VALUES (
  1763.       '%s', %d, '%s',
  1764.       %d, %d, %d,
  1765.       %d, %d,
  1766.       '%s', '%s', '%s', %d, %d)",
  1767.       $item['menu_name'], $item['plid'], $item['link_path'],
  1768.       $item['hidden'], $item['_external'], $item['has_children'],
  1769.       $item['expanded'], $item['weight'],
  1770.       $item['module'],  $item['link_title'], serialize($item['options']),
  1771.       $item['customized'], $item['updated']);
  1772.     $item['mlid'] = db_last_insert_id('menu_links''mlid');
  1773.   }
  1774.   if (!$item['plid']) {
  1775.     $item['p1'] = $item['mlid'];
  1776.     for ($i 2$i <= MENU_MAX_DEPTH$i++) {
  1777.       $item["p$i"] = 0;
  1778.     }
  1779.     $item['depth'] = 1;
  1780.   }
  1781.   else {
  1782.     // Cannot add beyond the maximum depth.
  1783.     if ($item['has_children'] && $existing_item) {
  1784.       $limit MENU_MAX_DEPTH menu_link_children_relative_depth($existing_item) - 1;
  1785.     }
  1786.     else {
  1787.       $limit MENU_MAX_DEPTH 1;
  1788.     }
  1789.     if ($parent['depth'] > $limit) {
  1790.       return FALSE;
  1791.     }
  1792.     $item['depth'] = $parent['depth'] + 1;
  1793.     _menu_link_parents_set($item$parent);
  1794.   }
  1795.   // Need to check both plid and menu_name, since plid can be 0 in any menu.
  1796.   if ($existing_item && ($item['plid'] != $existing_item['plid'] || $menu_name != $existing_item['menu_name'])) {
  1797.     _menu_link_move_children($item$existing_item);
  1798.   }
  1799.   // Find the callback. During the menu update we store empty paths to be
  1800.   // fixed later, so we skip this.
  1801.   if (!isset($_SESSION['system_update_6021']) && (empty($item['router_path'])  || !$existing_item || ($existing_item['link_path'] != $item['link_path']))) {
  1802.     if ($item['_external']) {
  1803.       $item['router_path'] = '';
  1804.     }
  1805.     else {
  1806.       // Find the router path which will serve this path.
  1807.       $item['parts'] = explode('/'$item['link_path'], MENU_MAX_PARTS);
  1808.       $item['router_path'] = _menu_find_router_path($menu$item['link_path']);
  1809.     }
  1810.   }
  1811.   db_query("UPDATE {menu_links} SET menu_name = '%s', plid = %d, link_path = '%s',
  1812.     router_path = '%s', hidden = %d, external = %d, has_children = %d,
  1813.     expanded = %d, weight = %d, depth = %d,
  1814.     p1 = %d, p2 = %d, p3 = %d, p4 = %d, p5 = %d, p6 = %d, p7 = %d, p8 = %d, p9 = %d,
  1815.     module = '%s', link_title = '%s', options = '%s', customized = %d WHERE mlid = %d",
  1816.     $item['menu_name'], $item['plid'], $item['link_path'],
  1817.     $item['router_path'], $item['hidden'], $item['_external'], $item['has_children'],
  1818.     $item['expanded'], $item['weight'],  $item['depth'],
  1819.     $item['p1'], $item['p2'], $item['p3'], $item['p4'], $item['p5'], $item['p6'], $item['p7'], $item['p8'], $item['p9'],
  1820.     $item['module'],  $item['link_title'], serialize($item['options']), $item['customized'], $item['mlid']);
  1821.   // Check the has_children status of the parent.
  1822.   _menu_update_parental_status($item);
  1823.   menu_cache_clear($menu_name);
  1824.   if ($existing_item && $menu_name != $existing_item['menu_name']) {
  1825.     menu_cache_clear($existing_item['menu_name']);
  1826.   }
  1827.   _menu_clear_page_cache();
  1828.   return $item['mlid'];
  1829. }
  1830. /**
  1831.  * Helper function to clear the page and block caches at most twice per page load.
  1832.  */
  1833. function _menu_clear_page_cache() {
  1834.   static $cache_cleared 0;
  1835.   // Clear the page and block caches, but at most twice, including at
  1836.   //  the end of the page load when there are multple links saved or deleted.
  1837.   if (empty($cache_cleared)) {
  1838.     cache_clear_all();
  1839.     // Keep track of which menus have expanded items.
  1840.     _menu_set_expanded_menus();
  1841.     $cache_cleared 1;
  1842.   }
  1843.   elseif ($cache_cleared == 1) {
  1844.     register_shutdown_function('cache_clear_all');
  1845.     // Keep track of which menus have expanded items.
  1846.     register_shutdown_function('_menu_set_expanded_menus');
  1847.     $cache_cleared 2;
  1848.   }
  1849. }
  1850. /**
  1851.  * Helper function to update a list of menus with expanded items
  1852.  */
  1853. function _menu_set_expanded_menus() {
  1854.   $names = array();
  1855.   $result db_query("SELECT menu_name FROM {menu_links} WHERE expanded != 0 GROUP BY menu_name");
  1856.   while ($n db_fetch_array($result)) {
  1857.     $names[] = $n['menu_name'];
  1858.   }
  1859.   variable_set('menu_expanded'$names);
  1860. }
  1861. /**
  1862.  * Find the router path which will serve this path.
  1863.  *
  1864.  * @param $menu
  1865.  *  The full built menu.
  1866.  * @param $link_path
  1867.  *  The path for we are looking up its router path.
  1868.  * @return
  1869.  *  A path from $menu keys or empty if $link_path points to a nonexisting
  1870.  *  place.
  1871.  */
  1872. function _menu_find_router_path($menu$link_path) {
  1873.   $parts explode('/'$link_pathMENU_MAX_PARTS);
  1874.   $router_path $link_path;
  1875.   if (!isset($menu[$router_path])) {
  1876.     list($ancestors) = menu_get_ancestors($parts);
  1877.     $ancestors[] = '';
  1878.     foreach ($ancestors as $key => $router_path) {
  1879.       if (isset($menu[$router_path])) {
  1880.         break;
  1881.       }
  1882.     }
  1883.   }
  1884.   return $router_path;
  1885. }
  1886. /**
  1887.  * Insert, update or delete an uncustomized menu link related to a module.
  1888.  *
  1889.  * @param $module
  1890.  *   The name of the module.
  1891.  * @param $op
  1892.  *   Operation to perform: insert, update or delete.
  1893.  * @param $link_path
  1894.  *   The path this link points to.
  1895.  * @param $link_title
  1896.  *   Title of the link to insert or new title to update the link to.
  1897.  *   Unused for delete.
  1898.  * @return
  1899.  *   The insert op returns the mlid of the new item. Others op return NULL.
  1900.  */
  1901. function menu_link_maintain($module$op$link_path$link_title) {
  1902.   switch ($op) {
  1903.     case 'insert':
  1904.       $menu_link = array(
  1905.         'link_title' => $link_title,
  1906.         'link_path' => $link_path,
  1907.         'module' => $module,
  1908.       );
  1909.       return menu_link_save($menu_link);
  1910.       break;
  1911.     case 'update':
  1912.       db_query("UPDATE {menu_links} SET link_title = '%s' WHERE link_path = '%s' AND customized = 0 AND module = '%s'"$link_title$link_path$module);
  1913.       menu_cache_clear();
  1914.       break;
  1915.     case 'delete':
  1916.       menu_link_delete(NULL$link_path);
  1917.       break;
  1918.   }
  1919. }
  1920. /**
  1921.  * Find the depth of an item's children relative to its depth.
  1922.  *
  1923.  * For example, if the item has a depth of 2, and the maximum of any child in
  1924.  * the menu link tree is 5, the relative depth is 3.
  1925.  *
  1926.  * @param $item
  1927.  *   An array representing a menu link item.
  1928.  * @return
  1929.  *   The relative depth, or zero.
  1930.  *
  1931.  */
  1932. function menu_link_children_relative_depth($item) {
  1933.   $i 1;
  1934.   $match '';
  1935.   $args[] = $item['menu_name'];
  1936.   $p 'p1';
  1937.   while ($i <= MENU_MAX_DEPTH && $item[$p]) {
  1938.     $match .= " AND $p = %d";
  1939.     $args[] = $item[$p];
  1940.     $p 'p'. ++$i;
  1941.   }
  1942.   $max_depth db_result(db_query_range("SELECT depth FROM {menu_links} WHERE menu_name = '%s'"$match ." ORDER BY depth DESC"$args01));
  1943.   return ($max_depth $item['depth']) ? $max_depth $item['depth'] : 0;
  1944. }
  1945. /**
  1946.  * Update the children of a menu link that's being moved.
  1947.  *
  1948.  * The menu name, parents (p1 - p6), and depth are updated for all children of
  1949.  * the link, and the has_children status of the previous parent is updated.
  1950.  */
  1951. function _menu_link_move_children($item$existing_item) {
  1952.   $args[] = $item['menu_name'];
  1953.   $set[] = "menu_name = '%s'";
  1954.   $i 1;
  1955.   while ($i <= $item['depth']) {
  1956.     $p 'p'$i++;
  1957.     $set[] = "$p = %d";
  1958.     $args[] = $item[$p];
  1959.   }
  1960.   $j $existing_item['depth'] + 1;
  1961.   while ($i <= MENU_MAX_DEPTH && $j <= MENU_MAX_DEPTH) {
  1962.     $set[] = 'p'$i++ .' = p'$j++;
  1963.   }
  1964.   while ($i <= MENU_MAX_DEPTH) {
  1965.     $set[] = 'p'$i++ .' = 0';
  1966.   }
  1967.   $shift $item['depth'] - $existing_item['depth'];
  1968.   if ($shift 0) {
  1969.     $args[] = -$shift;
  1970.     $set[] = 'depth = depth - %d';
  1971.   }
  1972.   elseif ($shift 0) {
  1973.     // The order of $set must be reversed so the new values don't overwrite the
  1974.     // old ones before they can be used because "Single-table UPDATE
  1975.     // assignments are generally evaluated from left to right"
  1976.     // see: http://dev.mysql.com/doc/refman/5.0/en/update.html
  1977.     $set array_reverse($set);
  1978.     $args array_reverse($args);
  1979.     $args[] = $shift;
  1980.     $set[] = 'depth = depth + %d';
  1981.   }
  1982.   $where[] = "menu_name = '%s'";
  1983.   $args[] = $existing_item['menu_name'];
  1984.   $p 'p1';
  1985.   for ($i 1$i <= MENU_MAX_DEPTH && $existing_item[$p]; $p 'p'. ++$i) {
  1986.     $where[] = "$p = %d";
  1987.     $args[] = $existing_item[$p];
  1988.   }
  1989.   db_query("UPDATE {menu_links} SET "implode(', '$set) ." WHERE "implode(' AND '$where), $args);
  1990.   // Check the has_children status of the parent, while excluding this item.
  1991.   _menu_update_parental_status($existing_itemTRUE);
  1992. }
  1993. /**
  1994.  * Check and update the has_children status for the parent of a link.
  1995.  */
  1996. function _menu_update_parental_status($item$exclude FALSE) {
  1997.   // If plid == 0, there is nothing to update.
  1998.   if ($item['plid']) {
  1999.     // We may want to exclude the passed link as a possible child.
  2000.     $where $exclude " AND mlid != %d" '';
  2001.     // Check if at least one visible child exists in the table.
  2002.     $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'], 01));
  2003.     db_query("UPDATE {menu_links} SET has_children = %d WHERE mlid = %d"$parent_has_children$item['plid']);
  2004.   }
  2005. }
  2006. /**
  2007.  * Helper function that sets the p1..p9 values for a menu link being saved.
  2008.  */
  2009. function _menu_link_parents_set(&$item$parent) {
  2010.   $i 1;
  2011.   while ($i $item['depth']) {
  2012.     $p 'p'$i++;
  2013.     $item[$p] = $parent[$p];
  2014.   }
  2015.   $p 'p'$i++;
  2016.   // The parent (p1 - p9) corresponding to the depth always equals the mlid.
  2017.   $item[$p] = $item['mlid'];
  2018.   while ($i <= MENU_MAX_DEPTH) {
  2019.     $p 'p'$i++;
  2020.     $item[$p] = 0;
  2021.   }
  2022. }
  2023. /**
  2024.  * Helper function to build the router table based on the data from hook_menu.
  2025.  */
  2026. function _menu_router_build($callbacks) {
  2027.   // First pass: separate callbacks from paths, making paths ready for
  2028.   // matching. Calculate fitness, and fill some default values.
  2029.   $menu = array();
  2030.   foreach ($callbacks as $path => $item) {
  2031.     $load_functions = array();
  2032.     $to_arg_functions = array();
  2033.     $fit 0;
  2034.     $move FALSE;
  2035.     $parts explode('/'$pathMENU_MAX_PARTS);
  2036.     $number_parts count($parts);
  2037.     // We store the highest index of parts here to save some work in the fit
  2038.     // calculation loop.
  2039.     $slashes $number_parts 1;
  2040.     // Extract load and to_arg functions.
  2041.     foreach ($parts as $k => $part) {
  2042.       $match FALSE;
  2043.       if (preg_match('/^%([a-z_]*)$/'$part$matches)) {
  2044.         if (empty($matches[1])) {
  2045.           $match TRUE;
  2046.           $load_functions[$k] = NULL;
  2047.         }
  2048.         else {
  2049.           if (function_exists($matches[1] .'_to_arg')) {
  2050.             $to_arg_functions[$k] = $matches[1] .'_to_arg';
  2051.             $load_functions[$k] = NULL;
  2052.             $match TRUE;
  2053.           }
  2054.           if (function_exists($matches[1] .'_load')) {
  2055.             $function $matches[1] .'_load';
  2056.             // Create an array of arguments that will be passed to the _load
  2057.             // function when this menu path is checked, if 'load arguments'
  2058.             // exists.
  2059.             $load_functions[$k] = isset($item['load arguments']) ? array($function => $item['load arguments']) : $function;
  2060.             $match TRUE;
  2061.           }
  2062.         }
  2063.       }
  2064.       if ($match) {
  2065.         $parts[$k] = '%';
  2066.       }
  2067.       else {
  2068.         $fit |=  << ($slashes $k);
  2069.       }
  2070.     }
  2071.     if ($fit) {
  2072.       $move TRUE;
  2073.     }
  2074.     else {
  2075.       // If there is no %, it fits maximally.
  2076.       $fit = (<< $number_parts) - 1;
  2077.     }
  2078.     $masks[$fit] = 1;
  2079.     $item['load_functions'] = empty($load_functions) ? '' serialize($load_functions);
  2080.     $item['to_arg_functions'] = empty($to_arg_functions) ? '' serialize($to_arg_functions);
  2081.     $item += array(
  2082.       'title' => '',
  2083.       'weight' => 0,
  2084.       'type' => MENU_NORMAL_ITEM,
  2085.       '_number_parts' => $number_parts,
  2086.       '_parts' => $parts,
  2087.       '_fit' => $fit,
  2088.     );
  2089.     $item += array(
  2090.       '_visible' => (bool)($item['type'] & MENU_VISIBLE_IN_BREADCRUMB),
  2091.       '_tab' => (bool)($item['type'] & MENU_IS_LOCAL_TASK),
  2092.     );
  2093.     if ($move) {
  2094.       $new_path implode('/'$item['_parts']);
  2095.       $menu[$new_path] = $item;
  2096.       $sort[$new_path] = $number_parts;
  2097.     }
  2098.     else {
  2099.       $menu[$path] = $item;
  2100.       $sort[$path] = $number_parts;
  2101.     }
  2102.   }
  2103.   array_multisort($sortSORT_NUMERIC$menu);
  2104.   // Apply inheritance rules.
  2105.   foreach ($menu as $path => $v) {
  2106.     $item = &$menu[$path];
  2107.     if (!$item['_tab']) {
  2108.       // Non-tab items.
  2109.       $item['tab_parent'] = '';
  2110.       $item['tab_root'] = $path;
  2111.     }
  2112.     for ($i $item['_number_parts'] - 1$i$i--) {
  2113.       $parent_path implode('/'array_slice($item['_parts'], 0$i));
  2114.       if (isset($menu[$parent_path])) {
  2115.         $parent $menu[$parent_path];
  2116.         if (!isset($item['tab_parent'])) {
  2117.           // Parent stores the parent of the path.
  2118.           $item['tab_parent'] = $parent_path;
  2119.         }
  2120.         if (!isset($item['tab_root']) && !$parent['_tab']) {
  2121.           $item['tab_root'] = $parent_path;
  2122.         }
  2123.         // If an access callback is not found for a default local task we use
  2124.         // the callback from the parent, since we expect them to be identical.
  2125.         // In all other cases, the access parameters must be specified.
  2126.         if (($item['type'] == MENU_DEFAULT_LOCAL_TASK) && !isset($item['access callback']) && isset($parent['access callback'])) {
  2127.           $item['access callback'] = $parent['access callback'];
  2128.           if (!isset($item['access arguments']) && isset($parent['access arguments'])) {
  2129.             $item['access arguments'] = $parent['access arguments'];
  2130.           }
  2131.         }
  2132.         // Same for page callbacks.
  2133.         if (!isset($item['page callback']) && isset($parent['page callback'])) {
  2134.           $item['page callback'] = $parent['page callback'];
  2135.           if (!isset($item['page arguments']) && isset($parent['page arguments'])) {
  2136.             $item['page arguments'] = $parent['page arguments'];
  2137.           }
  2138.           if (!isset($item['file']) && isset($parent['file'])) {
  2139.             $item['file'] = $parent['file'];
  2140.           }
  2141.           if (!isset($item['file path']) && isset($parent['file path'])) {
  2142.             $item['file path'] = $parent['file path'];
  2143.           }
  2144.         }
  2145.       }
  2146.     }
  2147.     if (!isset($item['access callback']) && isset($item['access arguments'])) {
  2148.       // Default callback.
  2149.       $item['access callback'] = 'user_access';
  2150.     }
  2151.     if (!isset($item['access callback']) || empty($item['page callback'])) {
  2152.       $item['access callback'] = 0;
  2153.     }
  2154.     if (is_bool($item['access callback'])) {
  2155.       $item['access callback'] = intval($item['access callback']);
  2156.     }
  2157.     $item += array(
  2158.       'access arguments' => array(),
  2159.       'access callback' => '',
  2160.       'page arguments' => array(),
  2161.       'page callback' => '',
  2162.       'block callback' => '',
  2163.       'title arguments' => array(),
  2164.       'title callback' => 't',
  2165.       'description' => '',
  2166.       'position' => '',
  2167.       'tab_parent' => '',
  2168.       'tab_root' => $path,
  2169.       'path' => $path,
  2170.       'file' => '',
  2171.       'file path' => '',
  2172.       'include file' => '',
  2173.     );
  2174.     // Calculate out the file to be included for each callback, if any.
  2175.     if ($item['file']) {
  2176.       $file_path $item['file path'] ? $item['file path'] : drupal_get_path('module'$item['module']);
  2177.       $item['include file'] = $file_path .'/'$item['file'];
  2178.     }
  2179.     $title_arguments $item['title arguments'] ? serialize($item['title arguments']) : '';
  2180.     db_query("INSERT INTO {menu_router}
  2181.       (path, load_functions, to_arg_functions, access_callback,
  2182.       access_arguments, page_callback, page_arguments, fit,
  2183.       number_parts, tab_parent, tab_root,
  2184.       title, title_callback, title_arguments,
  2185.       type, block_callback, description, position, weight, file)
  2186.       VALUES ('%s', '%s', '%s', '%s',
  2187.       '%s', '%s', '%s', %d,
  2188.       %d, '%s', '%s',
  2189.       '%s', '%s', '%s',
  2190.       %d, '%s', '%s', '%s', %d, '%s')",
  2191.       $path$item['load_functions'], $item['to_arg_functions'], $item['access callback'],
  2192.       serialize($item['access arguments']), $item['page callback'], serialize($item['page arguments']), $item['_fit'],
  2193.       $item['_number_parts'], $item['tab_parent'], $item['tab_root'],
  2194.       $item['title'], $item['title callback'], $title_arguments,
  2195.       $item['type'], $item['block callback'], $item['description'], $item['position'], $item['weight'], $item['include file']);
  2196.   }
  2197.   // Sort the masks so they are in order of descending fit, and store them.
  2198.   $masks array_keys($masks);
  2199.   rsort($masks);
  2200.   variable_set('menu_masks'$masks);
  2201.   return $menu;
  2202. }
  2203. /**
  2204.  * Returns TRUE if a path is external (e.g. http://example.com).
  2205.  */
  2206. function menu_path_is_external($path) {
  2207.   $colonpos strpos($path':');
  2208.   return $colonpos !== FALSE && !preg_match('![/?#]!'substr($path0$colonpos)) && filter_xss_bad_protocol($pathFALSE) == check_plain($path);
  2209. }
  2210. /**
  2211.  * Checks whether the site is off-line for maintenance.
  2212.  *
  2213.  * This function will log the current user out and redirect to front page
  2214.  * if the current user has no 'administer site configuration' permission.
  2215.  *
  2216.  * @return
  2217.  *   FALSE if the site is not off-line or its the login page or the user has
  2218.  *     'administer site configuration' permission.
  2219.  *   TRUE for anonymous users not on the login page if the site is off-line.
  2220.  */
  2221. function _menu_site_is_offline() {
  2222.   // Check if site is set to off-line mode.
  2223.   if (variable_get('site_offline'0)) {
  2224.     // Check if the user has administration privileges.
  2225.     if (user_access('administer site configuration')) {
  2226.       // Ensure that the off-line message is displayed only once [allowing for
  2227.       // page redirects], and specifically suppress its display on the site
  2228.       // maintenance page.
  2229.       if (drupal_get_normal_path($_GET['q']) != 'admin/settings/site-maintenance') {
  2230.         drupal_set_message(t('Operating in off-line mode.'), 'status'FALSE);
  2231.       }
  2232.     }
  2233.     else {
  2234.       // Anonymous users get a FALSE at the login prompt, TRUE otherwise.
  2235.       if (user_is_anonymous()) {
  2236.         return $_GET['q'] != 'user' && $_GET['q'] != 'user/login';
  2237.       }
  2238.       // Logged in users are unprivileged here, so they are logged out.
  2239.       require_once drupal_get_path('module''user') .'/user.pages.inc';
  2240.       user_logout();
  2241.     }
  2242.   }
  2243.   return FALSE;
  2244. }
  2245. /**
  2246.  * Validates the path of a menu link being created or edited.
  2247.  *
  2248.  * @return
  2249.  *   TRUE if it is a valid path AND the current user has access permission,
  2250.  *   FALSE otherwise.
  2251.  */
  2252. function menu_valid_path($form_item) {
  2253.   global $menu_admin;
  2254.   $item = array();
  2255.   $path $form_item['link_path'];
  2256.   // We indicate that a menu administrator is running the menu access check.
  2257.   $menu_admin TRUE;
  2258.   if ($path == '<front>' || menu_path_is_external($path)) {
  2259.     $item = array('access' => TRUE);
  2260.   }
  2261.   elseif (preg_match('/\/\%/'$path)) {
  2262.     // Path is dynamic (ie 'user/%'), so check directly against menu_router table.
  2263.     if ($item db_fetch_array(db_query("SELECT * FROM {menu_router} where path = '%s' "$path))) {
  2264.       $item['link_path']  = $form_item['link_path'];
  2265.       $item['link_title'] = $form_item['link_title'];
  2266.       $item['external']   = FALSE;
  2267.       $item['options'] = '';
  2268.       _menu_link_translate($item);
  2269.     }
  2270.   }
  2271.   else {
  2272.     $item menu_get_item($path);
  2273.   }
  2274.   $menu_admin FALSE;
  2275.   return $item && $item['access'];
  2276. }
  2277. /**
  2278.  * @} End of "defgroup menu".
  2279.  */