Skip navigation
Help

menu.inc

  1. drupal
    1. 6 drupal/includes/menu.inc
    2. 7 drupal/includes/menu.inc

API for the Drupal menu system.

Functions & methods

NameDescription
drupal_help_argGenerates elements for the $arg array in the help hook.
menu_build_treeBuild a menu tree, translate links, and check access.
menu_cache_clearClears the cached cached data for a single named menu.
menu_cache_clear_allClears all cached menu data. This should be called any time broad changes might have been made to the router items or menu links.
menu_contextual_linksRetrieve contextual links for a system object based on registered local tasks.
menu_delete_linksDeletes all links for a menu.
menu_execute_active_handlerExecute the page callback associated with the current path.
menu_get_active_breadcrumbGet the breadcrumb for the current page, as determined by the active trail.
menu_get_active_helpReturns the help associated with the active menu item.
menu_get_active_menu_namesGet the active menu for the current page - determines the active trail.
menu_get_active_titleGet the title of the current page, as determined by the active trail.
menu_get_active_trailGets the active trail (path to root menu root) of the current page.
menu_get_ancestorsReturns the ancestors (and relevant placeholders) for any given path.
menu_get_custom_themeGets the custom theme for the current page, if there is one.
menu_get_itemGet a router item.
menu_get_namesBuild a list of named menus.
menu_get_objectGet a loaded object from a router item.
menu_get_routerGet the menu router.
menu_links_cloneClone an array of menu links.
menu_link_children_relative_depthFind the depth of an item's children relative to its depth.
menu_link_deleteDelete one or several menu links.
menu_link_get_preferredLookup the preferred menu link for a given system path.
menu_link_loadGet a menu link by its mlid, access checked and link translated for rendering.
menu_link_maintainInsert, update or delete an uncustomized menu link related to a module.
menu_link_saveSaves a menu link.
menu_list_system_menusReturn an array containing the names of system-defined (default) menus.
menu_load_linksReturns an array containing all links for a menu.
menu_local_actionsReturns the rendered local actions at the current level.
menu_local_tabsReturns a renderable element for the primary and secondary tabs.
menu_local_tasksCollects the local tasks (tabs), action links, and the root path.
menu_main_menuReturn an array of links to be rendered as the Main menu.
menu_navigation_linksReturn an array of links for a navigation menu.
menu_primary_local_tasksReturns the rendered local tasks at the top level.
menu_rebuild(Re)populate the database tables used by various menu functions.
menu_reset_static_cacheResets the menu system static cache.
menu_router_buildCollect and alter the menu definitions.
menu_secondary_local_tasksReturns the rendered local tasks at the second level.
menu_secondary_menuReturn an array of links to be rendered as the Secondary links.
menu_set_active_itemSet the active path, which determines which page is loaded.
menu_set_active_menu_namesSet (or get) the active menu for the current page - determines the active trail.
menu_set_active_trailSets or gets the active trail (path to menu tree root) of the current page.
menu_set_custom_themeSets a custom theme for the current page, if there is one.
menu_set_itemReplaces the statically cached item for a given path.
menu_tab_root_pathReturns the router path, or the path of the parent tab of a default local task.
menu_tail_loadLoads path as one string from the argument we are currently at.
menu_tail_to_argReturns path as one string from the argument we are currently at.
menu_treeRenders a menu tree based on the current path.
menu_tree_all_dataGet the data structure representing a named menu tree.
menu_tree_check_accessCheck access and perform other dynamic operations for each link in the tree.
menu_tree_collect_node_linksRecursive helper function - collect node links.
menu_tree_dataBuild the data representing a menu tree.
menu_tree_outputReturns a rendered menu tree.
menu_tree_page_dataGet the data structure representing a named menu tree, based on the current page.
menu_unserializeUnserializes menu data, using a map to replace path elements.
template_preprocess_menu_treePreprocesses the rendered tree for theme_menu_tree().
theme_menu_linkReturns HTML for a menu link and submenu.
theme_menu_local_actionReturns HTML for a single local action link.
theme_menu_local_taskReturns HTML for a single local task link.
theme_menu_local_tasksReturns HTML for primary and secondary local tasks.
theme_menu_treeReturns HTML for a wrapper for a menu sub-tree.
_menu_build_treeBuild a menu tree.
_menu_check_accessCheck access to a menu item using the access callback
_menu_clear_page_cacheHelper function to clear the page and block caches at most twice per page load.
_menu_delete_itemHelper function for menu_link_delete; deletes a single menu link.
_menu_find_router_pathFind the router path which will serve this path.
_menu_item_localizeLocalize the router item title using t() or another callback.
_menu_link_buildBuilds a link from a router item.
_menu_link_find_parentFind a possible parent for a given menu link.
_menu_link_map_translateThis function translates the path elements in the map using any to_arg helper function. These functions take an argument and return an object. See http://drupal.org/node/109153 for more information.
_menu_link_move_childrenUpdate the children of a menu link that's being moved.
_menu_link_parents_setHelper function that sets the p1..p9 values for a menu link being saved.
_menu_link_translateThis function is similar to _menu_translate() but does link-specific preparation such as always calling to_arg functions
_menu_load_objectsLoads objects into the map as defined in the $item['load_functions'].
_menu_navigation_links_rebuildHelper function to build menu links for the items in the menu router.
_menu_router_buildHelper function to build the router table based on the data from hook_menu.
_menu_router_cacheHelper function to store the menu router if we have it in memory.
_menu_router_saveHelper function to save data from menu_router_build() to the router table.
_menu_set_expanded_menusHelper function to update a list of menus with expanded items
_menu_site_is_offlineChecks whether the site is in maintenance mode.
_menu_translateHandles dynamic path translation and menu access control.
_menu_tree_check_accessRecursive helper function for menu_tree_check_access()
_menu_tree_dataRecursive helper function to build the data representing a menu tree.
_menu_update_parental_statusCheck and update the has_children status for the parent of a link.

Constants

NameDescription
MENU_ACCESS_DENIEDInternal menu status code -- Menu item access is denied.
MENU_CALLBACKMenu type -- A hidden, internal callback, typically used for API calls.
MENU_CONTEXT_INLINEInternal menu flag: Local task should be displayed inline.
MENU_CONTEXT_NONEInternal menu flag: Invisible local task.
MENU_CONTEXT_PAGEInternal menu flag: Local task should be displayed in page context.
MENU_CREATED_BY_ADMINInternal menu flag -- menu item was created by administrator.
MENU_DEFAULT_LOCAL_TASKMenu type -- The "default" local task, which is initially active.
MENU_FOUNDInternal menu status code -- Menu item was found.
MENU_IS_LOCAL_ACTIONInternal menu flag -- menu item is a local action.
MENU_IS_LOCAL_TASKInternal menu flag -- menu item is a local task.
MENU_IS_ROOTInternal menu flag -- menu item is the root of the menu tree.
MENU_LINKS_TO_PARENTInternal menu flag -- menu item links back to its parent.
MENU_LOCAL_ACTIONMenu type -- An action specific to the parent, usually rendered as a link.
MENU_LOCAL_TASKMenu type -- A task specific to the parent item, usually rendered as a tab.
MENU_MAX_DEPTHThe maximum depth of a menu links tree - matches the number of p columns.
MENU_MAX_PARTSThe maximum number of path elements for a menu callback
MENU_MODIFIED_BY_ADMINInternal menu flag -- menu item can be modified by administrator.
MENU_NORMAL_ITEMMenu type -- A "normal" menu item that's shown in menu and breadcrumbs.
MENU_NOT_FOUNDInternal menu status code -- Menu item was not found.
MENU_SITE_OFFLINEInternal menu status code -- Menu item inaccessible because site is offline.
MENU_SITE_ONLINEInternal menu status code -- Everything is working fine.
MENU_SUGGESTED_ITEMMenu type -- A normal menu item, hidden until enabled by an administrator.
MENU_VISIBLE_IN_BREADCRUMBInternal menu flag -- menu item is visible in the breadcrumb.
MENU_VISIBLE_IN_TREEInternal menu flag -- menu item is visible in the menu tree.

File

