menu.module

You are here

  1. 7 modules/menu/menu.module
  2. 4.6 modules/menu.module
  3. 4.7 modules/menu.module
  4. 5 modules/menu/menu.module
  5. 6 modules/menu/menu.module

Allows administrators to customize the site's navigation menus.

A menu (in this context) is a hierarchical collection of links, generally used for navigation. This is not to be confused with the Menu system of menu.inc and hook_menu(), which defines page routing requests for Drupal, and also allows the defined page routing URLs to be added to the main site navigation menu.

Functions

Namesort descending Description
menu_block_info Implements hook_block_info().
menu_block_view Implements hook_block_view().
menu_block_view_alter Implements hook_block_view_alter().
menu_delete Delete a custom menu and all contained links.
menu_enable Implements hook_enable().
menu_form_node_form_alter Implements hook_form_BASE_FORM_ID_alter().
menu_form_node_type_form_alter Implements hook_form_FORM_ID_alter().
menu_get_menus Return an associative array of the custom menus names.
menu_help Implements hook_help().
menu_load Load the data for a single custom menu.
menu_load_all Load all custom menu data.
menu_menu Implements hook_menu().
menu_node_delete Implements hook_node_delete().
menu_node_insert Implements hook_node_insert().
menu_node_prepare Implements hook_node_prepare().
menu_node_save Helper for hook_node_insert() and hook_node_update().
menu_node_submit Implements hook_node_submit().
menu_node_update Implements hook_node_update().
menu_overview_title Title callback for the menu overview page and links.
menu_parent_options Return a list of menu items that are valid possible parents for the given menu item.
menu_parent_options_js Page callback. Get all the available menus and menu items as a JavaScript array.
menu_permission Implements hook_permission().
menu_reset_item Reset a system-defined menu link.
menu_save Save a custom menu.
menu_theme Implements hook_theme().
_menu_get_options Helper function to get the items of the given menu.
_menu_parents_recurse Recursive helper function for menu_parent_options().
_menu_parent_depth_limit Find the depth limit for items in the parent select.

Constants

Namesort descending Description
MENU_MAX_MENU_NAME_LENGTH_UI Maximum length of menu name as entered by the user. Database length is 32 and we add a menu- prefix.

File

