menu.inc

  1. drupal
    1. 4.6 includes/menu.inc
    2. 4.7 includes/menu.inc
    3. 5 includes/menu.inc
    4. 6 includes/menu.inc
    5. 7 includes/menu.inc
    6. 8 core/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_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_reset_static_cacheResets the menu system static cache.
menu_router_buildCollect and alter the menu definitions.
menu_router_rebuild(Re)populate the database tables used by various menu functions.
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 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_dataBuilds the data representing a menu tree.
menu_tree_get_pathGet the path for determining the active trail of the specified 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_tree_set_pathSet the path for determining the active trail of the specified menu tree.
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_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_PREFERRED_LINKReserved key to identify the most specific menu link for a given path.
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

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