drupal/includes/menu.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * API for the Drupal menu system.
  5. */
  6. /**
  7. * @defgroup menu Menu system
  8. * @{
  9. * Define the navigation menus, and route page requests to code based on URLs.
  10. *
  11. * The Drupal menu system drives both the navigation system from a user
  12. * perspective and the callback system that Drupal uses to respond to URLs
  13. * passed from the browser. For this reason, a good understanding of the
  14. * menu system is fundamental to the creation of complex modules. As a note,
  15. * this is related to, but separate from menu.module, which allows menus
  16. * (which in this context are hierarchical lists of links) to be customized from
  17. * the Drupal administrative interface.
  18. *
  19. * Drupal's menu system follows a simple hierarchy defined by paths.
  20. * Implementations of hook_menu() define menu items and assign them to
  21. * paths (which should be unique). The menu system aggregates these items
  22. * and determines the menu hierarchy from the paths. For example, if the
  23. * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
  24. * would form the structure:
  25. * - a
  26. * - a/b
  27. * - a/b/c/d
  28. * - a/b/h
  29. * - e
  30. * - f/g
  31. * Note that the number of elements in the path does not necessarily
  32. * determine the depth of the menu item in the tree.
  33. *
  34. * When responding to a page request, the menu system looks to see if the
  35. * path requested by the browser is registered as a menu item with a
  36. * callback. If not, the system searches up the menu tree for the most
  37. * complete match with a callback it can find. If the path a/b/i is
  38. * requested in the tree above, the callback for a/b would be used.
  39. *
  40. * The found callback function is called with any arguments specified
  41. * in the "page arguments" attribute of its menu item. The
  42. * attribute must be an array. After these arguments, any remaining
  43. * components of the path are appended as further arguments. In this
  44. * way, the callback for a/b above could respond to a request for
  45. * a/b/i differently than a request for a/b/j.
  46. *
  47. * For an illustration of this process, see page_example.module.
  48. *
  49. * Access to the callback functions is also protected by the menu system.
  50. * The "access callback" with an optional "access arguments" of each menu
  51. * item is called before the page callback proceeds. If this returns TRUE,
  52. * then access is granted; if FALSE, then access is denied. Default local task
  53. * menu items (see next paragraph) may omit this attribute to use the value
  54. * provided by the parent item.
  55. *
  56. * In the default Drupal interface, you will notice many links rendered as
  57. * tabs. These are known in the menu system as "local tasks", and they are
  58. * rendered as tabs by default, though other presentations are possible.
  59. * Local tasks function just as other menu items in most respects. It is
  60. * convention that the names of these tasks should be short verbs if
  61. * possible. In addition, a "default" local task should be provided for
  62. * each set. When visiting a local task's parent menu item, the default
  63. * local task will be rendered as if it is selected; this provides for a
  64. * normal tab user experience. This default task is special in that it
  65. * links not to its provided path, but to its parent item's path instead.
  66. * The default task's path is only used to place it appropriately in the
  67. * menu hierarchy.
  68. *
  69. * Everything described so far is stored in the menu_router table. The
  70. * menu_links table holds the visible menu links. By default these are
  71. * derived from the same hook_menu definitions, however you are free to
  72. * add more with menu_link_save().
  73. */
  74. /**
  75. * @defgroup menu_flags Menu flags
  76. * @{
  77. * Flags for use in the "type" attribute of menu items.
  78. */
  79. /**
  80. * Internal menu flag -- menu item is the root of the menu tree.
  81. */
  82. define('MENU_IS_ROOT', 0x0001);
  83. /**
  84. * Internal menu flag -- menu item is visible in the menu tree.
  85. */
  86. define('MENU_VISIBLE_IN_TREE', 0x0002);
  87. /**
  88. * Internal menu flag -- menu item is visible in the breadcrumb.
  89. */
  90. define('MENU_VISIBLE_IN_BREADCRUMB', 0x0004);
  91. /**
  92. * Internal menu flag -- menu item links back to its parent.
  93. */
  94. define('MENU_LINKS_TO_PARENT', 0x0008);
  95. /**
  96. * Internal menu flag -- menu item can be modified by administrator.
  97. */
  98. define('MENU_MODIFIED_BY_ADMIN', 0x0020);
  99. /**
  100. * Internal menu flag -- menu item was created by administrator.
  101. */
  102. define('MENU_CREATED_BY_ADMIN', 0x0040);
  103. /**
  104. * Internal menu flag -- menu item is a local task.
  105. */
  106. define('MENU_IS_LOCAL_TASK', 0x0080);
  107. /**
  108. * Internal menu flag -- menu item is a local action.
  109. */
  110. define('MENU_IS_LOCAL_ACTION', 0x0100);
  111. /**
  112. * @} End of "Menu flags".
  113. */
  114. /**
  115. * @defgroup menu_item_types Menu item types
  116. * @{
  117. * Definitions for various menu item types.
  118. *
  119. * Menu item definitions provide one of these constants, which are shortcuts for
  120. * combinations of @link menu_flags Menu flags @endlink.
  121. */
  122. /**
  123. * Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.
  124. *
  125. * Normal menu items show up in the menu tree and can be moved/hidden by
  126. * the administrator. Use this for most menu items. It is the default value if
  127. * no menu item type is specified.
  128. */
  129. define('MENU_NORMAL_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB);
  130. /**
  131. * Menu type -- A hidden, internal callback, typically used for API calls.
  132. *
  133. * Callbacks simply register a path so that the correct function is fired
  134. * when the URL is accessed. They do not appear in menus or breadcrumbs.
  135. */
  136. define('MENU_CALLBACK', 0x0000);
  137. /**
  138. * Menu type -- A normal menu item, hidden until enabled by an administrator.
  139. *
  140. * Modules may "suggest" menu items that the administrator may enable. They act
  141. * just as callbacks do until enabled, at which time they act like normal items.
  142. * Note for the value: 0x0010 was a flag which is no longer used, but this way
  143. * the values of MENU_CALLBACK and MENU_SUGGESTED_ITEM are separate.
  144. */
  145. define('MENU_SUGGESTED_ITEM', MENU_VISIBLE_IN_BREADCRUMB | 0x0010);
  146. /**
  147. * Menu type -- A task specific to the parent item, usually rendered as a tab.
  148. *
  149. * Local tasks are menu items that describe actions to be performed on their
  150. * parent item. An example is the path "node/52/edit", which performs the
  151. * "edit" task on "node/52".
  152. */
  153. define('MENU_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_VISIBLE_IN_BREADCRUMB);
  154. /**
  155. * Menu type -- The "default" local task, which is initially active.
  156. *
  157. * Every set of local tasks should provide one "default" task, that links to the
  158. * same path as its parent when clicked.
  159. */
  160. define('MENU_DEFAULT_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT | MENU_VISIBLE_IN_BREADCRUMB);
  161. /**
  162. * Menu type -- An action specific to the parent, usually rendered as a link.
  163. *
  164. * Local actions are menu items that describe actions on the parent item such
  165. * as adding a new user, taxonomy term, etc.
  166. */
  167. define('MENU_LOCAL_ACTION', MENU_IS_LOCAL_TASK | MENU_IS_LOCAL_ACTION | MENU_VISIBLE_IN_BREADCRUMB);
  168. /**
  169. * @} End of "Menu item types".
  170. */
  171. /**
  172. * @defgroup menu_context_types Menu context types
  173. * @{
  174. * Flags for use in the "context" attribute of menu router items.
  175. */
  176. /**
  177. * Internal menu flag: Invisible local task.
  178. *
  179. * This flag may be used for local tasks like "Delete", so custom modules and
  180. * themes can alter the default context and expose the task by altering menu.
  181. */
  182. define('MENU_CONTEXT_NONE', 0x0000);
  183. /**
  184. * Internal menu flag: Local task should be displayed in page context.
  185. */
  186. define('MENU_CONTEXT_PAGE', 0x0001);
  187. /**
  188. * Internal menu flag: Local task should be displayed inline.
  189. */
  190. define('MENU_CONTEXT_INLINE', 0x0002);
  191. /**
  192. * @} End of "Menu context types".
  193. */
  194. /**
  195. * @defgroup menu_status_codes Menu status codes
  196. * @{
  197. * Status codes for menu callbacks.
  198. */
  199. /**
  200. * Internal menu status code -- Menu item was found.
  201. */
  202. define('MENU_FOUND', 1);
  203. /**
  204. * Internal menu status code -- Menu item was not found.
  205. */
  206. define('MENU_NOT_FOUND', 2);
  207. /**
  208. * Internal menu status code -- Menu item access is denied.
  209. */
  210. define('MENU_ACCESS_DENIED', 3);
  211. /**
  212. * Internal menu status code -- Menu item inaccessible because site is offline.
  213. */
  214. define('MENU_SITE_OFFLINE', 4);
  215. /**
  216. * Internal menu status code -- Everything is working fine.
  217. */
  218. define('MENU_SITE_ONLINE', 5);
  219. /**
  220. * @} End of "Menu status codes".
  221. */
  222. /**
  223. * @defgroup menu_tree_parameters Menu tree parameters
  224. * @{
  225. * Parameters for a menu tree.
  226. */
  227. /**
  228. * The maximum number of path elements for a menu callback
  229. */
  230. define('MENU_MAX_PARTS', 9);
  231. /**
  232. * The maximum depth of a menu links tree - matches the number of p columns.
  233. */
  234. define('MENU_MAX_DEPTH', 9);
  235. /**
  236. * @} End of "Menu tree parameters".
  237. */
  238. /**
  239. * Returns the ancestors (and relevant placeholders) for any given path.
  240. *
  241. * For example, the ancestors of node/12345/edit are:
  242. * - node/12345/edit
  243. * - node/12345/%
  244. * - node/%/edit
  245. * - node/%/%
  246. * - node/12345
  247. * - node/%
  248. * - node
  249. *
  250. * To generate these, we will use binary numbers. Each bit represents a
  251. * part of the path. If the bit is 1, then it represents the original
  252. * value while 0 means wildcard. If the path is node/12/edit/foo
  253. * then the 1011 bitstring represents node/%/edit/foo where % means that
  254. * any argument matches that part. We limit ourselves to using binary
  255. * numbers that correspond the patterns of wildcards of router items that
  256. * actually exists. This list of 'masks' is built in menu_rebuild().
  257. *
  258. * @param $parts
  259. * An array of path parts, for the above example
  260. * array('node', '12345', 'edit').
  261. *
  262. * @return
  263. * An array which contains the ancestors and placeholders. Placeholders
  264. * simply contain as many '%s' as the ancestors.
  265. */
  266. function menu_get_ancestors($parts) {
  267. $number_parts = count($parts);
  268. $ancestors = array();
  269. $length = $number_parts - 1;
  270. $end = (1 << $number_parts) - 1;
  271. $masks = variable_get('menu_masks', array());
  272. // Only examine patterns that actually exist as router items (the masks).
  273. foreach ($masks as $i) {
  274. if ($i > $end) {
  275. // Only look at masks that are not longer than the path of interest.
  276. continue;
  277. }
  278. elseif ($i < (1 << $length)) {
  279. // We have exhausted the masks of a given length, so decrease the length.
  280. --$length;
  281. }
  282. $current = '';
  283. for ($j = $length; $j >= 0; $j--) {
  284. // Check the bit on the $j offset.
  285. if ($i & (1 << $j)) {
  286. // Bit one means the original value.
  287. $current .= $parts[$length - $j];
  288. }
  289. else {
  290. // Bit zero means means wildcard.
  291. $current .= '%';
  292. }
  293. // Unless we are at offset 0, add a slash.
  294. if ($j) {
  295. $current .= '/';
  296. }
  297. }
  298. $ancestors[] = $current;
  299. }
  300. return $ancestors;
  301. }
  302. /**
  303. * Unserializes menu data, using a map to replace path elements.
  304. *
  305. * The menu system stores various path-related information (such as the 'page
  306. * arguments' and 'access arguments' components of a menu item) in the database
  307. * using serialized arrays, where integer values in the arrays represent
  308. * arguments to be replaced by values from the path. This function first
  309. * unserializes such menu information arrays, and then does the path
  310. * replacement.
  311. *
  312. * The path replacement acts on each integer-valued element of the unserialized
  313. * menu data array ($data) using a map array ($map, which is typically an array
  314. * of path arguments) as a list of replacements. For instance, if there is an
  315. * element of $data whose value is the number 2, then it is replaced in $data
  316. * with $map[2]; non-integer values in $data are left alone.
  317. *
  318. * As an example, an unserialized $data array with elements ('node_load', 1)
  319. * represents instructions for calling the node_load() function. Specifically,
  320. * this instruction says to use the path component at index 1 as the input
  321. * parameter to node_load(). If the path is 'node/123', then $map will be the
  322. * array ('node', 123), and the returned array from this function will have
  323. * elements ('node_load', 123), since $map[1] is 123. This return value will
  324. * indicate specifically that node_load(123) is to be called to load the node
  325. * whose ID is 123 for this menu item.
  326. *
  327. * @param $data
  328. * A serialized array of menu data, as read from the database.
  329. * @param $map
  330. * A path argument array, used to replace integer values in $data; an integer
  331. * value N in $data will be replaced by value $map[N]. Typically, the $map
  332. * array is generated from a call to the arg() function.
  333. *
  334. * @return
  335. * The unserialized $data array, with path arguments replaced.
  336. */
  337. function menu_unserialize($data, $map) {
  338. if ($data = unserialize($data)) {
  339. foreach ($data as $k => $v) {
  340. if (is_int($v)) {
  341. $data[$k] = isset($map[$v]) ? $map[$v] : '';
  342. }
  343. }
  344. return $data;
  345. }
  346. else {
  347. return array();
  348. }
  349. }
  350. /**
  351. * Replaces the statically cached item for a given path.
  352. *
  353. * @param $path
  354. * The path.
  355. * @param $router_item
  356. * The router item. Usually you take a router entry from menu_get_item and
  357. * set it back either modified or to a different path. This lets you modify the
  358. * navigation block, the page title, the breadcrumb and the page help in one
  359. * call.
  360. */
  361. function menu_set_item($path, $router_item) {
  362. menu_get_item($path, $router_item);
  363. }
  364. /**
  365. * Get a router item.
  366. *
  367. * @param $path
  368. * The path, for example node/5. The function will find the corresponding
  369. * node/% item and return that.
  370. * @param $router_item
  371. * Internal use only.
  372. *
  373. * @return
  374. * The router item, an associate array corresponding to one row in the
  375. * menu_router table. The value of key map holds the loaded objects. The
  376. * value of key access is TRUE if the current user can access this page.
  377. * The values for key title, page_arguments, access_arguments, and
  378. * theme_arguments will be filled in based on the database values and the
  379. * objects loaded.
  380. */
  381. function menu_get_item($path = NULL, $router_item = NULL) {
  382. $router_items = &drupal_static(__FUNCTION__);
  383. if (!isset($path)) {
  384. $path = $_GET['q'];
  385. }
  386. if (isset($router_item)) {
  387. $router_items[$path] = $router_item;
  388. }
  389. if (!isset($router_items[$path])) {
  390. // Rebuild if we know it's needed, or if the menu masks are missing which
  391. // occurs rarely, likely due to a race condition of multiple rebuilds.
  392. if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
  393. menu_rebuild();
  394. }
  395. $original_map = arg(NULL, $path);
  396. // Since there is no limit to the length of $path, use a hash to keep it
  397. // short yet unique.
  398. $cid = 'menu_item:' . hash('sha256', $path);
  399. if ($cached = cache_get($cid, 'cache_menu')) {
  400. $router_item = $cached->data;
  401. }
  402. else {
  403. $parts = array_slice($original_map, 0, MENU_MAX_PARTS);
  404. $ancestors = menu_get_ancestors($parts);
  405. $router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();
  406. cache_set($cid, $router_item, 'cache_menu');
  407. }
  408. if ($router_item) {
  409. // Allow modules to alter the router item before it is translated and
  410. // checked for access.
  411. drupal_alter('menu_get_item', $router_item, $path, $original_map);
  412. $map = _menu_translate($router_item, $original_map);
  413. $router_item['original_map'] = $original_map;
  414. if ($map === FALSE) {
  415. $router_items[$path] = FALSE;
  416. return FALSE;
  417. }
  418. if ($router_item['access']) {
  419. $router_item['map'] = $map;
  420. $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
  421. $router_item['theme_arguments'] = array_merge(menu_unserialize($router_item['theme_arguments'], $map), array_slice($map, $router_item['number_parts']));
  422. }
  423. }
  424. $router_items[$path] = $router_item;
  425. }
  426. return $router_items[$path];
  427. }
  428. /**
  429. * Execute the page callback associated with the current path.
  430. *
  431. * @param $path
  432. * The drupal path whose handler is to be be executed. If set to NULL, then
  433. * the current path is used.
  434. * @param $deliver
  435. * (optional) A boolean to indicate whether the content should be sent to the
  436. * browser using the appropriate delivery callback (TRUE) or whether to return
  437. * the result to the caller (FALSE).
  438. */
  439. function menu_execute_active_handler($path = NULL, $deliver = TRUE) {
  440. // Check if site is offline.
  441. $page_callback_result = _menu_site_is_offline() ? MENU_SITE_OFFLINE : MENU_SITE_ONLINE;
  442. // Allow other modules to change the site status but not the path because that
  443. // would not change the global variable. hook_url_inbound_alter() can be used
  444. // to change the path. Code later will not use the $read_only_path variable.
  445. $read_only_path = !empty($path) ? $path : $_GET['q'];
  446. drupal_alter('menu_site_status', $page_callback_result, $read_only_path);
  447. // Only continue if the site status is not set.
  448. if ($page_callback_result == MENU_SITE_ONLINE) {
  449. if ($router_item = menu_get_item($path)) {
  450. if ($router_item['access']) {
  451. if ($router_item['include_file']) {
  452. require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
  453. }
  454. $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
  455. }
  456. else {
  457. $page_callback_result = MENU_ACCESS_DENIED;
  458. }
  459. }
  460. else {
  461. $page_callback_result = MENU_NOT_FOUND;
  462. }
  463. }
  464. // Deliver the result of the page callback to the browser, or if requested,
  465. // return it raw, so calling code can do more processing.
  466. if ($deliver) {
  467. $default_delivery_callback = (isset($router_item) && $router_item) ? $router_item['delivery_callback'] : NULL;
  468. drupal_deliver_page($page_callback_result, $default_delivery_callback);
  469. }
  470. else {
  471. return $page_callback_result;
  472. }
  473. }
  474. /**
  475. * Loads objects into the map as defined in the $item['load_functions'].
  476. *
  477. * @param $item
  478. * A menu router or menu link item
  479. * @param $map
  480. * An array of path arguments (ex: array('node', '5'))
  481. *
  482. * @return
  483. * Returns TRUE for success, FALSE if an object cannot be loaded.
  484. * Names of object loading functions are placed in $item['load_functions'].
  485. * Loaded objects are placed in $map[]; keys are the same as keys in the
  486. * $item['load_functions'] array.
  487. * $item['access'] is set to FALSE if an object cannot be loaded.
  488. */
  489. function _menu_load_objects(&$item, &$map) {
  490. if ($load_functions = $item['load_functions']) {
  491. // If someone calls this function twice, then unserialize will fail.
  492. if (!is_array($load_functions)) {
  493. $load_functions = unserialize($load_functions);
  494. }
  495. $path_map = $map;
  496. foreach ($load_functions as $index => $function) {
  497. if ($function) {
  498. $value = isset($path_map[$index]) ? $path_map[$index] : '';
  499. if (is_array($function)) {
  500. // Set up arguments for the load function. These were pulled from
  501. // 'load arguments' in the hook_menu() entry, but they need
  502. // some processing. In this case the $function is the key to the
  503. // load_function array, and the value is the list of arguments.
  504. list($function, $args) = each($function);
  505. $load_functions[$index] = $function;
  506. // Some arguments are placeholders for dynamic items to process.
  507. foreach ($args as $i => $arg) {
  508. if ($arg === '%index') {
  509. // Pass on argument index to the load function, so multiple
  510. // occurrences of the same placeholder can be identified.
  511. $args[$i] = $index;
  512. }
  513. if ($arg === '%map') {
  514. // Pass on menu map by reference. The accepting function must
  515. // also declare this as a reference if it wants to modify
  516. // the map.
  517. $args[$i] = &$map;
  518. }
  519. if (is_int($arg)) {
  520. $args[$i] = isset($path_map[$arg]) ? $path_map[$arg] : '';
  521. }
  522. }
  523. array_unshift($args, $value);
  524. $return = call_user_func_array($function, $args);
  525. }
  526. else {
  527. $return = $function($value);
  528. }
  529. // If callback returned an error or there is no callback, trigger 404.
  530. if ($return === FALSE) {
  531. $item['access'] = FALSE;
  532. $map = FALSE;
  533. return FALSE;
  534. }
  535. $map[$index] = $return;
  536. }
  537. }
  538. $item['load_functions'] = $load_functions;
  539. }
  540. return TRUE;
  541. }
  542. /**
  543. * Check access to a menu item using the access callback
  544. *
  545. * @param $item
  546. * A menu router or menu link item
  547. * @param $map
  548. * An array of path arguments (ex: array('node', '5'))
  549. *
  550. * @return
  551. * $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
  552. */
  553. function _menu_check_access(&$item, $map) {
  554. // Determine access callback, which will decide whether or not the current
  555. // user has access to this path.
  556. $callback = empty($item['access_callback']) ? 0 : trim($item['access_callback']);
  557. // Check for a TRUE or FALSE value.
  558. if (is_numeric($callback)) {
  559. $item['access'] = (bool) $callback;
  560. }
  561. else {
  562. $arguments = menu_unserialize($item['access_arguments'], $map);
  563. // As call_user_func_array is quite slow and user_access is a very common
  564. // callback, it is worth making a special case for it.
  565. if ($callback == 'user_access') {
  566. $item['access'] = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
  567. }
  568. elseif (function_exists($callback)) {
  569. $item['access'] = call_user_func_array($callback, $arguments);
  570. }
  571. }
  572. }
  573. /**
  574. * Localize the router item title using t() or another callback.
  575. *
  576. * Translate the title and description to allow storage of English title
  577. * strings in the database, yet display of them in the language required
  578. * by the current user.
  579. *
  580. * @param $item
  581. * A menu router item or a menu link item.
  582. * @param $map
  583. * The path as an array with objects already replaced. E.g., for path
  584. * node/123 $map would be array('node', $node) where $node is the node
  585. * object for node 123.
  586. * @param $link_translate
  587. * TRUE if we are translating a menu link item; FALSE if we are
  588. * translating a menu router item.
  589. *
  590. * @return
  591. * No return value.
  592. * $item['title'] is localized according to $item['title_callback'].
  593. * If an item's callback is check_plain(), $item['options']['html'] becomes
  594. * TRUE.
  595. * $item['description'] is translated using t().
  596. * When doing link translation and the $item['options']['attributes']['title']
  597. * (link title attribute) matches the description, it is translated as well.
  598. */
  599. function _menu_item_localize(&$item, $map, $link_translate = FALSE) {
  600. $callback = $item['title_callback'];
  601. $item['localized_options'] = $item['options'];
  602. // All 'class' attributes are assumed to be an array during rendering, but
  603. // links stored in the database may use an old string value.
  604. // @todo In order to remove this code we need to implement a database update
  605. // including unserializing all existing link options and running this code
  606. // on them, as well as adding validation to menu_link_save().
  607. if (isset($item['options']['attributes']['class']) && is_string($item['options']['attributes']['class'])) {
  608. $item['localized_options']['attributes']['class'] = explode(' ', $item['options']['attributes']['class']);
  609. }
  610. // If we are translating the title of a menu link, and its title is the same
  611. // as the corresponding router item, then we can use the title information
  612. // from the router. If it's customized, then we need to use the link title
  613. // itself; can't localize.
  614. // If we are translating a router item (tabs, page, breadcrumb), then we
  615. // can always use the information from the router item.
  616. if (!$link_translate || ($item['title'] == $item['link_title'])) {
  617. // t() is a special case. Since it is used very close to all the time,
  618. // we handle it directly instead of using indirect, slower methods.
  619. if ($callback == 't') {
  620. if (empty($item['title_arguments'])) {
  621. $item['title'] = t($item['title']);
  622. }
  623. else {
  624. $item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));
  625. }
  626. }
  627. elseif ($callback && function_exists($callback)) {
  628. if (empty($item['title_arguments'])) {
  629. $item['title'] = $callback($item['title']);
  630. }
  631. else {
  632. $item['title'] = call_user_func_array($callback, menu_unserialize($item['title_arguments'], $map));
  633. }
  634. // Avoid calling check_plain again on l() function.
  635. if ($callback == 'check_plain') {
  636. $item['localized_options']['html'] = TRUE;
  637. }
  638. }
  639. }
  640. elseif ($link_translate) {
  641. $item['title'] = $item['link_title'];
  642. }
  643. // Translate description, see the motivation above.
  644. if (!empty($item['description'])) {
  645. $original_description = $item['description'];
  646. $item['description'] = t($item['description']);
  647. if ($link_translate && isset($item['options']['attributes']['title']) && $item['options']['attributes']['title'] == $original_description) {
  648. $item['localized_options']['attributes']['title'] = $item['description'];
  649. }
  650. }
  651. }
  652. /**
  653. * Handles dynamic path translation and menu access control.
  654. *
  655. * When a user arrives on a page such as node/5, this function determines
  656. * what "5" corresponds to, by inspecting the page's menu path definition,
  657. * node/%node. This will call node_load(5) to load the corresponding node
  658. * object.
  659. *
  660. * It also works in reverse, to allow the display of tabs and menu items which
  661. * contain these dynamic arguments, translating node/%node to node/5.
  662. *
  663. * Translation of menu item titles and descriptions are done here to
  664. * allow for storage of English strings in the database, and translation
  665. * to the language required to generate the current page.
  666. *
  667. * @param $router_item
  668. * A menu router item
  669. * @param $map
  670. * An array of path arguments (ex: array('node', '5'))
  671. * @param $to_arg
  672. * Execute $item['to_arg_functions'] or not. Use only if you want to render a
  673. * path from the menu table, for example tabs.
  674. *
  675. * @return
  676. * Returns the map with objects loaded as defined in the
  677. * $item['load_functions']. $item['access'] becomes TRUE if the item is
  678. * accessible, FALSE otherwise. $item['href'] is set according to the map.
  679. * If an error occurs during calling the load_functions (like trying to load
  680. * a non existing node) then this function return FALSE.
  681. */
  682. function _menu_translate(&$router_item, $map, $to_arg = FALSE) {
  683. if ($to_arg && !empty($router_item['to_arg_functions'])) {
  684. // Fill in missing path elements, such as the current uid.
  685. _menu_link_map_translate($map, $router_item['to_arg_functions']);
  686. }
  687. // The $path_map saves the pieces of the path as strings, while elements in
  688. // $map may be replaced with loaded objects.
  689. $path_map = $map;
  690. if (!empty($router_item['load_functions']) && !_menu_load_objects($router_item, $map)) {
  691. // An error occurred loading an object.
  692. $router_item['access'] = FALSE;
  693. return FALSE;
  694. }
  695. // Generate the link path for the page request or local tasks.
  696. $link_map = explode('/', $router_item['path']);
  697. if (isset($router_item['tab_root'])) {
  698. $tab_root_map = explode('/', $router_item['tab_root']);
  699. }
  700. if (isset($router_item['tab_parent'])) {
  701. $tab_parent_map = explode('/', $router_item['tab_parent']);
  702. }
  703. for ($i = 0; $i < $router_item['number_parts']; $i++) {
  704. if ($link_map[$i] == '%') {
  705. $link_map[$i] = $path_map[$i];
  706. }
  707. if (isset($tab_root_map[$i]) && $tab_root_map[$i] == '%') {
  708. $tab_root_map[$i] = $path_map[$i];
  709. }
  710. if (isset($tab_parent_map[$i]) && $tab_parent_map[$i] == '%') {
  711. $tab_parent_map[$i] = $path_map[$i];
  712. }
  713. }
  714. $router_item['href'] = implode('/', $link_map);
  715. $router_item['tab_root_href'] = implode('/', $tab_root_map);
  716. $router_item['tab_parent_href'] = implode('/', $tab_parent_map);
  717. $router_item['options'] = array();
  718. _menu_check_access($router_item, $map);
  719. // For performance, don't localize an item the user can't access.
  720. if ($router_item['access']) {
  721. _menu_item_localize($router_item, $map);
  722. }
  723. return $map;
  724. }
  725. /**
  726. * This function translates the path elements in the map using any to_arg
  727. * helper function. These functions take an argument and return an object.
  728. * See http://drupal.org/node/109153 for more information.
  729. *
  730. * @param $map
  731. * An array of path arguments (ex: array('node', '5'))
  732. * @param $to_arg_functions
  733. * An array of helper function (ex: array(2 => 'menu_tail_to_arg'))
  734. */
  735. function _menu_link_map_translate(&$map, $to_arg_functions) {
  736. $to_arg_functions = unserialize($to_arg_functions);
  737. foreach ($to_arg_functions as $index => $function) {
  738. // Translate place-holders into real values.
  739. $arg = $function(!empty($map[$index]) ? $map[$index] : '', $map, $index);
  740. if (!empty($map[$index]) || isset($arg)) {
  741. $map[$index] = $arg;
  742. }
  743. else {
  744. unset($map[$index]);
  745. }
  746. }
  747. }
  748. /**
  749. * Returns path as one string from the argument we are currently at.
  750. */
  751. function menu_tail_to_arg($arg, $map, $index) {
  752. return implode('/', array_slice($map, $index));
  753. }
  754. /**
  755. * Loads path as one string from the argument we are currently at.
  756. *
  757. * To use this load function, you must specify the load arguments
  758. * in the router item as:
  759. * @code
  760. * $item['load arguments'] = array('%map', '%index');
  761. * @endcode
  762. *
  763. * @see search_menu().
  764. */
  765. function menu_tail_load($arg, &$map, $index) {
  766. $arg = implode('/', array_slice($map, $index));
  767. $map = array_slice($map, 0, $index);
  768. return $arg;
  769. }
  770. /**
  771. * This function is similar to _menu_translate() but does link-specific
  772. * preparation such as always calling to_arg functions
  773. *
  774. * @param $item
  775. * A menu link.
  776. * @param $translate
  777. * (optional) Whether to try to translate a link containing dynamic path
  778. * argument placeholders (%) based on the menu router item of the current
  779. * path. Defaults to FALSE. Internally used for breadcrumbs.
  780. *
  781. * @return
  782. * Returns the map of path arguments with objects loaded as defined in the
  783. * $item['load_functions'].
  784. * $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
  785. * $item['href'] is generated from link_path, possibly by to_arg functions.
  786. * $item['title'] is generated from link_title, and may be localized.
  787. * $item['options'] is unserialized; it is also changed within the call here
  788. * to $item['localized_options'] by _menu_item_localize().
  789. */
  790. function _menu_link_translate(&$item, $translate = FALSE) {
  791. if (!is_array($item['options'])) {
  792. $item['options'] = unserialize($item['options']);
  793. }
  794. if ($item['external']) {
  795. $item['access'] = 1;
  796. $map = array();
  797. $item['href'] = $item['link_path'];
  798. $item['title'] = $item['link_title'];
  799. $item['localized_options'] = $item['options'];
  800. }
  801. else {
  802. // Complete the path of the menu link with elements from the current path,
  803. // if it contains dynamic placeholders (%).
  804. $map = explode('/', $item['link_path']);
  805. if (strpos($item['link_path'], '%') !== FALSE) {
  806. // Invoke registered to_arg callbacks.
  807. if (!empty($item['to_arg_functions'])) {
  808. _menu_link_map_translate($map, $item['to_arg_functions']);
  809. }
  810. // Or try to derive the path argument map from the current router item,
  811. // if this $item's path is within the router item's path. This means
  812. // that if we are on the current path 'foo/%/bar/%/baz', then
  813. // menu_get_item() will have translated the menu router item for the
  814. // current path, and we can take over the argument map for a link like
  815. // 'foo/%/bar'. This inheritance is only valid for breadcrumb links.
  816. // @see _menu_tree_check_access()
  817. // @see menu_get_active_breadcrumb()
  818. elseif ($translate && ($current_router_item = menu_get_item())) {
  819. // If $translate is TRUE, then this link is in the active trail.
  820. // Only translate paths within the current path.
  821. if (strpos($current_router_item['path'], $item['link_path']) === 0) {
  822. $count = count($map);
  823. $map = array_slice($current_router_item['original_map'], 0, $count);
  824. $item['original_map'] = $map;
  825. if (isset($current_router_item['map'])) {
  826. $item['map'] = array_slice($current_router_item['map'], 0, $count);
  827. }
  828. // Reset access to check it (for the first time).
  829. unset($item['access']);
  830. }
  831. }
  832. }
  833. $item['href'] = implode('/', $map);
  834. // Skip links containing untranslated arguments.
  835. if (strpos($item['href'], '%') !== FALSE) {
  836. $item['access'] = FALSE;
  837. return FALSE;
  838. }
  839. // menu_tree_check_access() may set this ahead of time for links to nodes.
  840. if (!isset($item['access'])) {
  841. if (!empty($item['load_functions']) && !_menu_load_objects($item, $map)) {
  842. // An error occurred loading an object.
  843. $item['access'] = FALSE;
  844. return FALSE;
  845. }
  846. _menu_check_access($item, $map);
  847. }
  848. // For performance, don't localize a link the user can't access.
  849. if ($item['access']) {
  850. _menu_item_localize($item, $map, TRUE);
  851. }
  852. }
  853. // Allow other customizations - e.g. adding a page-specific query string to the
  854. // options array. For performance reasons we only invoke this hook if the link
  855. // has the 'alter' flag set in the options array.
  856. if (!empty($item['options']['alter'])) {
  857. drupal_alter('translated_menu_link', $item, $map);
  858. }
  859. return $map;
  860. }
  861. /**
  862. * Get a loaded object from a router item.
  863. *
  864. * menu_get_object() provides access to objects loaded by the current router
  865. * item. For example, on the page node/%node, the router loads the %node object,
  866. * and calling menu_get_object() will return that. Normally, it is necessary to
  867. * specify the type of object referenced, however node is the default.
  868. * The following example tests to see whether the node being displayed is of the
  869. * "story" content type:
  870. * @code
  871. * $node = menu_get_object();
  872. * $story = $node->type == 'story';
  873. * @endcode
  874. *
  875. * @param $type
  876. * Type of the object. These appear in hook_menu definitions as %type. Core
  877. * provides aggregator_feed, aggregator_category, contact, filter_format,
  878. * forum_term, menu, menu_link, node, taxonomy_vocabulary, user. See the
  879. * relevant {$type}_load function for more on each. Defaults to node.
  880. * @param $position
  881. * The position of the object in the path, where the first path segment is 0.
  882. * For node/%node, the position of %node is 1, but for comment/reply/%node,
  883. * it's 2. Defaults to 1.
  884. * @param $path
  885. * See menu_get_item() for more on this. Defaults to the current path.
  886. */
  887. function menu_get_object($type = 'node', $position = 1, $path = NULL) {
  888. $router_item = menu_get_item($path);
  889. if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type . '_load') {
  890. return $router_item['map'][$position];
  891. }
  892. }
  893. /**
  894. * Renders a menu tree based on the current path.
  895. *
  896. * The tree is expanded based on the current path and dynamic paths are also
  897. * changed according to the defined to_arg functions (for example the 'My
  898. * account' link is changed from user/% to a link with the current user's uid).
  899. *
  900. * @param $menu_name
  901. * The name of the menu.
  902. *
  903. * @return
  904. * A structured array representing the specified menu on the current page, to
  905. * be rendered by drupal_render().
  906. */
  907. function menu_tree($menu_name) {
  908. $menu_output = &drupal_static(__FUNCTION__, array());
  909. if (!isset($menu_output[$menu_name])) {
  910. $tree = menu_tree_page_data($menu_name);
  911. $menu_output[$menu_name] = menu_tree_output($tree);
  912. }
  913. return $menu_output[$menu_name];
  914. }
  915. /**
  916. * Returns a rendered menu tree.
  917. *
  918. * The menu item's LI element is given one of the following classes:
  919. * - expanded: The menu item is showing its submenu.
  920. * - collapsed: The menu item has a submenu which is not shown.
  921. * - leaf: The menu item has no submenu.
  922. *
  923. * @param $tree
  924. * A data structure representing the tree as returned from menu_tree_data.
  925. *
  926. * @return
  927. * A structured array to be rendered by drupal_render().
  928. */
  929. function menu_tree_output($tree) {
  930. $build = array();
  931. $items = array();
  932. // Pull out just the menu links we are going to render so that we
  933. // get an accurate count for the first/last classes.
  934. foreach ($tree as $data) {
  935. if ($data['link']['access'] && !$data['link']['hidden']) {
  936. $items[] = $data;
  937. }
  938. }
  939. $router_item = menu_get_item();
  940. $num_items = count($items);
  941. foreach ($items as $i => $data) {
  942. $class = array();
  943. if ($i == 0) {
  944. $class[] = 'first';
  945. }
  946. if ($i == $num_items - 1) {
  947. $class[] = 'last';
  948. }
  949. // Set a class for the <li>-tag. Since $data['below'] may contain local
  950. // tasks, only set 'expanded' class if the link also has children within
  951. // the current menu.
  952. if ($data['link']['has_children'] && $data['below']) {
  953. $class[] = 'expanded';
  954. }
  955. elseif ($data['link']['has_children']) {
  956. $class[] = 'collapsed';
  957. }
  958. else {
  959. $class[] = 'leaf';
  960. }
  961. // Set a class if the link is in the active trail.
  962. if ($data['link']['in_active_trail']) {
  963. $class[] = 'active-trail';
  964. $data['link']['localized_options']['attributes']['class'][] = 'active-trail';
  965. }
  966. // Normally, l() compares the href of every link with $_GET['q'] and sets
  967. // the active class accordingly. But local tasks do not appear in menu
  968. // trees, so if the current path is a local task, and this link is its
  969. // tab root, then we have to set the class manually.
  970. if ($data['link']['href'] == $router_item['tab_root_href'] && $data['link']['href'] != $_GET['q']) {
  971. $data['link']['localized_options']['attributes']['class'][] = 'active';
  972. }
  973. // Allow menu-specific theme overrides.
  974. $element['#theme'] = 'menu_link__' . strtr($data['link']['menu_name'], '-', '_');
  975. $element['#attributes']['class'] = $class;
  976. $element['#title'] = $data['link']['title'];
  977. $element['#href'] = $data['link']['href'];
  978. $element['#localized_options'] = !empty($data['link']['localized_options']) ? $data['link']['localized_options'] : array();
  979. $element['#below'] = $data['below'] ? menu_tree_output($data['below']) : $data['below'];
  980. $element['#original_link'] = $data['link'];
  981. // Index using the link's unique mlid.
  982. $build[$data['link']['mlid']] = $element;
  983. }
  984. if ($build) {
  985. // Make sure drupal_render() does not re-order the links.
  986. $build['#sorted'] = TRUE;
  987. // Add the theme wrapper for outer markup.
  988. // Allow menu-specific theme overrides.
  989. $build['#theme_wrappers'][] = 'menu_tree__' . strtr($data['link']['menu_name'], '-', '_');
  990. }
  991. return $build;
  992. }
  993. /**
  994. * Get the data structure representing a named menu tree.
  995. *
  996. * Since this can be the full tree including hidden items, the data returned
  997. * may be used for generating an an admin interface or a select.
  998. *
  999. * @param $menu_name
  1000. * The named menu links to return
  1001. * @param $link
  1002. * A fully loaded menu link, or NULL. If a link is supplied, only the
  1003. * path to root will be included in the returned tree - as if this link
  1004. * represented the current page in a visible menu.
  1005. * @param $max_depth
  1006. * Optional maximum depth of links to retrieve. Typically useful if only one
  1007. * or two levels of a sub tree are needed in conjunction with a non-NULL
  1008. * $link, in which case $max_depth should be greater than $link['depth'].
  1009. *
  1010. * @return
  1011. * An tree of menu links in an array, in the order they should be rendered.
  1012. */
  1013. function menu_tree_all_data($menu_name, $link = NULL, $max_depth = NULL) {
  1014. $tree = &drupal_static(__FUNCTION__, array());
  1015. // Use $mlid as a flag for whether the data being loaded is for the whole tree.
  1016. $mlid = isset($link['mlid']) ? $link['mlid'] : 0;
  1017. // Generate a cache ID (cid) specific for this $menu_name, $link, $language, and depth.
  1018. $cid = 'links:' . $menu_name . ':all:' . $mlid . ':' . $GLOBALS['language']->language . ':' . (int) $max_depth;
  1019. if (!isset($tree[$cid])) {
  1020. // If the static variable doesn't have the data, check {cache_menu}.
  1021. $cache = cache_get($cid, 'cache_menu');
  1022. if ($cache && isset($cache->data)) {
  1023. // If the cache entry exists, it contains the parameters for
  1024. // menu_build_tree().
  1025. $tree_parameters = $cache->data;
  1026. }
  1027. // If the tree data was not in the cache, build $tree_parameters.
  1028. if (!isset($tree_parameters)) {
  1029. $tree_parameters = array(
  1030. 'min_depth' => 1,
  1031. 'max_depth' => $max_depth,
  1032. );
  1033. if ($mlid) {
  1034. // The tree is for a single item, so we need to match the values in its
  1035. // p columns and 0 (the top level) with the plid values of other links.
  1036. $parents = array(0);
  1037. for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
  1038. if (!empty($link["p$i"])) {
  1039. $parents[] = $link["p$i"];
  1040. }
  1041. }
  1042. $tree_parameters['expanded'] = $parents;
  1043. $tree_parameters['active_trail'] = $parents;
  1044. $tree_parameters['active_trail'][] = $mlid;
  1045. }
  1046. // Cache the tree building parameters using the page-specific cid.
  1047. cache_set($cid, $tree_parameters, 'cache_menu');
  1048. }
  1049. // Build the tree using the parameters; the resulting tree will be cached
  1050. // by _menu_build_tree()).
  1051. $tree[$cid] = menu_build_tree($menu_name, $tree_parameters);
  1052. }
  1053. return $tree[$cid];
  1054. }
  1055. /**
  1056. * Get the data structure representing a named menu tree, based on the current page.
  1057. *
  1058. * The tree order is maintained by storing each parent in an individual
  1059. * field, see http://drupal.org/node/141866 for more.
  1060. *
  1061. * @param $menu_name
  1062. * The named menu links to return.
  1063. * @param $max_depth
  1064. * (optional) The maximum depth of links to retrieve.
  1065. * @param $only_active_trail
  1066. * (optional) Whether to only return the links in the active trail (TRUE)
  1067. * instead of all links on every level of the menu link tree (FALSE). Defaults
  1068. * to FALSE. Internally used for breadcrumbs only.
  1069. *
  1070. * @return
  1071. * An array of menu links, in the order they should be rendered. The array
  1072. * is a list of associative arrays -- these have two keys, link and below.
  1073. * link is a menu item, ready for theming as a link. Below represents the
  1074. * submenu below the link if there is one, and it is a subtree that has the
  1075. * same structure described for the top-level array.
  1076. */
  1077. function menu_tree_page_data($menu_name, $max_depth = NULL, $only_active_trail = FALSE) {
  1078. $tree = &drupal_static(__FUNCTION__, array());
  1079. // Load the menu item corresponding to the current page.
  1080. if ($item = menu_get_item()) {
  1081. if (isset($max_depth)) {
  1082. $max_depth = min($max_depth, MENU_MAX_DEPTH);
  1083. }
  1084. // Generate a cache ID (cid) specific for this page.
  1085. $cid = 'links:' . $menu_name . ':page:' . $item['href'] . ':' . $GLOBALS['language']->language . ':' . (int) $item['access'] . ':' . (int) $max_depth;
  1086. // If we are asked for the active trail only, and $menu_name has not been
  1087. // built and cached for this page yet, then this likely means that it
  1088. // won't be built anymore, as this function is invoked from
  1089. // template_process_page(). So in order to not build a giant menu tree
  1090. // that needs to be checked for access on all levels, we simply check
  1091. // whether we have the menu already in cache, or otherwise, build a minimum
  1092. // tree containing the breadcrumb/active trail only.
  1093. // @see menu_set_active_trail()
  1094. if (!isset($tree[$cid]) && $only_active_trail) {
  1095. $cid .= ':trail';
  1096. }
  1097. if (!isset($tree[$cid])) {
  1098. // If the static variable doesn't have the data, check {cache_menu}.
  1099. $cache = cache_get($cid, 'cache_menu');
  1100. if ($cache && isset($cache->data)) {
  1101. // If the cache entry exists, it contains the parameters for
  1102. // menu_build_tree().
  1103. $tree_parameters = $cache->data;
  1104. }
  1105. // If the tree data was not in the cache, build $tree_parameters.
  1106. if (!isset($tree_parameters)) {
  1107. $tree_parameters = array(
  1108. 'min_depth' => 1,
  1109. 'max_depth' => $max_depth,
  1110. );
  1111. // Parent mlids; used both as key and value to ensure uniqueness.
  1112. // We always want all the top-level links with plid == 0.
  1113. $active_trail = array(0 => 0);
  1114. // If the item for the current page is accessible, build the tree
  1115. // parameters accordingly.
  1116. if ($item['access']) {
  1117. // Find a menu link corresponding to the current path.
  1118. if ($active_link = menu_link_get_preferred()) {
  1119. // The active link may only be taken into account to build the
  1120. // active trail, if it resides in the requested menu. Otherwise,
  1121. // we'd needlessly re-run _menu_build_tree() queries for every menu
  1122. // on every page.
  1123. if ($active_link['menu_name'] == $menu_name) {
  1124. // Use all the coordinates, except the last one because there
  1125. // can be no child beyond the last column.
  1126. for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
  1127. if ($active_link['p' . $i]) {
  1128. $active_trail[$active_link['p' . $i]] = $active_link['p' . $i];
  1129. }
  1130. }
  1131. // If we are asked to build links for the active trail only, skip
  1132. // the entire 'expanded' handling.
  1133. if ($only_active_trail) {
  1134. $tree_parameters['only_active_trail'] = TRUE;
  1135. }
  1136. }
  1137. }
  1138. $parents = $active_trail;
  1139. $expanded = variable_get('menu_expanded', array());
  1140. // Check whether the current menu has any links set to be expanded.
  1141. if (!$only_active_trail && in_array($menu_name, $expanded)) {
  1142. // Collect all the links set to be expanded, and then add all of
  1143. // their children to the list as well.
  1144. do {
  1145. $result = db_select('menu_links', NULL, array('fetch' => PDO::FETCH_ASSOC))
  1146. ->fields('menu_links', array('mlid'))
  1147. ->condition('menu_name', $menu_name)
  1148. ->condition('expanded', 1)
  1149. ->condition('has_children', 1)
  1150. ->condition('plid', $parents, 'IN')
  1151. ->condition('mlid', $parents, 'NOT IN')
  1152. ->execute();
  1153. $num_rows = FALSE;
  1154. foreach ($result as $item) {
  1155. $parents[$item['mlid']] = $item['mlid'];
  1156. $num_rows = TRUE;
  1157. }
  1158. } while ($num_rows);
  1159. }
  1160. $tree_parameters['expanded'] = $parents;
  1161. $tree_parameters['active_trail'] = $active_trail;
  1162. }
  1163. // If access is denied, we only show top-level links in menus.
  1164. else {
  1165. $tree_parameters['expanded'] = $active_trail;
  1166. $tree_parameters['active_trail'] = $active_trail;
  1167. }
  1168. // Cache the tree building parameters using the page-specific cid.
  1169. cache_set($cid, $tree_parameters, 'cache_menu');
  1170. }
  1171. // Build the tree using the parameters; the resulting tree will be cached
  1172. // by _menu_build_tree().
  1173. $tree[$cid] = menu_build_tree($menu_name, $tree_parameters);
  1174. }
  1175. return $tree[$cid];
  1176. }
  1177. return array();
  1178. }
  1179. /**
  1180. * Build a menu tree, translate links, and check access.
  1181. *
  1182. * @param $menu_name
  1183. * The name of the menu.
  1184. * @param $parameters
  1185. * (optional) An associative array of build parameters. Possible keys:
  1186. * - expanded: An array of parent link ids to return only menu links that are
  1187. * children of one of the plids in this list. If empty, the whole menu tree
  1188. * is built, unless 'only_active_trail' is TRUE.
  1189. * - active_trail: An array of mlids, representing the coordinates of the
  1190. * currently active menu link.
  1191. * - only_active_trail: Whether to only return links that are in the active
  1192. * trail. This option is ignored, if 'expanded' is non-empty. Internally
  1193. * used for breadcrumbs.
  1194. * - min_depth: The minimum depth of menu links in the resulting tree.
  1195. * Defaults to 1, which is the default to build a whole tree for a menu, i.e.
  1196. * excluding menu container itself.
  1197. * - max_depth: The maximum depth of menu links in the resulting tree.
  1198. *
  1199. * @return
  1200. * A fully built menu tree.
  1201. */
  1202. function menu_build_tree($menu_name, array $parameters = array()) {
  1203. // Build the menu tree.
  1204. $data = _menu_build_tree($menu_name, $parameters);
  1205. // Check access for the current user to each item in the tree.
  1206. menu_tree_check_access($data['tree'], $data['node_links']);
  1207. return $data['tree'];
  1208. }
  1209. /**
  1210. * Build a menu tree.
  1211. *
  1212. * This function may be used build the data for a menu tree only, for example
  1213. * to further massage the data manually before further processing happens.
  1214. * menu_tree_check_access() needs to be invoked afterwards.
  1215. *
  1216. * @see menu_build_tree()
  1217. */
  1218. function _menu_build_tree($menu_name, array $parameters = array()) {
  1219. // Static cache of already built menu trees.
  1220. $trees = &drupal_static(__FUNCTION__, array());
  1221. // Build the cache id; sort parents to prevent duplicate storage and remove
  1222. // default parameter values.
  1223. if (isset($parameters['expanded'])) {
  1224. sort($parameters['expanded']);
  1225. }
  1226. $tree_cid = 'links:' . $menu_name . ':tree-data:' . $GLOBALS['language']->language . ':' . hash('sha256', serialize($parameters));
  1227. // If we do not have this tree in the static cache, check {cache_menu}.
  1228. if (!isset($trees[$tree_cid])) {
  1229. $cache = cache_get($tree_cid, 'cache_menu');
  1230. if ($cache && isset($cache->data)) {
  1231. $trees[$tree_cid] = $cache->data;
  1232. }
  1233. }
  1234. if (!isset($trees[$tree_cid])) {
  1235. // Select the links from the table, and recursively build the tree. We
  1236. // LEFT JOIN since there is no match in {menu_router} for an external
  1237. // link.
  1238. $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
  1239. $query->addTag('translatable');
  1240. $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
  1241. $query->fields('ml');
  1242. $query->fields('m', array(
  1243. 'load_functions',
  1244. 'to_arg_functions',
  1245. 'access_callback',
  1246. 'access_arguments',
  1247. 'page_callback',
  1248. 'page_arguments',
  1249. 'delivery_callback',
  1250. 'tab_parent',
  1251. 'tab_root',
  1252. 'title',
  1253. 'title_callback',
  1254. 'title_arguments',
  1255. 'theme_callback',
  1256. 'theme_arguments',
  1257. 'type',
  1258. 'description',
  1259. ));
  1260. for ($i = 1; $i <= MENU_MAX_DEPTH; $i++) {
  1261. $query->orderBy('p' . $i, 'ASC');
  1262. }
  1263. $query->condition('ml.menu_name', $menu_name);
  1264. if (!empty($parameters['expanded'])) {
  1265. $query->condition('ml.plid', $parameters['expanded'], 'IN');
  1266. }
  1267. elseif (!empty($parameters['only_active_trail'])) {
  1268. $query->condition('ml.mlid', $parameters['active_trail'], 'IN');
  1269. }
  1270. $min_depth = (isset($parameters['min_depth']) ? $parameters['min_depth'] : 1);
  1271. if ($min_depth != 1) {
  1272. $query->condition('ml.depth', $min_depth, '>=');
  1273. }
  1274. if (isset($parameters['max_depth'])) {
  1275. $query->condition('ml.depth', $parameters['max_depth'], '<=');
  1276. }
  1277. // Build an ordered array of links using the query result object.
  1278. $links = array();
  1279. foreach ($query->execute() as $item) {
  1280. $links[] = $item;
  1281. }
  1282. $active_trail = (isset($parameters['active_trail']) ? $parameters['active_trail'] : array());
  1283. $data['tree'] = menu_tree_data($links, $active_trail, $min_depth);
  1284. $data['node_links'] = array();
  1285. menu_tree_collect_node_links($data['tree'], $data['node_links']);
  1286. // Cache the data, if it is not already in the cache.
  1287. cache_set($tree_cid, $data, 'cache_menu');
  1288. $trees[$tree_cid] = $data;
  1289. }
  1290. return $trees[$tree_cid];
  1291. }
  1292. /**
  1293. * Recursive helper function - collect node links.
  1294. *
  1295. * @param $tree
  1296. * The menu tree you wish to collect node links from.
  1297. * @param $node_links
  1298. * An array in which to store the collected node links.
  1299. */
  1300. function menu_tree_collect_node_links(&$tree, &$node_links) {
  1301. foreach ($tree as $key => $v) {
  1302. if ($tree[$key]['link']['router_path'] == 'node/%') {
  1303. $nid = substr($tree[$key]['link']['link_path'], 5);
  1304. if (is_numeric($nid)) {
  1305. $node_links[$nid][$tree[$key]['link']['mlid']] = &$tree[$key]['link'];
  1306. $tree[$key]['link']['access'] = FALSE;
  1307. }
  1308. }
  1309. if ($tree[$key]['below']) {
  1310. menu_tree_collect_node_links($tree[$key]['below'], $node_links);
  1311. }
  1312. }
  1313. }
  1314. /**
  1315. * Check access and perform other dynamic operations for each link in the tree.
  1316. *
  1317. * @param $tree
  1318. * The menu tree you wish to operate on.
  1319. * @param $node_links
  1320. * A collection of node link references generated from $tree by
  1321. * menu_tree_collect_node_links().
  1322. */
  1323. function menu_tree_check_access(&$tree, $node_links = array()) {
  1324. if ($node_links) {
  1325. $nids = array_keys($node_links);
  1326. $select = db_select('node', 'n');
  1327. $select->addField('n', 'nid');
  1328. $select->condition('n.status', 1);
  1329. $select->condition('n.nid', $nids, 'IN');
  1330. $select->addTag('node_access');
  1331. $nids = $select->execute()->fetchCol();
  1332. foreach ($nids as $nid) {
  1333. foreach ($node_links[$nid] as $mlid => $link) {
  1334. $node_links[$nid][$mlid]['access'] = TRUE;
  1335. }
  1336. }
  1337. }
  1338. _menu_tree_check_access($tree);
  1339. }
  1340. /**
  1341. * Recursive helper function for menu_tree_check_access()
  1342. */
  1343. function _menu_tree_check_access(&$tree) {
  1344. $new_tree = array();
  1345. foreach ($tree as $key => $v) {
  1346. $item = &$tree[$key]['link'];
  1347. _menu_link_translate($item);
  1348. if ($item['access'] || ($item['in_active_trail'] && strpos($item['href'], '%') !== FALSE)) {
  1349. if ($tree[$key]['below']) {
  1350. _menu_tree_check_access($tree[$key]['below']);
  1351. }
  1352. // The weights are made a uniform 5 digits by adding 50000 as an offset.
  1353. // After _menu_link_translate(), $item['title'] has the localized link title.
  1354. // Adding the mlid to the end of the index insures that it is unique.
  1355. $new_tree[(50000 + $item['weight']) . ' ' . $item['title'] . ' ' . $item['mlid']] = $tree[$key];
  1356. }
  1357. }
  1358. // Sort siblings in the tree based on the weights and localized titles.
  1359. ksort($new_tree);
  1360. $tree = $new_tree;
  1361. }
  1362. /**
  1363. * Build the data representing a menu tree.
  1364. *
  1365. * @param $links
  1366. * An array of links (associative arrays) ordered by p1..p9.
  1367. * @param $parents
  1368. * An array of the plid values that represent the path from the current page
  1369. * to the root of the menu tree.
  1370. * @param $depth
  1371. * The minimum depth of any link in the $links array.
  1372. *
  1373. * @return
  1374. * See menu_tree_page_data for a description of the data structure.
  1375. */
  1376. function menu_tree_data(array $links, array $parents = array(), $depth = 1) {
  1377. // Reverse the array so we can use the more efficient array_pop() function.
  1378. $links = array_reverse($links);
  1379. return _menu_tree_data($links, $parents, $depth);
  1380. }
  1381. /**
  1382. * Recursive helper function to build the data representing a menu tree.
  1383. *
  1384. * The function is a bit complex because the rendering of a link depends on
  1385. * the next menu link.
  1386. */
  1387. function _menu_tree_data(&$links, $parents, $depth) {
  1388. $tree = array();
  1389. while ($item = array_pop($links)) {
  1390. // We need to determine if we're on the path to root so we can later build
  1391. // the correct active trail and breadcrumb.
  1392. $item['in_active_trail'] = in_array($item['mlid'], $parents);
  1393. // Add the current link to the tree.
  1394. $tree[$item['mlid']] = array(
  1395. 'link' => $item,
  1396. 'below' => array(),
  1397. );
  1398. // Look ahead to the next link, but leave it on the array so it's available
  1399. // to other recursive function calls if we return or build a sub-tree.
  1400. $next = end($links);
  1401. // Check whether the next link is the first in a new sub-tree.
  1402. if ($next && $next['depth'] > $depth) {
  1403. // Recursively call _menu_tree_data to build the sub-tree.
  1404. $tree[$item['mlid']]['below'] = _menu_tree_data($links, $parents, $next['depth']);
  1405. // Fetch next link after filling the sub-tree.
  1406. $next = end($links);
  1407. }
  1408. // Determine if we should exit the loop and return.
  1409. if (!$next || $next['depth'] < $depth) {
  1410. break;
  1411. }
  1412. }
  1413. return $tree;
  1414. }
  1415. /**
  1416. * Preprocesses the rendered tree for theme_menu_tree().
  1417. */
  1418. function template_preprocess_menu_tree(&$variables) {
  1419. $variables['tree'] = $variables['tree']['#children'];
  1420. }
  1421. /**
  1422. * Returns HTML for a wrapper for a menu sub-tree.
  1423. *
  1424. * @param $variables
  1425. * An associative array containing:
  1426. * - tree: An HTML string containing the tree's items.
  1427. *
  1428. * @see template_preprocess_menu_tree()
  1429. * @ingroup themeable
  1430. */
  1431. function theme_menu_tree($variables) {
  1432. return '<ul class="menu">' . $variables['tree'] . '</ul>';
  1433. }
  1434. /**
  1435. * Returns HTML for a menu link and submenu.
  1436. *
  1437. * @param $variables
  1438. * An associative array containing:
  1439. * - element: Structured array data for a menu link.
  1440. *
  1441. * @ingroup themeable
  1442. */
  1443. function theme_menu_link(array $variables) {
  1444. $element = $variables['element'];
  1445. $sub_menu = '';
  1446. if ($element['#below']) {
  1447. $sub_menu = drupal_render($element['#below']);
  1448. }
  1449. $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  1450. return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
  1451. }
  1452. /**
  1453. * Returns HTML for a single local task link.
  1454. *
  1455. * @param $variables
  1456. * An associative array containing:
  1457. * - element: A render element containing:
  1458. * - #link: A menu link array with 'title', 'href', and 'localized_options'
  1459. * keys.
  1460. * - #active: A boolean indicating whether the local task is active.
  1461. *
  1462. * @ingroup themeable
  1463. */
  1464. function theme_menu_local_task($variables) {
  1465. $link = $variables['element']['#link'];
  1466. $link_text = $link['title'];
  1467. if (!empty($variables['element']['#active'])) {
  1468. // Add text to indicate active tab for non-visual users.
  1469. $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';
  1470. // If the link does not contain HTML already, check_plain() it now.
  1471. // After we set 'html'=TRUE the link will not be sanitized by l().
  1472. if (empty($link['localized_options']['html'])) {
  1473. $link['title'] = check_plain($link['title']);
  1474. }
  1475. $link['localized_options']['html'] = TRUE;
  1476. $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  1477. }
  1478. return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
  1479. }
  1480. /**
  1481. * Returns HTML for a single local action link.
  1482. *
  1483. * @param $variables
  1484. * An associative array containing:
  1485. * - element: A render element containing:
  1486. * - #link: A menu link array with 'title', 'href', and 'localized_options'
  1487. * keys.
  1488. *
  1489. * @ingroup themeable
  1490. */
  1491. function theme_menu_local_action($variables) {
  1492. $link = $variables['element']['#link'];
  1493. $output = '<li>';
  1494. if (isset($link['href'])) {
  1495. $output .= l($link['title'], $link['href'], isset($link['localized_options']) ? $link['localized_options'] : array());
  1496. }
  1497. elseif (!empty($link['localized_options']['html'])) {
  1498. $output .= $link['title'];
  1499. }
  1500. else {
  1501. $output .= check_plain($link['title']);
  1502. }
  1503. $output .= "</li>\n";
  1504. return $output;
  1505. }
  1506. /**
  1507. * Generates elements for the $arg array in the help hook.
  1508. */
  1509. function drupal_help_arg($arg = array()) {
  1510. // Note - the number of empty elements should be > MENU_MAX_PARTS.
  1511. return $arg + array('', '', '', '', '', '', '', '', '', '', '', '');
  1512. }
  1513. /**
  1514. * Returns the help associated with the active menu item.
  1515. */
  1516. function menu_get_active_help() {
  1517. $output = '';
  1518. $router_path = menu_tab_root_path();
  1519. // We will always have a path unless we are on a 403 or 404.
  1520. if (!$router_path) {
  1521. return '';
  1522. }
  1523. $arg = drupal_help_arg(arg(NULL));
  1524. foreach (module_implements('help') as $module) {
  1525. $function = $module . '_help';
  1526. // Lookup help for this path.
  1527. if ($help = $function($router_path, $arg)) {
  1528. $output .= $help . "\n";
  1529. }
  1530. }
  1531. return $output;
  1532. }
  1533. /**
  1534. * Gets the custom theme for the current page, if there is one.
  1535. *
  1536. * @param $initialize
  1537. * This parameter should only be used internally; it is set to TRUE in order
  1538. * to force the custom theme to be initialized for the current page request.
  1539. *
  1540. * @return
  1541. * The machine-readable name of the custom theme, if there is one.
  1542. *
  1543. * @see menu_set_custom_theme()
  1544. */
  1545. function menu_get_custom_theme($initialize = FALSE) {
  1546. $custom_theme = &drupal_static(__FUNCTION__);
  1547. // Skip this if the site is offline or being installed or updated, since the
  1548. // menu system may not be correctly initialized then.
  1549. if ($initialize && !_menu_site_is_offline(TRUE) && (!defined('MAINTENANCE_MODE') || (MAINTENANCE_MODE != 'update' && MAINTENANCE_MODE != 'install'))) {
  1550. // First allow modules to dynamically set a custom theme for the current
  1551. // page. Since we can only have one, the last module to return a valid
  1552. // theme takes precedence.
  1553. $custom_themes = array_filter(module_invoke_all('custom_theme'), 'drupal_theme_access');
  1554. if (!empty($custom_themes)) {
  1555. $custom_theme = array_pop($custom_themes);
  1556. }
  1557. // If there is a theme callback function for the current page, execute it.
  1558. // If this returns a valid theme, it will override any theme that was set
  1559. // by a hook_custom_theme() implementation above.
  1560. $router_item = menu_get_item();
  1561. if (!empty($router_item['access']) && !empty($router_item['theme_callback']) && function_exists($router_item['theme_callback'])) {
  1562. $theme_name = call_user_func_array($router_item['theme_callback'], $router_item['theme_arguments']);
  1563. if (drupal_theme_access($theme_name)) {
  1564. $custom_theme = $theme_name;
  1565. }
  1566. }
  1567. }
  1568. return $custom_theme;
  1569. }
  1570. /**
  1571. * Sets a custom theme for the current page, if there is one.
  1572. */
  1573. function menu_set_custom_theme() {
  1574. menu_get_custom_theme(TRUE);
  1575. }
  1576. /**
  1577. * Build a list of named menus.
  1578. */
  1579. function menu_get_names() {
  1580. $names = &drupal_static(__FUNCTION__);
  1581. if (empty($names)) {
  1582. $names = db_select('menu_links')
  1583. ->distinct()
  1584. ->fields('menu_links', array('menu_name'))
  1585. ->orderBy('menu_name')
  1586. ->execute()->fetchCol();
  1587. }
  1588. return $names;
  1589. }
  1590. /**
  1591. * Return an array containing the names of system-defined (default) menus.
  1592. */
  1593. function menu_list_system_menus() {
  1594. return array(
  1595. 'navigation' => 'Navigation',
  1596. 'management' => 'Management',
  1597. 'user-menu' => 'User menu',
  1598. 'main-menu' => 'Main menu',
  1599. );
  1600. }
  1601. /**
  1602. * Return an array of links to be rendered as the Main menu.
  1603. */
  1604. function menu_main_menu() {
  1605. return menu_navigation_links(variable_get('menu_main_links_source', 'main-menu'));
  1606. }
  1607. /**
  1608. * Return an array of links to be rendered as the Secondary links.
  1609. */
  1610. function menu_secondary_menu() {
  1611. // If the secondary menu source is set as the primary menu, we display the
  1612. // second level of the primary menu.
  1613. if (variable_get('menu_secondary_links_source', 'user-menu') == variable_get('menu_main_links_source', 'main-menu')) {
  1614. return menu_navigation_links(variable_get('menu_main_links_source', 'main-menu'), 1);
  1615. }
  1616. else {
  1617. return menu_navigation_links(variable_get('menu_secondary_links_source', 'user-menu'), 0);
  1618. }
  1619. }
  1620. /**
  1621. * Return an array of links for a navigation menu.
  1622. *
  1623. * @param $menu_name
  1624. * The name of the menu.
  1625. * @param $level
  1626. * Optional, the depth of the menu to be returned.
  1627. *
  1628. * @return
  1629. * An array of links of the specified menu and level.
  1630. */
  1631. function menu_navigation_links($menu_name, $level = 0) {
  1632. // Don't even bother querying the menu table if no menu is specified.
  1633. if (empty($menu_name)) {
  1634. return array();
  1635. }
  1636. // Get the menu hierarchy for the current page.
  1637. $tree = menu_tree_page_data($menu_name, $level + 1);
  1638. // Go down the active trail until the right level is reached.
  1639. while ($level-- > 0 && $tree) {
  1640. // Loop through the current level's items until we find one that is in trail.
  1641. while ($item = array_shift($tree)) {
  1642. if ($item['link']['in_active_trail']) {
  1643. // If the item is in the active trail, we continue in the subtree.
  1644. $tree = empty($item['below']) ? array() : $item['below'];
  1645. break;
  1646. }
  1647. }
  1648. }
  1649. // Create a single level of links.
  1650. $router_item = menu_get_item();
  1651. $links = array();
  1652. foreach ($tree as $item) {
  1653. if (!$item['link']['hidden']) {
  1654. $class = '';
  1655. $l = $item['link']['localized_options'];
  1656. $l['href'] = $item['link']['href'];
  1657. $l['title'] = $item['link']['title'];
  1658. if ($item['link']['in_active_trail']) {
  1659. $class = ' active-trail';
  1660. $l['attributes']['class'][] = 'active-trail';
  1661. }
  1662. // Normally, l() compares the href of every link with $_GET['q'] and sets
  1663. // the active class accordingly. But local tasks do not appear in menu
  1664. // trees, so if the current path is a local task, and this link is its
  1665. // tab root, then we have to set the class manually.
  1666. if ($item['link']['href'] == $router_item['tab_root_href'] && $item['link']['href'] != $_GET['q']) {
  1667. $l['attributes']['class'][] = 'active';
  1668. }
  1669. // Keyed with the unique mlid to generate classes in theme_links().
  1670. $links['menu-' . $item['link']['mlid'] . $class] = $l;
  1671. }
  1672. }
  1673. return $links;
  1674. }
  1675. /**
  1676. * Collects the local tasks (tabs), action links, and the root path.
  1677. *
  1678. * @param $level
  1679. * The level of tasks you ask for. Primary tasks are 0, secondary are 1.
  1680. *
  1681. * @return
  1682. * An array containing
  1683. * - tabs: Local tasks for the requested level:
  1684. * - count: The number of local tasks.
  1685. * - output: The themed output of local tasks.
  1686. * - actions: Action links for the requested level:
  1687. * - count: The number of action links.
  1688. * - output: The themed output of action links.
  1689. * - root_path: The router path for the current page. If the current page is
  1690. * a default local task, then this corresponds to the parent tab.
  1691. */
  1692. function menu_local_tasks($level = 0) {
  1693. $data = &drupal_static(__FUNCTION__);
  1694. $root_path = &drupal_static(__FUNCTION__ . ':root_path', '');
  1695. $empty = array(
  1696. 'tabs' => array('count' => 0, 'output' => array()),
  1697. 'actions' => array('count' => 0, 'output' => array()),
  1698. 'root_path' => &$root_path,
  1699. );
  1700. if (!isset($data)) {
  1701. $data = array();
  1702. // Set defaults in case there are no actions or tabs.
  1703. $actions = $empty['actions'];
  1704. $tabs = array();
  1705. $router_item = menu_get_item();
  1706. // If this router item points to its parent, start from the parents to
  1707. // compute tabs and actions.
  1708. if ($router_item && ($router_item['type'] & MENU_LINKS_TO_PARENT)) {
  1709. $router_item = menu_get_item($router_item['tab_parent_href']);
  1710. }
  1711. // If we failed to fetch a router item or the current user doesn't have
  1712. // access to it, don't bother computing the tabs.
  1713. if (!$router_item || !$router_item['access']) {
  1714. return $empty;
  1715. }
  1716. // Get all tabs (also known as local tasks) and the root page.
  1717. $result = db_select('menu_router', NULL, array('fetch' => PDO::FETCH_ASSOC))
  1718. ->fields('menu_router')
  1719. ->condition('tab_root', $router_item['tab_root'])
  1720. ->condition('context', MENU_CONTEXT_INLINE, '<>')
  1721. ->orderBy('weight')
  1722. ->orderBy('title')
  1723. ->execute();
  1724. $map = $router_item['original_map'];
  1725. $children = array();
  1726. $tasks = array();
  1727. $root_path = $router_item['path'];
  1728. foreach ($result as $item) {
  1729. _menu_translate($item, $map, TRUE);
  1730. if ($item['tab_parent']) {
  1731. // All tabs, but not the root page.
  1732. $children[$item['tab_parent']][$item['path']] = $item;
  1733. }
  1734. // Store the translated item for later use.
  1735. $tasks[$item['path']] = $item;
  1736. }
  1737. // Find all tabs below the current path.
  1738. $path = $router_item['path'];
  1739. // Tab parenting may skip levels, so the number of parts in the path may not
  1740. // equal the depth. Thus we use the $depth counter (offset by 1000 for ksort).
  1741. $depth = 1001;
  1742. $actions['count'] = 0;
  1743. $actions['output'] = array();
  1744. while (isset($children[$path])) {
  1745. $tabs_current = array();
  1746. $actions_current = array();
  1747. $next_path = '';
  1748. $tab_count = 0;
  1749. $action_count = 0;
  1750. foreach ($children[$path] as $item) {
  1751. // Local tasks can be normal items too, so bitmask with
  1752. // MENU_IS_LOCAL_TASK before checking.
  1753. if (!($item['type'] & MENU_IS_LOCAL_TASK)) {
  1754. // This item is not a tab, skip it.
  1755. continue;
  1756. }
  1757. if ($item['access']) {
  1758. $link = $item;
  1759. // The default task is always active. As tabs can be normal items
  1760. // too, so bitmask with MENU_LINKS_TO_PARENT before checking.
  1761. if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
  1762. // Find the first parent which is not a default local task or action.
  1763. for ($p = $item['tab_parent']; ($tasks[$p]['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT; $p = $tasks[$p]['tab_parent']);
  1764. // Use the path of the parent instead.
  1765. $link['href'] = $tasks[$p]['href'];
  1766. // Mark the link as active, if the current path happens to be the
  1767. // path of the default local task itself (i.e., instead of its
  1768. // tab_parent_href or tab_root_href). Normally, links for default
  1769. // local tasks link to their parent, but the path of default local
  1770. // tasks can still be accessed directly, in which case this link
  1771. // would not be marked as active, since l() only compares the href
  1772. // with $_GET['q'].
  1773. if ($link['href'] != $_GET['q']) {
  1774. $link['localized_options']['attributes']['class'][] = 'active';
  1775. }
  1776. $tabs_current[] = array(
  1777. '#theme' => 'menu_local_task',
  1778. '#link' => $link,
  1779. '#active' => TRUE,
  1780. );
  1781. $next_path = $item['path'];
  1782. $tab_count++;
  1783. }
  1784. else {
  1785. // Actions can be normal items too, so bitmask with
  1786. // MENU_IS_LOCAL_ACTION before checking.
  1787. if (($item['type'] & MENU_IS_LOCAL_ACTION) == MENU_IS_LOCAL_ACTION) {
  1788. // The item is an action, display it as such.
  1789. $actions_current[] = array(
  1790. '#theme' => 'menu_local_action',
  1791. '#link' => $link,
  1792. );
  1793. $action_count++;
  1794. }
  1795. else {
  1796. // Otherwise, it's a normal tab.
  1797. $tabs_current[] = array(
  1798. '#theme' => 'menu_local_task',
  1799. '#link' => $link,
  1800. );
  1801. $tab_count++;
  1802. }
  1803. }
  1804. }
  1805. }
  1806. $path = $next_path;
  1807. $tabs[$depth]['count'] = $tab_count;
  1808. $tabs[$depth]['output'] = $tabs_current;
  1809. $actions['count'] += $action_count;
  1810. $actions['output'] = array_merge($actions['output'], $actions_current);
  1811. $depth++;
  1812. }
  1813. $data['actions'] = $actions;
  1814. // Find all tabs at the same level or above the current one.
  1815. $parent = $router_item['tab_parent'];
  1816. $path = $router_item['path'];
  1817. $current = $router_item;
  1818. $depth = 1000;
  1819. while (isset($children[$parent])) {
  1820. $tabs_current = array();
  1821. $next_path = '';
  1822. $next_parent = '';
  1823. $count = 0;
  1824. foreach ($children[$parent] as $item) {
  1825. // Skip local actions.
  1826. if ($item['type'] & MENU_IS_LOCAL_ACTION) {
  1827. continue;
  1828. }
  1829. if ($item['access']) {
  1830. $count++;
  1831. $link = $item;
  1832. // Local tasks can be normal items too, so bitmask with
  1833. // MENU_LINKS_TO_PARENT before checking.
  1834. if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
  1835. // Find the first parent which is not a default local task.
  1836. for ($p = $item['tab_parent']; ($tasks[$p]['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT; $p = $tasks[$p]['tab_parent']);
  1837. // Use the path of the parent instead.
  1838. $link['href'] = $tasks[$p]['href'];
  1839. if ($item['path'] == $router_item['path']) {
  1840. $root_path = $tasks[$p]['path'];
  1841. }
  1842. }
  1843. // We check for the active tab.
  1844. if ($item['path'] == $path) {
  1845. // Mark the link as active, if the current path is a (second-level)
  1846. // local task of a default local task. Since this default local task
  1847. // links to its parent, l() will not mark it as active, as it only
  1848. // compares the link's href to $_GET['q'].
  1849. if ($link['href'] != $_GET['q']) {
  1850. $link['localized_options']['attributes']['class'][] = 'active';
  1851. }
  1852. $tabs_current[] = array(
  1853. '#theme' => 'menu_local_task',
  1854. '#link' => $link,
  1855. '#active' => TRUE,
  1856. );
  1857. $next_path = $item['tab_parent'];
  1858. if (isset($tasks[$next_path])) {
  1859. $next_parent = $tasks[$next_path]['tab_parent'];
  1860. }
  1861. }
  1862. else {
  1863. $tabs_current[] = array(
  1864. '#theme' => 'menu_local_task',
  1865. '#link' => $link,
  1866. );
  1867. }
  1868. }
  1869. }
  1870. $path = $next_path;
  1871. $parent = $next_parent;
  1872. $tabs[$depth]['count'] = $count;
  1873. $tabs[$depth]['output'] = $tabs_current;
  1874. $depth--;
  1875. }
  1876. // Sort by depth.
  1877. ksort($tabs);
  1878. // Remove the depth, we are interested only in their relative placement.
  1879. $tabs = array_values($tabs);
  1880. $data['tabs'] = $tabs;
  1881. // Allow modules to alter local tasks or dynamically append further tasks.
  1882. drupal_alter('menu_local_tasks', $data, $router_item, $root_path);
  1883. }
  1884. if (isset($data['tabs'][$level])) {
  1885. return array(
  1886. 'tabs' => $data['tabs'][$level],
  1887. 'actions' => $data['actions'],
  1888. 'root_path' => $root_path,
  1889. );
  1890. }
  1891. // @todo If there are no tabs, then there still can be actions; for example,
  1892. // when added via hook_menu_local_tasks_alter().
  1893. elseif (!empty($data['actions']['output'])) {
  1894. return array('actions' => $data['actions']) + $empty;
  1895. }
  1896. return $empty;
  1897. }
  1898. /**
  1899. * Retrieve contextual links for a system object based on registered local tasks.
  1900. *
  1901. * This leverages the menu system to retrieve the first layer of registered
  1902. * local tasks for a given system path. All local tasks of the tab type
  1903. * MENU_CONTEXT_INLINE are taken into account.
  1904. *
  1905. * @see hook_menu()
  1906. *
  1907. * For example, when considering the following registered local tasks:
  1908. * - node/%node/view (default local task) with no 'context' defined
  1909. * - node/%node/edit with context: MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE
  1910. * - node/%node/revisions with context: MENU_CONTEXT_PAGE
  1911. * - node/%node/report-as-spam with context: MENU_CONTEXT_INLINE
  1912. *
  1913. * If the path "node/123" is passed to this function, then it will return the
  1914. * links for 'edit' and 'report-as-spam'.
  1915. *
  1916. * @param $module
  1917. * The name of the implementing module. This is used to prefix the key for
  1918. * each contextual link, which is transformed into a CSS class during
  1919. * rendering by theme_links(). For example, if $module is 'block' and the
  1920. * retrieved local task path argument is 'edit', then the resulting CSS class
  1921. * will be 'block-edit'.
  1922. * @param $parent_path
  1923. * The static menu router path of the object to retrieve local tasks for, for
  1924. * example 'node' or 'admin/structure/block/manage'.
  1925. * @param $args
  1926. * A list of dynamic path arguments to append to $parent_path to form the
  1927. * fully-qualified menu router path, for example array(123) for a certain
  1928. * node or array('system', 'navigation') for a certain block.
  1929. *
  1930. * @return
  1931. * A list of menu router items that are local tasks for the passed-in path.
  1932. *
  1933. * @see contextual_links_preprocess()
  1934. */
  1935. function menu_contextual_links($module, $parent_path, $args) {
  1936. static $path_empty = array();
  1937. $links = array();
  1938. // Performance: In case a previous invocation for the same parent path did not
  1939. // return any links, we immediately return here.
  1940. if (isset($path_empty[$parent_path])) {
  1941. return $links;
  1942. }
  1943. // Construct the item-specific parent path.
  1944. $path = $parent_path . '/' . implode('/', $args);
  1945. // Get the router item for the given parent link path.
  1946. $router_item = menu_get_item($path);
  1947. if (!$router_item || !$router_item['access']) {
  1948. $path_empty[$parent_path] = TRUE;
  1949. return $links;
  1950. }
  1951. $data = &drupal_static(__FUNCTION__, array());
  1952. $root_path = $router_item['path'];
  1953. // Performance: For a single, normalized path (such as 'node/%') we only query
  1954. // available tasks once per request.
  1955. if (!isset($data[$root_path])) {
  1956. // Get all contextual links that are direct children of the router item and
  1957. // not of the tab type 'view'.
  1958. $data[$root_path] = db_select('menu_router', 'm')
  1959. ->fields('m')
  1960. ->condition('tab_parent', $router_item['tab_root'])
  1961. ->condition('context', MENU_CONTEXT_NONE, '<>')
  1962. ->condition('context', MENU_CONTEXT_PAGE, '<>')
  1963. ->orderBy('weight')
  1964. ->orderBy('title')
  1965. ->execute()
  1966. ->fetchAllAssoc('path', PDO::FETCH_ASSOC);
  1967. }
  1968. $parent_length = drupal_strlen($root_path) + 1;
  1969. $map = $router_item['original_map'];
  1970. foreach ($data[$root_path] as $item) {
  1971. // Extract the actual "task" string from the path argument.
  1972. $key = drupal_substr($item['path'], $parent_length);
  1973. // Denormalize and translate the contextual link.
  1974. _menu_translate($item, $map, TRUE);
  1975. if (!$item['access']) {
  1976. continue;
  1977. }
  1978. // All contextual links are keyed by the actual "task" path argument,
  1979. // prefixed with the name of the implementing module.
  1980. $links[$module . '-' . $key] = $item;
  1981. }
  1982. // Allow modules to alter contextual links.
  1983. drupal_alter('menu_contextual_links', $links, $router_item, $root_path);
  1984. // Performance: If the current user does not have access to any links for this
  1985. // router path and no other module added further links, we assign FALSE here
  1986. // to skip the entire process the next time the same router path is requested.
  1987. if (empty($links)) {
  1988. $path_empty[$parent_path] = TRUE;
  1989. }
  1990. return $links;
  1991. }
  1992. /**
  1993. * Returns the rendered local tasks at the top level.
  1994. */
  1995. function menu_primary_local_tasks() {
  1996. $links = menu_local_tasks(0);
  1997. // Do not display single tabs.
  1998. return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
  1999. }
  2000. /**
  2001. * Returns the rendered local tasks at the second level.
  2002. */
  2003. function menu_secondary_local_tasks() {
  2004. $links = menu_local_tasks(1);
  2005. // Do not display single tabs.
  2006. return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
  2007. }
  2008. /**
  2009. * Returns the rendered local actions at the current level.
  2010. */
  2011. function menu_local_actions() {
  2012. $links = menu_local_tasks();
  2013. return $links['actions']['output'];
  2014. }
  2015. /**
  2016. * Returns the router path, or the path of the parent tab of a default local task.
  2017. */
  2018. function menu_tab_root_path() {
  2019. $links = menu_local_tasks();
  2020. return $links['root_path'];
  2021. }
  2022. /**
  2023. * Returns a renderable element for the primary and secondary tabs.
  2024. */
  2025. function menu_local_tabs() {
  2026. return array(
  2027. '#theme' => 'menu_local_tasks',
  2028. '#primary' => menu_primary_local_tasks(),
  2029. '#secondary' => menu_secondary_local_tasks(),
  2030. );
  2031. }
  2032. /**
  2033. * Returns HTML for primary and secondary local tasks.
  2034. *
  2035. * @ingroup themeable
  2036. */
  2037. function theme_menu_local_tasks(&$variables) {
  2038. $output = '';
  2039. if (!empty($variables['primary'])) {
  2040. $variables['primary']['#prefix'] = '<h2 class="element-invisible">' . t('Primary tabs') . '</h2>';
  2041. $variables['primary']['#prefix'] .= '<ul class="tabs primary">';
  2042. $variables['primary']['#suffix'] = '</ul>';
  2043. $output .= drupal_render($variables['primary']);
  2044. }
  2045. if (!empty($variables['secondary'])) {
  2046. $variables['secondary']['#prefix'] = '<h2 class="element-invisible">' . t('Secondary tabs') . '</h2>';
  2047. $variables['secondary']['#prefix'] .= '<ul class="tabs secondary">';
  2048. $variables['secondary']['#suffix'] = '</ul>';
  2049. $output .= drupal_render($variables['secondary']);
  2050. }
  2051. return $output;
  2052. }
  2053. /**
  2054. * Set (or get) the active menu for the current page - determines the active trail.
  2055. */
  2056. function menu_set_active_menu_names($menu_names = NULL) {
  2057. $active = &drupal_static(__FUNCTION__);
  2058. if (isset($menu_names) && is_array($menu_names)) {
  2059. $active = $menu_names;
  2060. }
  2061. elseif (!isset($active)) {
  2062. $active = variable_get('menu_default_active_menus', array_keys(menu_list_system_menus()));
  2063. }
  2064. return $active;
  2065. }
  2066. /**
  2067. * Get the active menu for the current page - determines the active trail.
  2068. */
  2069. function menu_get_active_menu_names() {
  2070. return menu_set_active_menu_names();
  2071. }
  2072. /**
  2073. * Set the active path, which determines which page is loaded.
  2074. *
  2075. * @param $path
  2076. * A Drupal path - not a path alias.
  2077. *
  2078. * Note that this may not have the desired effect unless invoked very early
  2079. * in the page load, such as during hook_boot, or unless you call
  2080. * menu_execute_active_handler() to generate your page output.
  2081. */
  2082. function menu_set_active_item($path) {
  2083. $_GET['q'] = $path;
  2084. }
  2085. /**
  2086. * Sets or gets the active trail (path to menu tree root) of the current page.
  2087. *
  2088. * @param $new_trail
  2089. * Menu trail to set, or NULL to use previously-set or calculated trail. If
  2090. * supplying a trail, use the same format as the return value (see below).
  2091. *
  2092. * @return
  2093. * Path to menu root of the current page, as an array of menu link items,
  2094. * starting with the site's home page. Each link item is an associative array
  2095. * with the following components:
  2096. * - title: Title of the item.
  2097. * - href: Drupal path of the item.
  2098. * - localized_options: Options for passing into the l() function.
  2099. * - type: A menu type constant, such as MENU_DEFAULT_LOCAL_TASK, or 0 to
  2100. * indicate it's not really in the menu (used for the home page item).
  2101. * If $new_trail is supplied, the value is saved in a static variable and
  2102. * returned. If $new_trail is not supplied, and there is a saved value from
  2103. * a previous call, the saved value is returned. If $new_trail is not supplied
  2104. * and there is no saved value, the path to the current page is calculated,
  2105. * saved as the static value, and returned.
  2106. */
  2107. function menu_set_active_trail($new_trail = NULL) {
  2108. $trail = &drupal_static(__FUNCTION__);
  2109. if (isset($new_trail)) {
  2110. $trail = $new_trail;
  2111. }
  2112. elseif (!isset($trail)) {
  2113. $trail = array();
  2114. $trail[] = array(
  2115. 'title' => t('Home'),
  2116. 'href' => '<front>',
  2117. 'link_path' => '',
  2118. 'localized_options' => array(),
  2119. 'type' => 0,
  2120. );
  2121. // Try to retrieve a menu link corresponding to the current path. If more
  2122. // than one exists, the link from the most preferred menu is returned.
  2123. $preferred_link = menu_link_get_preferred();
  2124. $current_item = menu_get_item();
  2125. // There is a link for the current path.
  2126. if ($preferred_link) {
  2127. // Pass TRUE for $only_active_trail to make menu_tree_page_data() build
  2128. // a stripped down menu tree containing the active trail only, in case
  2129. // the given menu has not been built in this request yet.
  2130. $tree = menu_tree_page_data($preferred_link['menu_name'], NULL, TRUE);
  2131. list($key, $curr) = each($tree);
  2132. }
  2133. // There is no link for the current path.
  2134. else {
  2135. $preferred_link = $current_item;
  2136. $curr = FALSE;
  2137. }
  2138. while ($curr) {
  2139. $link = $curr['link'];
  2140. if ($link['in_active_trail']) {
  2141. // Add the link to the trail, unless it links to its parent.
  2142. if (!($link['type'] & MENU_LINKS_TO_PARENT)) {
  2143. // The menu tree for the active trail may contain additional links
  2144. // that have not been translated yet, since they contain dynamic
  2145. // argument placeholders (%). Such links are not contained in regular
  2146. // menu trees, and have only been loaded for the additional
  2147. // translation that happens here, so as to be able to display them in
  2148. // the breadcumb for the current page.
  2149. // @see _menu_tree_check_access()
  2150. // @see _menu_link_translate()
  2151. if (strpos($link['href'], '%') !== FALSE) {
  2152. _menu_link_translate($link, TRUE);
  2153. }
  2154. if ($link['access']) {
  2155. $trail[] = $link;
  2156. }
  2157. }
  2158. $tree = $curr['below'] ? $curr['below'] : array();
  2159. }
  2160. list($key, $curr) = each($tree);
  2161. }
  2162. // Make sure the current page is in the trail to build the page title, by
  2163. // appending either the preferred link or the menu router item for the
  2164. // current page. Exclude it if we are on the front page.
  2165. $last = end($trail);
  2166. if ($last['href'] != $preferred_link['href'] && !drupal_is_front_page()) {
  2167. $trail[] = $preferred_link;
  2168. }
  2169. }
  2170. return $trail;
  2171. }
  2172. /**
  2173. * Lookup the preferred menu link for a given system path.
  2174. *
  2175. * @param $path
  2176. * The path, for example 'node/5'. The function will find the corresponding
  2177. * menu link ('node/5' if it exists, or fallback to 'node/%').
  2178. *
  2179. * @return
  2180. * A fully translated menu link, or NULL if no matching menu link was
  2181. * found. The most specific menu link ('node/5' preferred over 'node/%') in
  2182. * the most preferred menu (as defined by menu_get_active_menu_names()) is
  2183. * returned.
  2184. */
  2185. function menu_link_get_preferred($path = NULL) {
  2186. $preferred_links = &drupal_static(__FUNCTION__);
  2187. if (!isset($path)) {
  2188. $path = $_GET['q'];
  2189. }
  2190. if (!isset($preferred_links[$path])) {
  2191. $preferred_links[$path] = FALSE;
  2192. // Look for the correct menu link by building a list of candidate paths,
  2193. // which are ordered by priority (translated hrefs are preferred over
  2194. // untranslated paths). Afterwards, the most relevant path is picked from
  2195. // the menus, ordered by menu preference.
  2196. $item = menu_get_item($path);
  2197. $path_candidates = array();
  2198. // 1. The current item href.
  2199. $path_candidates[$item['href']] = $item['href'];
  2200. // 2. The tab root href of the current item (if any).
  2201. if ($item['tab_parent'] && ($tab_root = menu_get_item($item['tab_root_href']))) {
  2202. $path_candidates[$tab_root['href']] = $tab_root['href'];
  2203. }
  2204. // 3. The current item path (with wildcards).
  2205. $path_candidates[$item['path']] = $item['path'];
  2206. // 4. The tab root path of the current item (if any).
  2207. if (!empty($tab_root)) {
  2208. $path_candidates[$tab_root['path']] = $tab_root['path'];
  2209. }
  2210. // Retrieve a list of menu names, ordered by preference.
  2211. $menu_names = menu_get_active_menu_names();
  2212. $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
  2213. $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
  2214. $query->fields('ml');
  2215. // Weight must be taken from {menu_links}, not {menu_router}.
  2216. $query->addField('ml', 'weight', 'link_weight');
  2217. $query->fields('m');
  2218. $query->condition('ml.menu_name', $menu_names, 'IN');
  2219. $query->condition('ml.link_path', $path_candidates, 'IN');
  2220. // Sort candidates by link path and menu name.
  2221. $candidates = array();
  2222. foreach ($query->execute() as $candidate) {
  2223. $candidate['weight'] = $candidate['link_weight'];
  2224. $candidates[$candidate['link_path']][$candidate['menu_name']] = $candidate;
  2225. }
  2226. // Pick the most specific link, in the most preferred menu.
  2227. foreach ($path_candidates as $link_path) {
  2228. if (!isset($candidates[$link_path])) {
  2229. continue;
  2230. }
  2231. foreach ($menu_names as $menu_name) {
  2232. if (!isset($candidates[$link_path][$menu_name])) {
  2233. continue;
  2234. }
  2235. $candidate_item = $candidates[$link_path][$menu_name];
  2236. $map = explode('/', $path);
  2237. _menu_translate($candidate_item, $map);
  2238. if ($candidate_item['access']) {
  2239. $preferred_links[$path] = $candidate_item;
  2240. }
  2241. break 2;
  2242. }
  2243. }
  2244. }
  2245. return $preferred_links[$path];
  2246. }
  2247. /**
  2248. * Gets the active trail (path to root menu root) of the current page.
  2249. *
  2250. * See menu_set_active_trail() for details of return value.
  2251. */
  2252. function menu_get_active_trail() {
  2253. return menu_set_active_trail();
  2254. }
  2255. /**
  2256. * Get the breadcrumb for the current page, as determined by the active trail.
  2257. *
  2258. * @see menu_set_active_trail()
  2259. */
  2260. function menu_get_active_breadcrumb() {
  2261. $breadcrumb = array();
  2262. // No breadcrumb for the front page.
  2263. if (drupal_is_front_page()) {
  2264. return $breadcrumb;
  2265. }
  2266. $item = menu_get_item();
  2267. if (!empty($item['access'])) {
  2268. $active_trail = menu_get_active_trail();
  2269. // Allow modules to alter the breadcrumb, if possible, as that is much
  2270. // faster than rebuilding an entirely new active trail.
  2271. drupal_alter('menu_breadcrumb', $active_trail, $item);
  2272. // Don't show a link to the current page in the breadcrumb trail.
  2273. $end = end($active_trail);
  2274. if ($item['href'] == $end['href']) {
  2275. array_pop($active_trail);
  2276. }
  2277. // Remove the tab root (parent) if the current path links to its parent.
  2278. // Normally, the tab root link is included in the breadcrumb, as soon as we
  2279. // are on a local task or any other child link. However, if we are on a
  2280. // default local task (e.g., node/%/view), then we do not want the tab root
  2281. // link (e.g., node/%) to appear, as it would be identical to the current
  2282. // page. Since this behavior also needs to work recursively (i.e., on
  2283. // default local tasks of default local tasks), and since the last non-task
  2284. // link in the trail is used as page title (see menu_get_active_title()),
  2285. // this condition cannot be cleanly integrated into menu_get_active_trail().
  2286. // menu_get_active_trail() already skips all links that link to their parent
  2287. // (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
  2288. // itself, we always remove the last link in the trail, if the current
  2289. // router item links to its parent.
  2290. if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
  2291. array_pop($active_trail);
  2292. }
  2293. foreach ($active_trail as $parent) {
  2294. $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
  2295. }
  2296. }
  2297. return $breadcrumb;
  2298. }
  2299. /**
  2300. * Get the title of the current page, as determined by the active trail.
  2301. */
  2302. function menu_get_active_title() {
  2303. $active_trail = menu_get_active_trail();
  2304. foreach (array_reverse($active_trail) as $item) {
  2305. if (!(bool) ($item['type'] & MENU_IS_LOCAL_TASK)) {
  2306. return $item['title'];
  2307. }
  2308. }
  2309. }
  2310. /**
  2311. * Get a menu link by its mlid, access checked and link translated for rendering.
  2312. *
  2313. * This function should never be called from within node_load() or any other
  2314. * function used as a menu object load function since an infinite recursion may
  2315. * occur.
  2316. *
  2317. * @param $mlid
  2318. * The mlid of the menu item.
  2319. *
  2320. * @return
  2321. * A menu link, with $item['access'] filled and link translated for
  2322. * rendering.
  2323. */
  2324. function menu_link_load($mlid) {
  2325. if (is_numeric($mlid)) {
  2326. $query = db_select('menu_links', 'ml');
  2327. $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
  2328. $query->fields('ml');
  2329. // Weight should be taken from {menu_links}, not {menu_router}.
  2330. $query->addField('ml', 'weight', 'link_weight');
  2331. $query->fields('m');
  2332. $query->condition('ml.mlid', $mlid);
  2333. if ($item = $query->execute()->fetchAssoc()) {
  2334. $item['weight'] = $item['link_weight'];
  2335. _menu_link_translate($item);
  2336. return $item;
  2337. }
  2338. }
  2339. return FALSE;
  2340. }
  2341. /**
  2342. * Clears the cached cached data for a single named menu.
  2343. */
  2344. function menu_cache_clear($menu_name = 'navigation') {
  2345. $cache_cleared = &drupal_static(__FUNCTION__, array());
  2346. if (empty($cache_cleared[$menu_name])) {
  2347. cache_clear_all('links:' . $menu_name . ':', 'cache_menu', TRUE);
  2348. $cache_cleared[$menu_name] = 1;
  2349. }
  2350. elseif ($cache_cleared[$menu_name] == 1) {
  2351. drupal_register_shutdown_function('cache_clear_all', 'links:' . $menu_name . ':', 'cache_menu', TRUE);
  2352. $cache_cleared[$menu_name] = 2;
  2353. }
  2354. // Also clear the menu system static caches.
  2355. menu_reset_static_cache();
  2356. }
  2357. /**
  2358. * Clears all cached menu data. This should be called any time broad changes
  2359. * might have been made to the router items or menu links.
  2360. */
  2361. function menu_cache_clear_all() {
  2362. cache_clear_all('*', 'cache_menu', TRUE);
  2363. menu_reset_static_cache();
  2364. }
  2365. /**
  2366. * Resets the menu system static cache.
  2367. */
  2368. function menu_reset_static_cache() {
  2369. drupal_static_reset('_menu_build_tree');
  2370. drupal_static_reset('menu_tree');
  2371. drupal_static_reset('menu_tree_all_data');
  2372. drupal_static_reset('menu_tree_page_data');
  2373. drupal_static_reset('menu_load_all');
  2374. drupal_static_reset('menu_link_get_preferred');
  2375. }
  2376. /**
  2377. * (Re)populate the database tables used by various menu functions.
  2378. *
  2379. * This function will clear and populate the {menu_router} table, add entries
  2380. * to {menu_links} for new router items, then remove stale items from
  2381. * {menu_links}. If called from update.php or install.php, it will also
  2382. * schedule a call to itself on the first real page load from
  2383. * menu_execute_active_handler(), because the maintenance page environment
  2384. * is different and leaves stale data in the menu tables.
  2385. *
  2386. * @return
  2387. * TRUE if the menu was rebuilt, FALSE if another thread was rebuilding
  2388. * in parallel and the current thread just waited for completion.
  2389. */
  2390. function menu_rebuild() {
  2391. if (!lock_acquire('menu_rebuild')) {
  2392. // Wait for another request that is already doing this work.
  2393. // We choose to block here since otherwise the router item may not
  2394. // be available in menu_execute_active_handler() resulting in a 404.
  2395. lock_wait('menu_rebuild');
  2396. return FALSE;
  2397. }
  2398. $transaction = db_transaction();
  2399. try {
  2400. list($menu, $masks) = menu_router_build();
  2401. _menu_router_save($menu, $masks);
  2402. _menu_navigation_links_rebuild($menu);
  2403. // Clear the menu, page and block caches.
  2404. menu_cache_clear_all();
  2405. _menu_clear_page_cache();
  2406. if (defined('MAINTENANCE_MODE')) {
  2407. variable_set('menu_rebuild_needed', TRUE);
  2408. }
  2409. else {
  2410. variable_del('menu_rebuild_needed');
  2411. }
  2412. }
  2413. catch (Exception $e) {
  2414. $transaction->rollback();
  2415. watchdog_exception('menu', $e);
  2416. }
  2417. lock_release('menu_rebuild');
  2418. return TRUE;
  2419. }
  2420. /**
  2421. * Collect and alter the menu definitions.
  2422. */
  2423. function menu_router_build() {
  2424. // We need to manually call each module so that we can know which module
  2425. // a given item came from.
  2426. $callbacks = array();
  2427. foreach (module_implements('menu') as $module) {
  2428. $router_items = call_user_func($module . '_menu');
  2429. if (isset($router_items) && is_array($router_items)) {
  2430. foreach (array_keys($router_items) as $path) {
  2431. $router_items[$path]['module'] = $module;
  2432. }
  2433. $callbacks = array_merge($callbacks, $router_items);
  2434. }
  2435. }
  2436. // Alter the menu as defined in modules, keys are like user/%user.
  2437. drupal_alter('menu', $callbacks);
  2438. list($menu, $masks) = _menu_router_build($callbacks);
  2439. _menu_router_cache($menu);
  2440. return array($menu, $masks);
  2441. }
  2442. /**
  2443. * Helper function to store the menu router if we have it in memory.
  2444. */
  2445. function _menu_router_cache($new_menu = NULL) {
  2446. $menu = &drupal_static(__FUNCTION__);
  2447. if (isset($new_menu)) {
  2448. $menu = $new_menu;
  2449. }
  2450. return $menu;
  2451. }
  2452. /**
  2453. * Get the menu router.
  2454. */
  2455. function menu_get_router() {
  2456. // Check first if we have it in memory already.
  2457. $menu = _menu_router_cache();
  2458. if (empty($menu)) {
  2459. list($menu, $masks) = menu_router_build();
  2460. }
  2461. return $menu;
  2462. }
  2463. /**
  2464. * Builds a link from a router item.
  2465. */
  2466. function _menu_link_build($item) {
  2467. // Suggested items are disabled by default.
  2468. if ($item['type'] == MENU_SUGGESTED_ITEM) {
  2469. $item['hidden'] = 1;
  2470. }
  2471. // Hide all items that are not visible in the tree.
  2472. elseif (!($item['type'] & MENU_VISIBLE_IN_TREE)) {
  2473. $item['hidden'] = -1;
  2474. }
  2475. // Note, we set this as 'system', so that we can be sure to distinguish all
  2476. // the menu links generated automatically from entries in {menu_router}.
  2477. $item['module'] = 'system';
  2478. $item += array(
  2479. 'menu_name' => 'navigation',
  2480. 'link_title' => $item['title'],
  2481. 'link_path' => $item['path'],
  2482. 'hidden' => 0,
  2483. 'options' => empty($item['description']) ? array() : array('attributes' => array('title' => $item['description'])),
  2484. );
  2485. return $item;
  2486. }
  2487. /**
  2488. * Helper function to build menu links for the items in the menu router.
  2489. */
  2490. function _menu_navigation_links_rebuild($menu) {
  2491. // Add normal and suggested items as links.
  2492. $menu_links = array();
  2493. foreach ($menu as $path => $item) {
  2494. if ($item['_visible']) {
  2495. $menu_links[$path] = $item;
  2496. $sort[$path] = $item['_number_parts'];
  2497. }
  2498. }
  2499. if ($menu_links) {
  2500. // Keep an array of processed menu links, to allow menu_link_save() to
  2501. // check this for parents instead of querying the database.
  2502. $parent_candidates = array();
  2503. // Make sure no child comes before its parent.
  2504. array_multisort($sort, SORT_NUMERIC, $menu_links);
  2505. foreach ($menu_links as $key => $item) {
  2506. $existing_item = db_select('menu_links')
  2507. ->fields('menu_links')
  2508. ->condition('link_path', $item['path'])
  2509. ->condition('module', 'system')
  2510. ->execute()->fetchAssoc();
  2511. if ($existing_item) {
  2512. $item['mlid'] = $existing_item['mlid'];
  2513. // A change in hook_menu may move the link to a different menu
  2514. if (empty($item['menu_name']) || ($item['menu_name'] == $existing_item['menu_name'])) {
  2515. $item['menu_name'] = $existing_item['menu_name'];
  2516. $item['plid'] = $existing_item['plid'];
  2517. }
  2518. else {
  2519. // It moved to a new menu. Let menu_link_save() try to find a new
  2520. // parent based on the path.
  2521. unset($item['plid']);
  2522. }
  2523. $item['has_children'] = $existing_item['has_children'];
  2524. $item['updated'] = $existing_item['updated'];
  2525. }
  2526. if ($existing_item && $existing_item['customized']) {
  2527. $parent_candidates[$existing_item['mlid']] = $existing_item;
  2528. }
  2529. else {
  2530. $item = _menu_link_build($item);
  2531. menu_link_save($item, $existing_item, $parent_candidates);
  2532. $parent_candidates[$item['mlid']] = $item;
  2533. unset($menu_links[$key]);
  2534. }
  2535. }
  2536. }
  2537. $paths = array_keys($menu);
  2538. // Updated and customized items whose router paths are gone need new ones.
  2539. $result = db_select('menu_links', NULL, array('fetch' => PDO::FETCH_ASSOC))
  2540. ->fields('menu_links', array(
  2541. 'link_path',
  2542. 'mlid',
  2543. 'router_path',
  2544. 'updated',
  2545. ))
  2546. ->condition(db_or()
  2547. ->condition('updated', 1)
  2548. ->condition(db_and()
  2549. ->condition('router_path', $paths, 'NOT IN')
  2550. ->condition('external', 0)
  2551. ->condition('customized', 1)
  2552. )
  2553. )
  2554. ->execute();
  2555. foreach ($result as $item) {
  2556. $router_path = _menu_find_router_path($item['link_path']);
  2557. if (!empty($router_path) && ($router_path != $item['router_path'] || $item['updated'])) {
  2558. // If the router path and the link path matches, it's surely a working
  2559. // item, so we clear the updated flag.
  2560. $updated = $item['updated'] && $router_path != $item['link_path'];
  2561. db_update('menu_links')
  2562. ->fields(array(
  2563. 'router_path' => $router_path,
  2564. 'updated' => (int) $updated,
  2565. ))
  2566. ->condition('mlid', $item['mlid'])
  2567. ->execute();
  2568. }
  2569. }
  2570. // Find any item whose router path does not exist any more.
  2571. $result = db_select('menu_links')
  2572. ->fields('menu_links')
  2573. ->condition('router_path', $paths, 'NOT IN')
  2574. ->condition('external', 0)
  2575. ->condition('updated', 0)
  2576. ->condition('customized', 0)
  2577. ->orderBy('depth', 'DESC')
  2578. ->execute();
  2579. // Remove all such items. Starting from those with the greatest depth will
  2580. // minimize the amount of re-parenting done by menu_link_delete().
  2581. foreach ($result as $item) {
  2582. _menu_delete_item($item, TRUE);
  2583. }
  2584. }
  2585. /**
  2586. * Clone an array of menu links.
  2587. *
  2588. * @param $links
  2589. * An array of menu links to clone.
  2590. * @param $menu_name
  2591. * (optional) The name of a menu that the links will be cloned for. If not
  2592. * set, the cloned links will be in the same menu as the original set of
  2593. * links that were passed in.
  2594. *
  2595. * @return
  2596. * An array of menu links with the same properties as the passed-in array,
  2597. * but with the link identifiers removed so that a new link will be created
  2598. * when any of them is passed in to menu_link_save().
  2599. *
  2600. * @see menu_link_save()
  2601. */
  2602. function menu_links_clone($links, $menu_name = NULL) {
  2603. foreach ($links as &$link) {
  2604. unset($link['mlid']);
  2605. unset($link['plid']);
  2606. if (isset($menu_name)) {
  2607. $link['menu_name'] = $menu_name;
  2608. }
  2609. }
  2610. return $links;
  2611. }
  2612. /**
  2613. * Returns an array containing all links for a menu.
  2614. *
  2615. * @param $menu_name
  2616. * The name of the menu whose links should be returned.
  2617. *
  2618. * @return
  2619. * An array of menu links.
  2620. */
  2621. function menu_load_links($menu_name) {
  2622. $links = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC))
  2623. ->fields('ml')
  2624. ->condition('ml.menu_name', $menu_name)
  2625. // Order by weight so as to be helpful for menus that are only one level
  2626. // deep.
  2627. ->orderBy('weight')
  2628. ->execute()
  2629. ->fetchAll();
  2630. foreach ($links as &$link) {
  2631. $link['options'] = unserialize($link['options']);
  2632. }
  2633. return $links;
  2634. }
  2635. /**
  2636. * Deletes all links for a menu.
  2637. *
  2638. * @param $menu_name
  2639. * The name of the menu whose links will be deleted.
  2640. */
  2641. function menu_delete_links($menu_name) {
  2642. $links = menu_load_links($menu_name);
  2643. foreach ($links as $link) {
  2644. // To speed up the deletion process, we reset some link properties that
  2645. // would trigger re-parenting logic in _menu_delete_item() and
  2646. // _menu_update_parental_status().
  2647. $link['has_children'] = FALSE;
  2648. $link['plid'] = 0;
  2649. _menu_delete_item($link);
  2650. }
  2651. }
  2652. /**
  2653. * Delete one or several menu links.
  2654. *
  2655. * @param $mlid
  2656. * A valid menu link mlid or NULL. If NULL, $path is used.
  2657. * @param $path
  2658. * The path to the menu items to be deleted. $mlid must be NULL.
  2659. */
  2660. function menu_link_delete($mlid, $path = NULL) {
  2661. if (isset($mlid)) {
  2662. _menu_delete_item(db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc());
  2663. }
  2664. else {
  2665. $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $path));
  2666. foreach ($result as $link) {
  2667. _menu_delete_item($link);
  2668. }
  2669. }
  2670. }
  2671. /**
  2672. * Helper function for menu_link_delete; deletes a single menu link.
  2673. *
  2674. * @param $item
  2675. * Item to be deleted.
  2676. * @param $force
  2677. * Forces deletion. Internal use only, setting to TRUE is discouraged.
  2678. */
  2679. function _menu_delete_item($item, $force = FALSE) {
  2680. $item = is_object($item) ? get_object_vars($item) : $item;
  2681. if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) {
  2682. // Children get re-attached to the item's parent.
  2683. if ($item['has_children']) {
  2684. $result = db_query("SELECT mlid FROM {menu_links} WHERE plid = :plid", array(':plid' => $item['mlid']));
  2685. foreach ($result as $m) {
  2686. $child = menu_link_load($m->mlid);
  2687. $child['plid'] = $item['plid'];
  2688. menu_link_save($child);
  2689. }
  2690. }
  2691. // Notify modules we are deleting the item.
  2692. module_invoke_all('menu_link_delete', $item);
  2693. db_delete('menu_links')->condition('mlid', $item['mlid'])->execute();
  2694. // Update the has_children status of the parent.
  2695. _menu_update_parental_status($item);
  2696. menu_cache_clear($item['menu_name']);
  2697. _menu_clear_page_cache();
  2698. }
  2699. }
  2700. /**
  2701. * Saves a menu link.
  2702. *
  2703. * After calling this function, rebuild the menu cache using
  2704. * menu_cache_clear_all().
  2705. *
  2706. * @param $item
  2707. * An associative array representing a menu link item, with elements:
  2708. * - link_path: (required) The path of the menu item, which should be
  2709. * normalized first by calling drupal_get_normal_path() on it.
  2710. * - link_title: (required) Title to appear in menu for the link.
  2711. * - menu_name: (optional) The machine name of the menu for the link.
  2712. * Defaults to 'navigation'.
  2713. * - weight: (optional) Integer to determine position in menu. Default is 0.
  2714. * - expanded: (optional) Boolean that determines if the item is expanded.
  2715. * - options: (optional) An array of options, see l() for more.
  2716. * - mlid: (optional) Menu link identifier, the primary integer key for each
  2717. * menu link. Can be set to an existing value, or to 0 or NULL
  2718. * to insert a new link.
  2719. * - plid: (optional) The mlid of the parent.
  2720. * - router_path: (optional) The path of the relevant router item.
  2721. * @param $existing_item
  2722. * Optional, the current record from the {menu_links} table as an array.
  2723. * @param $parent_candidates
  2724. * Optional array of menu links keyed by mlid. Used by
  2725. * _menu_navigation_links_rebuild() only.
  2726. *
  2727. * @return
  2728. * The mlid of the saved menu link, or FALSE if the menu link could not be
  2729. * saved.
  2730. */
  2731. function menu_link_save(&$item, $existing_item = array(), $parent_candidates = array()) {
  2732. drupal_alter('menu_link', $item);
  2733. // This is the easiest way to handle the unique internal path '<front>',
  2734. // since a path marked as external does not need to match a router path.
  2735. $item['external'] = (url_is_external($item['link_path']) || $item['link_path'] == '<front>') ? 1 : 0;
  2736. // Load defaults.
  2737. $item += array(
  2738. 'menu_name' => 'navigation',
  2739. 'weight' => 0,
  2740. 'link_title' => '',
  2741. 'hidden' => 0,
  2742. 'has_children' => 0,
  2743. 'expanded' => 0,
  2744. 'options' => array(),
  2745. 'module' => 'menu',
  2746. 'customized' => 0,
  2747. 'updated' => 0,
  2748. );
  2749. if (isset($item['mlid'])) {
  2750. if (!$existing_item) {
  2751. $existing_item = db_query('SELECT * FROM {menu_links} WHERE mlid = :mlid', array('mlid' => $item['mlid']))->fetchAssoc();
  2752. }
  2753. if ($existing_item) {
  2754. $existing_item['options'] = unserialize($existing_item['options']);
  2755. }
  2756. }
  2757. else {
  2758. $existing_item = FALSE;
  2759. }
  2760. // Try to find a parent link. If found, assign it and derive its menu.
  2761. $parent = _menu_link_find_parent($item, $parent_candidates);
  2762. if (!empty($parent['mlid'])) {
  2763. $item['plid'] = $parent['mlid'];
  2764. $item['menu_name'] = $parent['menu_name'];
  2765. }
  2766. // If no corresponding parent link was found, move the link to the top-level.
  2767. else {
  2768. $item['plid'] = 0;
  2769. }
  2770. $menu_name = $item['menu_name'];
  2771. if (!$existing_item) {
  2772. $item['mlid'] = db_insert('menu_links')
  2773. ->fields(array(
  2774. 'menu_name' => $item['menu_name'],
  2775. 'plid' => $item['plid'],
  2776. 'link_path' => $item['link_path'],
  2777. 'hidden' => $item['hidden'],
  2778. 'external' => $item['external'],
  2779. 'has_children' => $item['has_children'],
  2780. 'expanded' => $item['expanded'],
  2781. 'weight' => $item['weight'],
  2782. 'module' => $item['module'],
  2783. 'link_title' => $item['link_title'],
  2784. 'options' => serialize($item['options']),
  2785. 'customized' => $item['customized'],
  2786. 'updated' => $item['updated'],
  2787. ))
  2788. ->execute();
  2789. }
  2790. // Directly fill parents for top-level links.
  2791. if ($item['plid'] == 0) {
  2792. $item['p1'] = $item['mlid'];
  2793. for ($i = 2; $i <= MENU_MAX_DEPTH; $i++) {
  2794. $item["p$i"] = 0;
  2795. }
  2796. $item['depth'] = 1;
  2797. }
  2798. // Otherwise, ensure that this link's depth is not beyond the maximum depth
  2799. // and fill parents based on the parent link.
  2800. else {
  2801. if ($item['has_children'] && $existing_item) {
  2802. $limit = MENU_MAX_DEPTH - menu_link_children_relative_depth($existing_item) - 1;
  2803. }
  2804. else {
  2805. $limit = MENU_MAX_DEPTH - 1;
  2806. }
  2807. if ($parent['depth'] > $limit) {
  2808. return FALSE;
  2809. }
  2810. $item['depth'] = $parent['depth'] + 1;
  2811. _menu_link_parents_set($item, $parent);
  2812. }
  2813. // Need to check both plid and menu_name, since plid can be 0 in any menu.
  2814. if ($existing_item && ($item['plid'] != $existing_item['plid'] || $menu_name != $existing_item['menu_name'])) {
  2815. _menu_link_move_children($item, $existing_item);
  2816. }
  2817. // Find the router_path.
  2818. if (empty($item['router_path']) || !$existing_item || ($existing_item['link_path'] != $item['link_path'])) {
  2819. if ($item['external']) {
  2820. $item['router_path'] = '';
  2821. }
  2822. else {
  2823. // Find the router path which will serve this path.
  2824. $item['parts'] = explode('/', $item['link_path'], MENU_MAX_PARTS);
  2825. $item['router_path'] = _menu_find_router_path($item['link_path']);
  2826. }
  2827. }
  2828. // If every value in $existing_item is the same in the $item, there is no
  2829. // reason to run the update queries or clear the caches. We use
  2830. // array_intersect_assoc() with the $item as the first parameter because
  2831. // $item may have additional keys left over from building a router entry.
  2832. // The intersect removes the extra keys, allowing a meaningful comparison.
  2833. if (!$existing_item || (array_intersect_assoc($item, $existing_item)) != $existing_item) {
  2834. db_update('menu_links')
  2835. ->fields(array(
  2836. 'menu_name' => $item['menu_name'],
  2837. 'plid' => $item['plid'],
  2838. 'link_path' => $item['link_path'],
  2839. 'router_path' => $item['router_path'],
  2840. 'hidden' => $item['hidden'],
  2841. 'external' => $item['external'],
  2842. 'has_children' => $item['has_children'],
  2843. 'expanded' => $item['expanded'],
  2844. 'weight' => $item['weight'],
  2845. 'depth' => $item['depth'],
  2846. 'p1' => $item['p1'],
  2847. 'p2' => $item['p2'],
  2848. 'p3' => $item['p3'],
  2849. 'p4' => $item['p4'],
  2850. 'p5' => $item['p5'],
  2851. 'p6' => $item['p6'],
  2852. 'p7' => $item['p7'],
  2853. 'p8' => $item['p8'],
  2854. 'p9' => $item['p9'],
  2855. 'module' => $item['module'],
  2856. 'link_title' => $item['link_title'],
  2857. 'options' => serialize($item['options']),
  2858. 'customized' => $item['customized'],
  2859. ))
  2860. ->condition('mlid', $item['mlid'])
  2861. ->execute();
  2862. // Check the has_children status of the parent.
  2863. _menu_update_parental_status($item);
  2864. menu_cache_clear($menu_name);
  2865. if ($existing_item && $menu_name != $existing_item['menu_name']) {
  2866. menu_cache_clear($existing_item['menu_name']);
  2867. }
  2868. // Notify modules we have acted on a menu item.
  2869. $hook = 'menu_link_insert';
  2870. if ($existing_item) {
  2871. $hook = 'menu_link_update';
  2872. }
  2873. module_invoke_all($hook, $item);
  2874. // Now clear the cache.
  2875. _menu_clear_page_cache();
  2876. }
  2877. return $item['mlid'];
  2878. }
  2879. /**
  2880. * Find a possible parent for a given menu link.
  2881. *
  2882. * Because the parent of a given link might not exist anymore in the database,
  2883. * we apply a set of heuristics to determine a proper parent:
  2884. *
  2885. * - use the passed parent link if specified and existing.
  2886. * - else, use the first existing link down the previous link hierarchy
  2887. * - else, for system menu links (derived from hook_menu()), reparent
  2888. * based on the path hierarchy.
  2889. *
  2890. * @param $menu_link
  2891. * A menu link.
  2892. * @param $parent_candidates
  2893. * An array of menu links keyed by mlid.
  2894. * @return
  2895. * A menu link structure of the possible parent or FALSE if no valid parent
  2896. * has been found.
  2897. */
  2898. function _menu_link_find_parent($menu_link, $parent_candidates = array()) {
  2899. $parent = FALSE;
  2900. // This item is explicitely top-level, skip the rest of the parenting.
  2901. if (isset($menu_link['plid']) && empty($menu_link['plid'])) {
  2902. return $parent;
  2903. }
  2904. // If we have a parent link ID, try to use that.
  2905. $candidates = array();
  2906. if (isset($menu_link['plid'])) {
  2907. $candidates[] = $menu_link['plid'];
  2908. }
  2909. // Else, if we have a link hierarchy try to find a valid parent in there.
  2910. if (!empty($menu_link['depth']) && $menu_link['depth'] > 1) {
  2911. for ($depth = $menu_link['depth'] - 1; $depth >= 1; $depth--) {
  2912. $candidates[] = $menu_link['p' . $depth];
  2913. }
  2914. }
  2915. foreach ($candidates as $mlid) {
  2916. if (isset($parent_candidates[$mlid])) {
  2917. $parent = $parent_candidates[$mlid];
  2918. }
  2919. else {
  2920. $parent = db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc();
  2921. }
  2922. if ($parent) {
  2923. return $parent;
  2924. }
  2925. }
  2926. // If everything else failed, try to derive the parent from the path
  2927. // hierarchy. This only makes sense for links derived from menu router
  2928. // items (ie. from hook_menu()).
  2929. if ($menu_link['module'] == 'system') {
  2930. $query = db_select('menu_links');
  2931. $query->condition('module', 'system');
  2932. // We always respect the link's 'menu_name'; inheritance for router items is
  2933. // ensured in _menu_router_build().
  2934. $query->condition('menu_name', $menu_link['menu_name']);
  2935. // Find the parent - it must be unique.
  2936. $parent_path = $menu_link['link_path'];
  2937. do {
  2938. $parent = FALSE;
  2939. $parent_path = substr($parent_path, 0, strrpos($parent_path, '/'));
  2940. $new_query = clone $query;
  2941. $new_query->condition('link_path', $parent_path);
  2942. // Only valid if we get a unique result.
  2943. if ($new_query->countQuery()->execute()->fetchField() == 1) {
  2944. $parent = $new_query->fields('menu_links')->execute()->fetchAssoc();
  2945. }
  2946. } while ($parent === FALSE && $parent_path);
  2947. }
  2948. return $parent;
  2949. }
  2950. /**
  2951. * Helper function to clear the page and block caches at most twice per page load.
  2952. */
  2953. function _menu_clear_page_cache() {
  2954. $cache_cleared = &drupal_static(__FUNCTION__, 0);
  2955. // Clear the page and block caches, but at most twice, including at
  2956. // the end of the page load when there are multiple links saved or deleted.
  2957. if ($cache_cleared == 0) {
  2958. cache_clear_all();
  2959. // Keep track of which menus have expanded items.
  2960. _menu_set_expanded_menus();
  2961. $cache_cleared = 1;
  2962. }
  2963. elseif ($cache_cleared == 1) {
  2964. drupal_register_shutdown_function('cache_clear_all');
  2965. // Keep track of which menus have expanded items.
  2966. drupal_register_shutdown_function('_menu_set_expanded_menus');
  2967. $cache_cleared = 2;
  2968. }
  2969. }
  2970. /**
  2971. * Helper function to update a list of menus with expanded items
  2972. */
  2973. function _menu_set_expanded_menus() {
  2974. $names = db_query("SELECT menu_name FROM {menu_links} WHERE expanded <> 0 GROUP BY menu_name")->fetchCol();
  2975. variable_set('menu_expanded', $names);
  2976. }
  2977. /**
  2978. * Find the router path which will serve this path.
  2979. *
  2980. * @param $link_path
  2981. * The path for we are looking up its router path.
  2982. *
  2983. * @return
  2984. * A path from $menu keys or empty if $link_path points to a nonexisting
  2985. * place.
  2986. */
  2987. function _menu_find_router_path($link_path) {
  2988. // $menu will only have data during a menu rebuild.
  2989. $menu = _menu_router_cache();
  2990. $router_path = $link_path;
  2991. $parts = explode('/', $link_path, MENU_MAX_PARTS);
  2992. $ancestors = menu_get_ancestors($parts);
  2993. if (empty($menu)) {
  2994. // Not during a menu rebuild, so look up in the database.
  2995. $router_path = (string) db_select('menu_router')
  2996. ->fields('menu_router', array('path'))
  2997. ->condition('path', $ancestors, 'IN')
  2998. ->orderBy('fit', 'DESC')
  2999. ->range(0, 1)
  3000. ->execute()->fetchField();
  3001. }
  3002. elseif (!isset($menu[$router_path])) {
  3003. // Add an empty router path as a fallback.
  3004. $ancestors[] = '';
  3005. foreach ($ancestors as $key => $router_path) {
  3006. if (isset($menu[$router_path])) {
  3007. // Exit the loop leaving $router_path as the first match.
  3008. break;
  3009. }
  3010. }
  3011. // If we did not find the path, $router_path will be the empty string
  3012. // at the end of $ancestors.
  3013. }
  3014. return $router_path;
  3015. }
  3016. /**
  3017. * Insert, update or delete an uncustomized menu link related to a module.
  3018. *
  3019. * @param $module
  3020. * The name of the module.
  3021. * @param $op
  3022. * Operation to perform: insert, update or delete.
  3023. * @param $link_path
  3024. * The path this link points to.
  3025. * @param $link_title
  3026. * Title of the link to insert or new title to update the link to.
  3027. * Unused for delete.
  3028. *
  3029. * @return
  3030. * The insert op returns the mlid of the new item. Others op return NULL.
  3031. */
  3032. function menu_link_maintain($module, $op, $link_path, $link_title) {
  3033. switch ($op) {
  3034. case 'insert':
  3035. $menu_link = array(
  3036. 'link_title' => $link_title,
  3037. 'link_path' => $link_path,
  3038. 'module' => $module,
  3039. );
  3040. return menu_link_save($menu_link);
  3041. break;
  3042. case 'update':
  3043. $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path AND module = :module AND customized = 0", array(':link_path' => $link_path, ':module' => $module))->fetchAll(PDO::FETCH_ASSOC);
  3044. foreach ($result as $link) {
  3045. $link['link_title'] = $link_title;
  3046. $link['options'] = unserialize($link['options']);
  3047. menu_link_save($link);
  3048. }
  3049. break;
  3050. case 'delete':
  3051. menu_link_delete(NULL, $link_path);
  3052. break;
  3053. }
  3054. }
  3055. /**
  3056. * Find the depth of an item's children relative to its depth.
  3057. *
  3058. * For example, if the item has a depth of 2, and the maximum of any child in
  3059. * the menu link tree is 5, the relative depth is 3.
  3060. *
  3061. * @param $item
  3062. * An array representing a menu link item.
  3063. *
  3064. * @return
  3065. * The relative depth, or zero.
  3066. *
  3067. */
  3068. function menu_link_children_relative_depth($item) {
  3069. $query = db_select('menu_links');
  3070. $query->addField('menu_links', 'depth');
  3071. $query->condition('menu_name', $item['menu_name']);
  3072. $query->orderBy('depth', 'DESC');
  3073. $query->range(0, 1);
  3074. $i = 1;
  3075. $p = 'p1';
  3076. while ($i <= MENU_MAX_DEPTH && $item[$p]) {
  3077. $query->condition($p, $item[$p]);
  3078. $p = 'p' . ++$i;
  3079. }
  3080. $max_depth = $query->execute()->fetchField();
  3081. return ($max_depth > $item['depth']) ? $max_depth - $item['depth'] : 0;
  3082. }
  3083. /**
  3084. * Update the children of a menu link that's being moved.
  3085. *
  3086. * The menu name, parents (p1 - p6), and depth are updated for all children of
  3087. * the link, and the has_children status of the previous parent is updated.
  3088. */
  3089. function _menu_link_move_children($item, $existing_item) {
  3090. $query = db_update('menu_links');
  3091. $query->fields(array('menu_name' => $item['menu_name']));
  3092. $p = 'p1';
  3093. $expressions = array();
  3094. for ($i = 1; $i <= $item['depth']; $p = 'p' . ++$i) {
  3095. $expressions[] = array($p, ":p_$i", array(":p_$i" => $item[$p]));
  3096. }
  3097. $j = $existing_item['depth'] + 1;
  3098. while ($i <= MENU_MAX_DEPTH && $j <= MENU_MAX_DEPTH) {
  3099. $expressions[] = array('p' . $i++, 'p' . $j++, array());
  3100. }
  3101. while ($i <= MENU_MAX_DEPTH) {
  3102. $expressions[] = array('p' . $i++, 0, array());
  3103. }
  3104. $shift = $item['depth'] - $existing_item['depth'];
  3105. if ($shift > 0) {
  3106. // The order of expressions must be reversed so the new values don't
  3107. // overwrite the old ones before they can be used because "Single-table
  3108. // UPDATE assignments are generally evaluated from left to right"
  3109. // see: http://dev.mysql.com/doc/refman/5.0/en/update.html
  3110. $expressions = array_reverse($expressions);
  3111. }
  3112. foreach ($expressions as $expression) {
  3113. $query->expression($expression[0], $expression[1], $expression[2]);
  3114. }
  3115. $query->expression('depth', 'depth + :depth', array(':depth' => $shift));
  3116. $query->condition('menu_name', $existing_item['menu_name']);
  3117. $p = 'p1';
  3118. for ($i = 1; $i <= MENU_MAX_DEPTH && $existing_item[$p]; $p = 'p' . ++$i) {
  3119. $query->condition($p, $existing_item[$p]);
  3120. }
  3121. $query->execute();
  3122. // Check the has_children status of the parent, while excluding this item.
  3123. _menu_update_parental_status($existing_item, TRUE);
  3124. }
  3125. /**
  3126. * Check and update the has_children status for the parent of a link.
  3127. */
  3128. function _menu_update_parental_status($item, $exclude = FALSE) {
  3129. // If plid == 0, there is nothing to update.
  3130. if ($item['plid']) {
  3131. // Check if at least one visible child exists in the table.
  3132. $query = db_select('menu_links');
  3133. $query->addField('menu_links', 'mlid');
  3134. $query->condition('menu_name', $item['menu_name']);
  3135. $query->condition('hidden', 0);
  3136. $query->condition('plid', $item['plid']);
  3137. $query->range(0, 1);
  3138. if ($exclude) {
  3139. $query->condition('mlid', $item['mlid'], '<>');
  3140. }
  3141. $parent_has_children = ((bool) $query->execute()->fetchField()) ? 1 : 0;
  3142. db_update('menu_links')
  3143. ->fields(array('has_children' => $parent_has_children))
  3144. ->condition('mlid', $item['plid'])
  3145. ->execute();
  3146. }
  3147. }
  3148. /**
  3149. * Helper function that sets the p1..p9 values for a menu link being saved.
  3150. */
  3151. function _menu_link_parents_set(&$item, $parent) {
  3152. $i = 1;
  3153. while ($i < $item['depth']) {
  3154. $p = 'p' . $i++;
  3155. $item[$p] = $parent[$p];
  3156. }
  3157. $p = 'p' . $i++;
  3158. // The parent (p1 - p9) corresponding to the depth always equals the mlid.
  3159. $item[$p] = $item['mlid'];
  3160. while ($i <= MENU_MAX_DEPTH) {
  3161. $p = 'p' . $i++;
  3162. $item[$p] = 0;
  3163. }
  3164. }
  3165. /**
  3166. * Helper function to build the router table based on the data from hook_menu.
  3167. */
  3168. function _menu_router_build($callbacks) {
  3169. // First pass: separate callbacks from paths, making paths ready for
  3170. // matching. Calculate fitness, and fill some default values.
  3171. $menu = array();
  3172. $masks = array();
  3173. foreach ($callbacks as $path => $item) {
  3174. $load_functions = array();
  3175. $to_arg_functions = array();
  3176. $fit = 0;
  3177. $move = FALSE;
  3178. $parts = explode('/', $path, MENU_MAX_PARTS);
  3179. $number_parts = count($parts);
  3180. // We store the highest index of parts here to save some work in the fit
  3181. // calculation loop.
  3182. $slashes = $number_parts - 1;
  3183. // Extract load and to_arg functions.
  3184. foreach ($parts as $k => $part) {
  3185. $match = FALSE;
  3186. // Look for wildcards in the form allowed to be used in PHP functions,
  3187. // because we are using these to construct the load function names.
  3188. if (preg_match('/^%(|' . DRUPAL_PHP_FUNCTION_PATTERN . ')$/', $part, $matches)) {
  3189. if (empty($matches[1])) {
  3190. $match = TRUE;
  3191. $load_functions[$k] = NULL;
  3192. }
  3193. else {
  3194. if (function_exists($matches[1] . '_to_arg')) {
  3195. $to_arg_functions[$k] = $matches[1] . '_to_arg';
  3196. $load_functions[$k] = NULL;
  3197. $match = TRUE;
  3198. }
  3199. if (function_exists($matches[1] . '_load')) {
  3200. $function = $matches[1] . '_load';
  3201. // Create an array of arguments that will be passed to the _load
  3202. // function when this menu path is checked, if 'load arguments'
  3203. // exists.
  3204. $load_functions[$k] = isset($item['load arguments']) ? array($function => $item['load arguments']) : $function;
  3205. $match = TRUE;
  3206. }
  3207. }
  3208. }
  3209. if ($match) {
  3210. $parts[$k] = '%';
  3211. }
  3212. else {
  3213. $fit |= 1 << ($slashes - $k);
  3214. }
  3215. }
  3216. if ($fit) {
  3217. $move = TRUE;
  3218. }
  3219. else {
  3220. // If there is no %, it fits maximally.
  3221. $fit = (1 << $number_parts) - 1;
  3222. }
  3223. $masks[$fit] = 1;
  3224. $item['_load_functions'] = $load_functions;
  3225. $item['to_arg_functions'] = empty($to_arg_functions) ? '' : serialize($to_arg_functions);
  3226. $item += array(
  3227. 'title' => '',
  3228. 'weight' => 0,
  3229. 'type' => MENU_NORMAL_ITEM,
  3230. 'module' => '',
  3231. '_number_parts' => $number_parts,
  3232. '_parts' => $parts,
  3233. '_fit' => $fit,
  3234. );
  3235. $item += array(
  3236. '_visible' => (bool) ($item['type'] & MENU_VISIBLE_IN_BREADCRUMB),
  3237. '_tab' => (bool) ($item['type'] & MENU_IS_LOCAL_TASK),
  3238. );
  3239. if ($move) {
  3240. $new_path = implode('/', $item['_parts']);
  3241. $menu[$new_path] = $item;
  3242. $sort[$new_path] = $number_parts;
  3243. }
  3244. else {
  3245. $menu[$path] = $item;
  3246. $sort[$path] = $number_parts;
  3247. }
  3248. }
  3249. array_multisort($sort, SORT_NUMERIC, $menu);
  3250. // Apply inheritance rules.
  3251. foreach ($menu as $path => $v) {
  3252. $item = &$menu[$path];
  3253. if (!$item['_tab']) {
  3254. // Non-tab items.
  3255. $item['tab_parent'] = '';
  3256. $item['tab_root'] = $path;
  3257. }
  3258. // If not specified, assign the default tab type for local tasks.
  3259. elseif (!isset($item['context'])) {
  3260. $item['context'] = MENU_CONTEXT_PAGE;
  3261. }
  3262. for ($i = $item['_number_parts'] - 1; $i; $i--) {
  3263. $parent_path = implode('/', array_slice($item['_parts'], 0, $i));
  3264. if (isset($menu[$parent_path])) {
  3265. $parent = &$menu[$parent_path];
  3266. // If we have no menu name, try to inherit it from parent items.
  3267. if (!isset($item['menu_name'])) {
  3268. // If the parent item of this item does not define a menu name (and no
  3269. // previous iteration assigned one already), try to find the menu name
  3270. // of the parent item in the currently stored menu links.
  3271. if (!isset($parent['menu_name'])) {
  3272. $menu_name = db_query("SELECT menu_name FROM {menu_links} WHERE router_path = :router_path AND module = 'system'", array(':router_path' => $parent_path))->fetchField();
  3273. if ($menu_name) {
  3274. $parent['menu_name'] = $menu_name;
  3275. }
  3276. }
  3277. // If the parent item defines a menu name, inherit it.
  3278. if (!empty($parent['menu_name'])) {
  3279. $item['menu_name'] = $parent['menu_name'];
  3280. }
  3281. }
  3282. if (!isset($item['tab_parent'])) {
  3283. // Parent stores the parent of the path.
  3284. $item['tab_parent'] = $parent_path;
  3285. }
  3286. if (!isset($item['tab_root']) && !$parent['_tab']) {
  3287. $item['tab_root'] = $parent_path;
  3288. }
  3289. // If an access callback is not found for a default local task we use
  3290. // the callback from the parent, since we expect them to be identical.
  3291. // In all other cases, the access parameters must be specified.
  3292. if (($item['type'] == MENU_DEFAULT_LOCAL_TASK) && !isset($item['access callback']) && isset($parent['access callback'])) {
  3293. $item['access callback'] = $parent['access callback'];
  3294. if (!isset($item['access arguments']) && isset($parent['access arguments'])) {
  3295. $item['access arguments'] = $parent['access arguments'];
  3296. }
  3297. }
  3298. // Same for page callbacks.
  3299. if (!isset($item['page callback']) && isset($parent['page callback'])) {
  3300. $item['page callback'] = $parent['page callback'];
  3301. if (!isset($item['page arguments']) && isset($parent['page arguments'])) {
  3302. $item['page arguments'] = $parent['page arguments'];
  3303. }
  3304. if (!isset($item['file path']) && isset($parent['file path'])) {
  3305. $item['file path'] = $parent['file path'];
  3306. }
  3307. if (!isset($item['file']) && isset($parent['file'])) {
  3308. $item['file'] = $parent['file'];
  3309. if (empty($item['file path']) && isset($item['module']) && isset($parent['module']) && $item['module'] != $parent['module']) {
  3310. $item['file path'] = drupal_get_path('module', $parent['module']);
  3311. }
  3312. }
  3313. }
  3314. // Same for delivery callbacks.
  3315. if (!isset($item['delivery callback']) && isset($parent['delivery callback'])) {
  3316. $item['delivery callback'] = $parent['delivery callback'];
  3317. }
  3318. // Same for theme callbacks.
  3319. if (!isset($item['theme callback']) && isset($parent['theme callback'])) {
  3320. $item['theme callback'] = $parent['theme callback'];
  3321. if (!isset($item['theme arguments']) && isset($parent['theme arguments'])) {
  3322. $item['theme arguments'] = $parent['theme arguments'];
  3323. }
  3324. }
  3325. // Same for load arguments: if a loader doesn't have any explict
  3326. // arguments, try to find arguments in the parent.
  3327. if (!isset($item['load arguments'])) {
  3328. foreach ($item['_load_functions'] as $k => $function) {
  3329. // This loader doesn't have any explict arguments...
  3330. if (!is_array($function)) {
  3331. // ... check the parent for a loader at the same position
  3332. // using the same function name and defining arguments...
  3333. if (isset($parent['_load_functions'][$k]) && is_array($parent['_load_functions'][$k]) && key($parent['_load_functions'][$k]) === $function) {
  3334. // ... and inherit the arguments on the child.
  3335. $item['_load_functions'][$k] = $parent['_load_functions'][$k];
  3336. }
  3337. }
  3338. }
  3339. }
  3340. }
  3341. }
  3342. if (!isset($item['access callback']) && isset($item['access arguments'])) {
  3343. // Default callback.
  3344. $item['access callback'] = 'user_access';
  3345. }
  3346. if (!isset($item['access callback']) || empty($item['page callback'])) {
  3347. $item['access callback'] = 0;
  3348. }
  3349. if (is_bool($item['access callback'])) {
  3350. $item['access callback'] = intval($item['access callback']);
  3351. }
  3352. $item['load_functions'] = empty($item['_load_functions']) ? '' : serialize($item['_load_functions']);
  3353. $item += array(
  3354. 'access arguments' => array(),
  3355. 'access callback' => '',
  3356. 'page arguments' => array(),
  3357. 'page callback' => '',
  3358. 'delivery callback' => '',
  3359. 'title arguments' => array(),
  3360. 'title callback' => 't',
  3361. 'theme arguments' => array(),
  3362. 'theme callback' => '',
  3363. 'description' => '',
  3364. 'position' => '',
  3365. 'context' => 0,
  3366. 'tab_parent' => '',
  3367. 'tab_root' => $path,
  3368. 'path' => $path,
  3369. 'file' => '',
  3370. 'file path' => '',
  3371. 'include file' => '',
  3372. );
  3373. // Calculate out the file to be included for each callback, if any.
  3374. if ($item['file']) {
  3375. $file_path = $item['file path'] ? $item['file path'] : drupal_get_path('module', $item['module']);
  3376. $item['include file'] = $file_path . '/' . $item['file'];
  3377. }
  3378. }
  3379. // Sort the masks so they are in order of descending fit.
  3380. $masks = array_keys($masks);
  3381. rsort($masks);
  3382. return array($menu, $masks);
  3383. }
  3384. /**
  3385. * Helper function to save data from menu_router_build() to the router table.
  3386. */
  3387. function _menu_router_save($menu, $masks) {
  3388. // Delete the existing router since we have some data to replace it.
  3389. db_truncate('menu_router')->execute();
  3390. // Prepare insert object.
  3391. $insert = db_insert('menu_router')
  3392. ->fields(array(
  3393. 'path',
  3394. 'load_functions',
  3395. 'to_arg_functions',
  3396. 'access_callback',
  3397. 'access_arguments',
  3398. 'page_callback',
  3399. 'page_arguments',
  3400. 'delivery_callback',
  3401. 'fit',
  3402. 'number_parts',
  3403. 'context',
  3404. 'tab_parent',
  3405. 'tab_root',
  3406. 'title',
  3407. 'title_callback',
  3408. 'title_arguments',
  3409. 'theme_callback',
  3410. 'theme_arguments',
  3411. 'type',
  3412. 'description',
  3413. 'position',
  3414. 'weight',
  3415. 'include_file',
  3416. ));
  3417. $num_records = 0;
  3418. foreach ($menu as $path => $item) {
  3419. // Fill in insert object values.
  3420. $insert->values(array(
  3421. 'path' => $item['path'],
  3422. 'load_functions' => $item['load_functions'],
  3423. 'to_arg_functions' => $item['to_arg_functions'],
  3424. 'access_callback' => $item['access callback'],
  3425. 'access_arguments' => serialize($item['access arguments']),
  3426. 'page_callback' => $item['page callback'],
  3427. 'page_arguments' => serialize($item['page arguments']),
  3428. 'delivery_callback' => $item['delivery callback'],
  3429. 'fit' => $item['_fit'],
  3430. 'number_parts' => $item['_number_parts'],
  3431. 'context' => $item['context'],
  3432. 'tab_parent' => $item['tab_parent'],
  3433. 'tab_root' => $item['tab_root'],
  3434. 'title' => $item['title'],
  3435. 'title_callback' => $item['title callback'],
  3436. 'title_arguments' => ($item['title arguments'] ? serialize($item['title arguments']) : ''),
  3437. 'theme_callback' => $item['theme callback'],
  3438. 'theme_arguments' => serialize($item['theme arguments']),
  3439. 'type' => $item['type'],
  3440. 'description' => $item['description'],
  3441. 'position' => $item['position'],
  3442. 'weight' => $item['weight'],
  3443. 'include_file' => $item['include file'],
  3444. ));
  3445. // Execute in batches to avoid the memory overhead of all of those records
  3446. // in the query object.
  3447. if (++$num_records == 20) {
  3448. $insert->execute();
  3449. $num_records = 0;
  3450. }
  3451. }
  3452. // Insert any remaining records.
  3453. $insert->execute();
  3454. // Store the masks.
  3455. variable_set('menu_masks', $masks);
  3456. return $menu;
  3457. }
  3458. /**
  3459. * Checks whether the site is in maintenance mode.
  3460. *
  3461. * This function will log the current user out and redirect to front page
  3462. * if the current user has no 'access site in maintenance mode' permission.
  3463. *
  3464. * @param $check_only
  3465. * If this is set to TRUE, the function will perform the access checks and
  3466. * return the site offline status, but not log the user out or display any
  3467. * messages.
  3468. *
  3469. * @return
  3470. * FALSE if the site is not in maintenance mode, the user login page is
  3471. * displayed, or the user has the 'access site in maintenance mode'
  3472. * permission. TRUE for anonymous users not being on the login page when the
  3473. * site is in maintenance mode.
  3474. */
  3475. function _menu_site_is_offline($check_only = FALSE) {
  3476. // Check if site is in maintenance mode.
  3477. if (variable_get('maintenance_mode', 0)) {
  3478. if (user_access('access site in maintenance mode')) {
  3479. // Ensure that the maintenance mode message is displayed only once
  3480. // (allowing for page redirects) and specifically suppress its display on
  3481. // the maintenance mode settings page.
  3482. if (!$check_only && $_GET['q'] != 'admin/config/development/maintenance') {
  3483. if (user_access('administer site configuration')) {
  3484. drupal_set_message(t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance'))), 'status', FALSE);
  3485. }
  3486. else {
  3487. drupal_set_message(t('Operating in maintenance mode.'), 'status', FALSE);
  3488. }
  3489. }
  3490. }
  3491. else {
  3492. return TRUE;
  3493. }
  3494. }
  3495. return FALSE;
  3496. }
  3497. /**
  3498. * @} End of "defgroup menu".
  3499. */