modules/menu/menu.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Allows administrators to customize the site's navigation menus.
  5. *
  6. * A menu (in this context) is a hierarchical collection of links, generally
  7. * used for navigation. This is not to be confused with the
  8. * @link menu Menu system @endlink of menu.inc and hook_menu(), which defines
  9. * page routing requests for Drupal, and also allows the defined page routing
  10. * URLs to be added to the main site navigation menu.
  11. */
  12. /**
  13. * Maximum length of menu name as entered by the user. Database length is 32
  14. * and we add a menu- prefix.
  15. */
  16. define('MENU_MAX_MENU_NAME_LENGTH_UI', 27);
  17. /**
  18. * Implements hook_help().
  19. */
  20. function menu_help($path, $arg) {
  21. switch ($path) {
  22. case 'admin/help#menu':
  23. $output = '';
  24. $output .= '<h3>' . t('About') . '</h3>';
  25. $output .= '<p>' . t('The Menu module provides an interface for managing menus. A menu is a hierarchical collection of links, which can be within or external to the site, generally used for navigation. Each menu is rendered in a block that can be enabled and positioned through the <a href="@blocks">Blocks administration page</a>. You can view and manage menus on the <a href="@menus">Menus administration page</a>. For more information, see the online handbook entry for the <a href="@menu">Menu module</a>.', array('@blocks' => url('admin/structure/block'), '@menus' => url('admin/structure/menu'), '@menu' => 'http://drupal.org/documentation/modules/menu/')) . '</p>';
  26. $output .= '<h3>' . t('Uses') . '</h3>';
  27. $output .= '<dl>';
  28. $output .= '<dt>' . t('Managing menus') . '</dt>';
  29. $output .= '<dd>' . t('Users with the <em>Administer menus and menu items</em> permission can add, edit and delete custom menus on the <a href="@menu">Menus administration page</a>. Custom menus can be special site menus, menus of external links, or any combination of internal and external links. You may create an unlimited number of additional menus, each of which will automatically have an associated block. By selecting <em>list links</em>, you can add, edit, or delete links for a given menu. The links listing page provides a drag-and-drop interface for controlling the order of links, and creating a hierarchy within the menu.', array('@menu' => url('admin/structure/menu'), '@add-menu' => url('admin/structure/menu/add'))) . '</dd>';
  30. $output .= '<dt>' . t('Displaying menus') . '</dt>';
  31. $output .= '<dd>' . t('After you have created a menu, you must enable and position the associated block on the <a href="@blocks">Blocks administration page</a>.', array('@blocks' => url('admin/structure/block'))) . '</dd>';
  32. $output .= '</dl>';
  33. return $output;
  34. case 'admin/structure/menu/add':
  35. return '<p>' . t('You can enable the newly-created block for this menu on the <a href="@blocks">Blocks administration page</a>.', array('@blocks' => url('admin/structure/block'))) . '</p>';
  36. }
  37. if ($path == 'admin/structure/menu' && module_exists('block')) {
  38. return '<p>' . t('Each menu has a corresponding block that is managed on the <a href="@blocks">Blocks administration page</a>.', array('@blocks' => url('admin/structure/block'))) . '</p>';
  39. }
  40. }
  41. /**
  42. * Implements hook_permission().
  43. */
  44. function menu_permission() {
  45. return array(
  46. 'administer menu' => array(
  47. 'title' => t('Administer menus and menu items'),
  48. ),
  49. );
  50. }
  51. /**
  52. * Implements hook_menu().
  53. */
  54. function menu_menu() {
  55. $items['admin/structure/menu'] = array(
  56. 'title' => 'Menus',
  57. 'description' => 'Add new menus to your site, edit existing menus, and rename and reorganize menu links.',
  58. 'page callback' => 'menu_overview_page',
  59. 'access callback' => 'user_access',
  60. 'access arguments' => array('administer menu'),
  61. 'file' => 'menu.admin.inc',
  62. );
  63. $items['admin/structure/menu/parents'] = array(
  64. 'title' => 'Parent menu items',
  65. 'page callback' => 'menu_parent_options_js',
  66. 'type' => MENU_CALLBACK,
  67. 'access arguments' => array(TRUE),
  68. );
  69. $items['admin/structure/menu/list'] = array(
  70. 'title' => 'List menus',
  71. 'type' => MENU_DEFAULT_LOCAL_TASK,
  72. 'weight' => -10,
  73. );
  74. $items['admin/structure/menu/add'] = array(
  75. 'title' => 'Add menu',
  76. 'page callback' => 'drupal_get_form',
  77. 'page arguments' => array('menu_edit_menu', 'add'),
  78. 'access arguments' => array('administer menu'),
  79. 'type' => MENU_LOCAL_ACTION,
  80. 'file' => 'menu.admin.inc',
  81. );
  82. $items['admin/structure/menu/settings'] = array(
  83. 'title' => 'Settings',
  84. 'page callback' => 'drupal_get_form',
  85. 'page arguments' => array('menu_configure'),
  86. 'access arguments' => array('administer menu'),
  87. 'type' => MENU_LOCAL_TASK,
  88. 'weight' => 5,
  89. 'file' => 'menu.admin.inc',
  90. );
  91. $items['admin/structure/menu/manage/%menu'] = array(
  92. 'title' => 'Customize menu',
  93. 'page callback' => 'drupal_get_form',
  94. 'page arguments' => array('menu_overview_form', 4),
  95. 'title callback' => 'menu_overview_title',
  96. 'title arguments' => array(4),
  97. 'access arguments' => array('administer menu'),
  98. 'file' => 'menu.admin.inc',
  99. );
  100. $items['admin/structure/menu/manage/%menu/list'] = array(
  101. 'title' => 'List links',
  102. 'weight' => -10,
  103. 'type' => MENU_DEFAULT_LOCAL_TASK,
  104. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  105. );
  106. $items['admin/structure/menu/manage/%menu/add'] = array(
  107. 'title' => 'Add link',
  108. 'page callback' => 'drupal_get_form',
  109. 'page arguments' => array('menu_edit_item', 'add', NULL, 4),
  110. 'access arguments' => array('administer menu'),
  111. 'type' => MENU_LOCAL_ACTION,
  112. 'file' => 'menu.admin.inc',
  113. );
  114. $items['admin/structure/menu/manage/%menu/edit'] = array(
  115. 'title' => 'Edit menu',
  116. 'page callback' => 'drupal_get_form',
  117. 'page arguments' => array('menu_edit_menu', 'edit', 4),
  118. 'access arguments' => array('administer menu'),
  119. 'type' => MENU_LOCAL_TASK,
  120. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  121. 'file' => 'menu.admin.inc',
  122. );
  123. $items['admin/structure/menu/manage/%menu/delete'] = array(
  124. 'title' => 'Delete menu',
  125. 'page callback' => 'menu_delete_menu_page',
  126. 'page arguments' => array(4),
  127. 'access arguments' => array('administer menu'),
  128. 'file' => 'menu.admin.inc',
  129. );
  130. $items['admin/structure/menu/item/%menu_link/edit'] = array(
  131. 'title' => 'Edit menu link',
  132. 'page callback' => 'drupal_get_form',
  133. 'page arguments' => array('menu_edit_item', 'edit', 4, NULL),
  134. 'access arguments' => array('administer menu'),
  135. 'file' => 'menu.admin.inc',
  136. );
  137. $items['admin/structure/menu/item/%menu_link/reset'] = array(
  138. 'title' => 'Reset menu link',
  139. 'page callback' => 'drupal_get_form',
  140. 'page arguments' => array('menu_reset_item_confirm', 4),
  141. 'access arguments' => array('administer menu'),
  142. 'file' => 'menu.admin.inc',
  143. );
  144. $items['admin/structure/menu/item/%menu_link/delete'] = array(
  145. 'title' => 'Delete menu link',
  146. 'page callback' => 'menu_item_delete_page',
  147. 'page arguments' => array(4),
  148. 'access arguments' => array('administer menu'),
  149. 'file' => 'menu.admin.inc',
  150. );
  151. return $items;
  152. }
  153. /**
  154. * Implements hook_theme().
  155. */
  156. function menu_theme() {
  157. return array(
  158. 'menu_overview_form' => array(
  159. 'file' => 'menu.admin.inc',
  160. 'render element' => 'form',
  161. ),
  162. 'menu_admin_overview' => array(
  163. 'file' => 'menu.admin.inc',
  164. 'variables' => array('title' => NULL, 'name' => NULL, 'description' => NULL),
  165. ),
  166. );
  167. }
  168. /**
  169. * Implements hook_enable().
  170. *
  171. * Add a link for each custom menu.
  172. */
  173. function menu_enable() {
  174. menu_rebuild();
  175. $base_link = db_query("SELECT mlid AS plid, menu_name FROM {menu_links} WHERE link_path = 'admin/structure/menu' AND module = 'system'")->fetchAssoc();
  176. $base_link['router_path'] = 'admin/structure/menu/manage/%';
  177. $base_link['module'] = 'menu';
  178. $result = db_query("SELECT * FROM {menu_custom}", array(), array('fetch' => PDO::FETCH_ASSOC));
  179. foreach ($result as $menu) {
  180. // $link is passed by reference to menu_link_save(), so we make a copy of $base_link.
  181. $link = $base_link;
  182. $link['mlid'] = 0;
  183. $link['link_title'] = $menu['title'];
  184. $link['link_path'] = 'admin/structure/menu/manage/' . $menu['menu_name'];
  185. $menu_link = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path AND plid = :plid", array(
  186. ':path' => $link['link_path'],
  187. ':plid' => $link['plid']
  188. ))
  189. ->fetchField();
  190. if (!$menu_link) {
  191. menu_link_save($link);
  192. }
  193. }
  194. menu_cache_clear_all();
  195. }
  196. /**
  197. * Title callback for the menu overview page and links.
  198. */
  199. function menu_overview_title($menu) {
  200. return $menu['title'];
  201. }
  202. /**
  203. * Load the data for a single custom menu.
  204. *
  205. * @param $menu_name
  206. * The unique name of a custom menu to load.
  207. * @return
  208. * Array defining the custom menu, or FALSE if the menu doesn't exist.
  209. */
  210. function menu_load($menu_name) {
  211. $all_menus = menu_load_all();
  212. return isset($all_menus[$menu_name]) ? $all_menus[$menu_name] : FALSE;
  213. }
  214. /**
  215. * Load all custom menu data.
  216. *
  217. * @return
  218. * Array of custom menu data.
  219. */
  220. function menu_load_all() {
  221. $custom_menus = &drupal_static(__FUNCTION__);
  222. if (!isset($custom_menus)) {
  223. if ($cached = cache_get('menu_custom', 'cache_menu')) {
  224. $custom_menus = $cached->data;
  225. }
  226. else {
  227. $custom_menus = db_query('SELECT * FROM {menu_custom}')->fetchAllAssoc('menu_name', PDO::FETCH_ASSOC);
  228. cache_set('menu_custom', $custom_menus, 'cache_menu');
  229. }
  230. }
  231. return $custom_menus;
  232. }
  233. /**
  234. * Save a custom menu.
  235. *
  236. * @param $menu
  237. * An array representing a custom menu:
  238. * - menu_name: The unique name of the custom menu (composed of lowercase
  239. * letters, numbers, and hyphens).
  240. * - title: The human readable menu title.
  241. * - description: The custom menu description.
  242. *
  243. * Modules should always pass a fully populated $menu when saving a custom
  244. * menu, so other modules are able to output proper status or watchdog messages.
  245. *
  246. * @see menu_load()
  247. */
  248. function menu_save($menu) {
  249. $status = db_merge('menu_custom')
  250. ->key(array('menu_name' => $menu['menu_name']))
  251. ->fields(array(
  252. 'title' => $menu['title'],
  253. 'description' => $menu['description'],
  254. ))
  255. ->execute();
  256. menu_cache_clear_all();
  257. switch ($status) {
  258. case SAVED_NEW:
  259. // Make sure the menu is present in the active menus variable so that its
  260. // items may appear in the menu active trail.
  261. // @see menu_set_active_menu_names()
  262. $active_menus = variable_get('menu_default_active_menus', array_keys(menu_get_menus()));
  263. if (!in_array($menu['menu_name'], $active_menus)) {
  264. $active_menus[] = $menu['menu_name'];
  265. variable_set('menu_default_active_menus', $active_menus);
  266. }
  267. module_invoke_all('menu_insert', $menu);
  268. break;
  269. case SAVED_UPDATED:
  270. module_invoke_all('menu_update', $menu);
  271. break;
  272. }
  273. }
  274. /**
  275. * Delete a custom menu and all contained links.
  276. *
  277. * Note that this function deletes all menu links in a custom menu. While menu
  278. * links derived from router paths may be restored by rebuilding the menu, all
  279. * customized and custom links will be irreversibly gone. Therefore, this
  280. * function should usually be called from a user interface (form submit) handler
  281. * only, which allows the user to confirm the action.
  282. *
  283. * @param $menu
  284. * An array representing a custom menu:
  285. * - menu_name: The unique name of the custom menu.
  286. * - title: The human readable menu title.
  287. * - description: The custom menu description.
  288. *
  289. * Modules should always pass a fully populated $menu when deleting a custom
  290. * menu, so other modules are able to output proper status or watchdog messages.
  291. *
  292. * @see menu_load()
  293. *
  294. * menu_delete_links() will take care of clearing the page cache. Other modules
  295. * should take care of their menu-related data by implementing
  296. * hook_menu_delete().
  297. */
  298. function menu_delete($menu) {
  299. // Delete all links from the menu.
  300. menu_delete_links($menu['menu_name']);
  301. // Remove menu from active menus variable.
  302. $active_menus = variable_get('menu_default_active_menus', array_keys(menu_get_menus()));
  303. foreach ($active_menus as $i => $menu_name) {
  304. if ($menu['menu_name'] == $menu_name) {
  305. unset($active_menus[$i]);
  306. variable_set('menu_default_active_menus', $active_menus);
  307. }
  308. }
  309. // Delete the custom menu.
  310. db_delete('menu_custom')
  311. ->condition('menu_name', $menu['menu_name'])
  312. ->execute();
  313. menu_cache_clear_all();
  314. module_invoke_all('menu_delete', $menu);
  315. }
  316. /**
  317. * Return a list of menu items that are valid possible parents for the given menu item.
  318. *
  319. * @param $menus
  320. * An array of menu names and titles, such as from menu_get_menus().
  321. * @param $item
  322. * The menu item or the node type for which to generate a list of parents.
  323. * If $item['mlid'] == 0 then the complete tree is returned.
  324. * @param $type
  325. * The node type for which to generate a list of parents.
  326. * If $item itself is a node type then $type is ignored.
  327. * @return
  328. * An array of menu link titles keyed on the a string containing the menu name
  329. * and mlid. The list excludes the given item and its children.
  330. *
  331. * @todo This has to be turned into a #process form element callback. The
  332. * 'menu_override_parent_selector' variable is entirely superfluous.
  333. */
  334. function menu_parent_options($menus, $item, $type = '') {
  335. // The menu_links table can be practically any size and we need a way to
  336. // allow contrib modules to provide more scalable pattern choosers.
  337. // hook_form_alter is too late in itself because all the possible parents are
  338. // retrieved here, unless menu_override_parent_selector is set to TRUE.
  339. if (variable_get('menu_override_parent_selector', FALSE)) {
  340. return array();
  341. }
  342. $available_menus = array();
  343. if (!is_array($item)) {
  344. // If $item is not an array then it is a node type.
  345. // Use it as $type and prepare a dummy menu item for _menu_get_options().
  346. $type = $item;
  347. $item = array('mlid' => 0);
  348. }
  349. if (empty($type)) {
  350. // If no node type is set, use all menus given to this function.
  351. $available_menus = $menus;
  352. }
  353. else {
  354. // If a node type is set, use all available menus for this type.
  355. $type_menus = variable_get('menu_options_' . $type, array('main-menu' => 'main-menu'));
  356. foreach ($type_menus as $menu) {
  357. $available_menus[$menu] = $menu;
  358. }
  359. }
  360. return _menu_get_options($menus, $available_menus, $item);
  361. }
  362. /**
  363. * Page callback.
  364. * Get all the available menus and menu items as a JavaScript array.
  365. */
  366. function menu_parent_options_js() {
  367. $available_menus = array();
  368. if (isset($_POST['menus']) && count($_POST['menus'])) {
  369. foreach ($_POST['menus'] as $menu) {
  370. $available_menus[$menu] = $menu;
  371. }
  372. }
  373. $options = _menu_get_options(menu_get_menus(), $available_menus, array('mlid' => 0));
  374. drupal_json_output($options);
  375. }
  376. /**
  377. * Helper function to get the items of the given menu.
  378. */
  379. function _menu_get_options($menus, $available_menus, $item) {
  380. // If the item has children, there is an added limit to the depth of valid parents.
  381. if (isset($item['parent_depth_limit'])) {
  382. $limit = $item['parent_depth_limit'];
  383. }
  384. else {
  385. $limit = _menu_parent_depth_limit($item);
  386. }
  387. $options = array();
  388. foreach ($menus as $menu_name => $title) {
  389. if (isset($available_menus[$menu_name])) {
  390. $tree = menu_tree_all_data($menu_name, NULL);
  391. $options[$menu_name . ':0'] = '<' . $title . '>';
  392. _menu_parents_recurse($tree, $menu_name, '--', $options, $item['mlid'], $limit);
  393. }
  394. }
  395. return $options;
  396. }
  397. /**
  398. * Recursive helper function for menu_parent_options().
  399. */
  400. function _menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude, $depth_limit) {
  401. foreach ($tree as $data) {
  402. if ($data['link']['depth'] > $depth_limit) {
  403. // Don't iterate through any links on this level.
  404. break;
  405. }
  406. if ($data['link']['mlid'] != $exclude && $data['link']['hidden'] >= 0) {
  407. $title = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, FALSE);
  408. if ($data['link']['hidden']) {
  409. $title .= ' (' . t('disabled') . ')';
  410. }
  411. $options[$menu_name . ':' . $data['link']['mlid']] = $title;
  412. if ($data['below']) {
  413. _menu_parents_recurse($data['below'], $menu_name, $indent . '--', $options, $exclude, $depth_limit);
  414. }
  415. }
  416. }
  417. }
  418. /**
  419. * Reset a system-defined menu link.
  420. */
  421. function menu_reset_item($link) {
  422. // To reset the link to its original values, we need to retrieve its
  423. // definition from hook_menu(). Otherwise, for example, the link's menu would
  424. // not be reset, because properties like the original 'menu_name' are not
  425. // stored anywhere else. Since resetting a link happens rarely and this is a
  426. // one-time operation, retrieving the full menu router does no harm.
  427. $menu = menu_get_router();
  428. $router_item = $menu[$link['router_path']];
  429. $new_link = _menu_link_build($router_item);
  430. // Merge existing menu link's ID and 'has_children' property.
  431. foreach (array('mlid', 'has_children') as $key) {
  432. $new_link[$key] = $link[$key];
  433. }
  434. menu_link_save($new_link);
  435. return $new_link;
  436. }
  437. /**
  438. * Implements hook_block_info().
  439. */
  440. function menu_block_info() {
  441. $menus = menu_get_menus(FALSE);
  442. $blocks = array();
  443. foreach ($menus as $name => $title) {
  444. $blocks[$name]['info'] = check_plain($title);
  445. // Menu blocks can't be cached because each menu item can have
  446. // a custom access callback. menu.inc manages its own caching.
  447. $blocks[$name]['cache'] = DRUPAL_NO_CACHE;
  448. }
  449. return $blocks;
  450. }
  451. /**
  452. * Implements hook_block_view().
  453. */
  454. function menu_block_view($delta = '') {
  455. $menus = menu_get_menus(FALSE);
  456. $data['subject'] = check_plain($menus[$delta]);
  457. $data['content'] = menu_tree($delta);
  458. // Add contextual links for this block.
  459. if (!empty($data['content'])) {
  460. $data['content']['#contextual_links']['menu'] = array('admin/structure/menu/manage', array($delta));
  461. }
  462. return $data;
  463. }
  464. /**
  465. * Implements hook_block_view_alter().
  466. */
  467. function menu_block_view_alter(&$data, $block) {
  468. // Add contextual links for system menu blocks.
  469. if ($block->module == 'system' && !empty($data['content'])) {
  470. $system_menus = menu_list_system_menus();
  471. if (isset($system_menus[$block->delta])) {
  472. $data['content']['#contextual_links']['menu'] = array('admin/structure/menu/manage', array($block->delta));
  473. }
  474. }
  475. }
  476. /**
  477. * Implements hook_node_insert().
  478. */
  479. function menu_node_insert($node) {
  480. menu_node_save($node);
  481. }
  482. /**
  483. * Implements hook_node_update().
  484. */
  485. function menu_node_update($node) {
  486. menu_node_save($node);
  487. }
  488. /**
  489. * Helper for hook_node_insert() and hook_node_update().
  490. */
  491. function menu_node_save($node) {
  492. if (isset($node->menu)) {
  493. $link = &$node->menu;
  494. if (empty($link['enabled'])) {
  495. if (!empty($link['mlid'])) {
  496. menu_link_delete($link['mlid']);
  497. }
  498. }
  499. elseif (trim($link['link_title'])) {
  500. $link['link_title'] = trim($link['link_title']);
  501. $link['link_path'] = "node/$node->nid";
  502. if (trim($link['description'])) {
  503. $link['options']['attributes']['title'] = trim($link['description']);
  504. }
  505. else {
  506. // If the description field was left empty, remove the title attribute
  507. // from the menu link.
  508. unset($link['options']['attributes']['title']);
  509. }
  510. if (!menu_link_save($link)) {
  511. drupal_set_message(t('There was an error saving the menu link.'), 'error');
  512. }
  513. }
  514. }
  515. }
  516. /**
  517. * Implements hook_node_delete().
  518. */
  519. function menu_node_delete($node) {
  520. // Delete all menu module links that point to this node.
  521. $result = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path AND module = 'menu'", array(':path' => 'node/' . $node->nid), array('fetch' => PDO::FETCH_ASSOC));
  522. foreach ($result as $m) {
  523. menu_link_delete($m['mlid']);
  524. }
  525. }
  526. /**
  527. * Implements hook_node_prepare().
  528. */
  529. function menu_node_prepare($node) {
  530. if (empty($node->menu)) {
  531. // Prepare the node for the edit form so that $node->menu always exists.
  532. $menu_name = strtok(variable_get('menu_parent_' . $node->type, 'main-menu:0'), ':');
  533. $item = array();
  534. if (isset($node->nid)) {
  535. $mlid = FALSE;
  536. // Give priority to the default menu
  537. $type_menus = variable_get('menu_options_' . $node->type, array('main-menu' => 'main-menu'));
  538. if (in_array($menu_name, $type_menus)) {
  539. $mlid = db_query_range("SELECT mlid FROM {menu_links} WHERE link_path = :path AND menu_name = :menu_name AND module = 'menu' ORDER BY mlid ASC", 0, 1, array(
  540. ':path' => 'node/' . $node->nid,
  541. ':menu_name' => $menu_name,
  542. ))->fetchField();
  543. }
  544. // Check all allowed menus if a link does not exist in the default menu.
  545. if (!$mlid && !empty($type_menus)) {
  546. $mlid = db_query_range("SELECT mlid FROM {menu_links} WHERE link_path = :path AND module = 'menu' AND menu_name IN (:type_menus) ORDER BY mlid ASC", 0, 1, array(
  547. ':path' => 'node/' . $node->nid,
  548. ':type_menus' => array_values($type_menus),
  549. ))->fetchField();
  550. }
  551. if ($mlid) {
  552. $item = menu_link_load($mlid);
  553. }
  554. }
  555. // Set default values.
  556. $node->menu = $item + array(
  557. 'link_title' => '',
  558. 'mlid' => 0,
  559. 'plid' => 0,
  560. 'menu_name' => $menu_name,
  561. 'weight' => 0,
  562. 'options' => array(),
  563. 'module' => 'menu',
  564. 'expanded' => 0,
  565. 'hidden' => 0,
  566. 'has_children' => 0,
  567. 'customized' => 0,
  568. );
  569. }
  570. // Find the depth limit for the parent select.
  571. if (!isset($node->menu['parent_depth_limit'])) {
  572. $node->menu['parent_depth_limit'] = _menu_parent_depth_limit($node->menu);
  573. }
  574. }
  575. /**
  576. * Find the depth limit for items in the parent select.
  577. */
  578. function _menu_parent_depth_limit($item) {
  579. return MENU_MAX_DEPTH - 1 - (($item['mlid'] && $item['has_children']) ? menu_link_children_relative_depth($item) : 0);
  580. }
  581. /**
  582. * Implements hook_form_BASE_FORM_ID_alter().
  583. *
  584. * Adds menu item fields to the node form.
  585. *
  586. * @see menu_node_submit()
  587. */
  588. function menu_form_node_form_alter(&$form, $form_state) {
  589. // Generate a list of possible parents (not including this link or descendants).
  590. // @todo This must be handled in a #process handler.
  591. $link = $form['#node']->menu;
  592. $type = $form['#node']->type;
  593. // menu_parent_options() is goofy and can actually handle either a menu link
  594. // or a node type both as second argument. Pick based on whether there is
  595. // a link already (menu_node_prepare() sets mlid default to 0).
  596. $options = menu_parent_options(menu_get_menus(), $link['mlid'] ? $link : $type, $type);
  597. // If no possible parent menu items were found, there is nothing to display.
  598. if (empty($options)) {
  599. return;
  600. }
  601. $form['menu'] = array(
  602. '#type' => 'fieldset',
  603. '#title' => t('Menu settings'),
  604. '#access' => user_access('administer menu'),
  605. '#collapsible' => TRUE,
  606. '#collapsed' => !$link['link_title'],
  607. '#group' => 'additional_settings',
  608. '#attached' => array(
  609. 'js' => array(drupal_get_path('module', 'menu') . '/menu.js'),
  610. ),
  611. '#tree' => TRUE,
  612. '#weight' => -2,
  613. '#attributes' => array('class' => array('menu-link-form')),
  614. );
  615. $form['menu']['enabled'] = array(
  616. '#type' => 'checkbox',
  617. '#title' => t('Provide a menu link'),
  618. '#default_value' => (int) (bool) $link['mlid'],
  619. );
  620. $form['menu']['link'] = array(
  621. '#type' => 'container',
  622. '#parents' => array('menu'),
  623. '#states' => array(
  624. 'invisible' => array(
  625. 'input[name="menu[enabled]"]' => array('checked' => FALSE),
  626. ),
  627. ),
  628. );
  629. // Populate the element with the link data.
  630. foreach (array('mlid', 'module', 'hidden', 'has_children', 'customized', 'options', 'expanded', 'hidden', 'parent_depth_limit') as $key) {
  631. $form['menu']['link'][$key] = array('#type' => 'value', '#value' => $link[$key]);
  632. }
  633. $form['menu']['link']['link_title'] = array(
  634. '#type' => 'textfield',
  635. '#title' => t('Menu link title'),
  636. '#default_value' => $link['link_title'],
  637. );
  638. $form['menu']['link']['description'] = array(
  639. '#type' => 'textarea',
  640. '#title' => t('Description'),
  641. '#default_value' => isset($link['options']['attributes']['title']) ? $link['options']['attributes']['title'] : '',
  642. '#rows' => 1,
  643. '#description' => t('Shown when hovering over the menu link.'),
  644. );
  645. $default = ($link['mlid'] ? $link['menu_name'] . ':' . $link['plid'] : variable_get('menu_parent_' . $type, 'main-menu:0'));
  646. // If the current parent menu item is not present in options, use the first
  647. // available option as default value.
  648. // @todo User should not be allowed to access menu link settings in such a
  649. // case.
  650. if (!isset($options[$default])) {
  651. $array = array_keys($options);
  652. $default = reset($array);
  653. }
  654. $form['menu']['link']['parent'] = array(
  655. '#type' => 'select',
  656. '#title' => t('Parent item'),
  657. '#default_value' => $default,
  658. '#options' => $options,
  659. '#attributes' => array('class' => array('menu-parent-select')),
  660. );
  661. $form['menu']['link']['weight'] = array(
  662. '#type' => 'weight',
  663. '#title' => t('Weight'),
  664. '#delta' => 50,
  665. '#default_value' => $link['weight'],
  666. '#description' => t('Menu links with smaller weights are displayed before links with larger weights.'),
  667. );
  668. }
  669. /**
  670. * Implements hook_node_submit().
  671. *
  672. * @see menu_form_node_form_alter()
  673. */
  674. function menu_node_submit($node, $form, $form_state) {
  675. // Decompose the selected menu parent option into 'menu_name' and 'plid', if
  676. // the form used the default parent selection widget.
  677. if (!empty($form_state['values']['menu']['parent'])) {
  678. list($node->menu['menu_name'], $node->menu['plid']) = explode(':', $form_state['values']['menu']['parent']);
  679. }
  680. }
  681. /**
  682. * Implements hook_form_FORM_ID_alter().
  683. *
  684. * Adds menu options to the node type form.
  685. */
  686. function menu_form_node_type_form_alter(&$form, $form_state) {
  687. $menu_options = menu_get_menus();
  688. $type = $form['#node_type'];
  689. $form['menu'] = array(
  690. '#type' => 'fieldset',
  691. '#title' => t('Menu settings'),
  692. '#collapsible' => TRUE,
  693. '#collapsed' => TRUE,
  694. '#attached' => array(
  695. 'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
  696. ),
  697. '#group' => 'additional_settings',
  698. );
  699. $form['menu']['menu_options'] = array(
  700. '#type' => 'checkboxes',
  701. '#title' => t('Available menus'),
  702. '#default_value' => variable_get('menu_options_' . $type->type, array('main-menu')),
  703. '#options' => $menu_options,
  704. '#description' => t('The menus available to place links in for this content type.'),
  705. );
  706. // To avoid an 'illegal option' error after saving the form we have to load
  707. // all available menu items.
  708. // Otherwise it is not possible to dynamically add options to the list.
  709. // @todo Convert menu_parent_options() into a #process callback.
  710. $options = menu_parent_options(menu_get_menus(), array('mlid' => 0));
  711. $form['menu']['menu_parent'] = array(
  712. '#type' => 'select',
  713. '#title' => t('Default parent item'),
  714. '#default_value' => variable_get('menu_parent_' . $type->type, 'main-menu:0'),
  715. '#options' => $options,
  716. '#description' => t('Choose the menu item to be the default parent for a new link in the content authoring form.'),
  717. '#attributes' => array('class' => array('menu-title-select')),
  718. );
  719. // Call Drupal.menu_update_parent_list() to filter the list of
  720. // available default parent menu items based on the selected menus.
  721. drupal_add_js(
  722. '(function ($) { Drupal.menu_update_parent_list(); })(jQuery);',
  723. array('scope' => 'footer', 'type' => 'inline')
  724. );
  725. }
  726. /**
  727. * Return an associative array of the custom menus names.
  728. *
  729. * @param $all
  730. * If FALSE return only user-added menus, or if TRUE also include
  731. * the menus defined by the system.
  732. * @return
  733. * An array with the machine-readable names as the keys, and human-readable
  734. * titles as the values.
  735. */
  736. function menu_get_menus($all = TRUE) {
  737. if ($custom_menus = menu_load_all()) {
  738. if (!$all) {
  739. $custom_menus = array_diff_key($custom_menus, menu_list_system_menus());
  740. }
  741. foreach ($custom_menus as $menu_name => $menu) {
  742. $custom_menus[$menu_name] = t($menu['title']);
  743. }
  744. asort($custom_menus);
  745. }
  746. return $custom_menus;
  747. }