menu.module 27.9 KB
Newer Older
1
2
<?php

Dries's avatar
   
Dries committed
3
4
/**
 * @file
5
6
7
8
9
10
11
 * 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
 * @link menu Menu system @endlink 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.
Dries's avatar
   
Dries committed
12
13
 */

14
15
16
17
/**
 * Maximum length of menu name as entered by the user. Database length is 32
 * and we add a menu- prefix.
 */
18
const MENU_MAX_MENU_NAME_LENGTH_UI = 27;
19

20
/**
21
 * Implements hook_help().
22
 */
23
24
function menu_help($path, $arg) {
  switch ($path) {
25
    case 'admin/help#menu':
26
27
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
28
      $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>';
29
30
31
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Managing menus') . '</dt>';
32
      $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>';
33
34
35
      $output .= '<dt>' . t('Displaying menus') . '</dt>';
      $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>';
      $output .= '</dl>';
36
      return $output;
37
    case 'admin/structure/menu/add':
38
      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>';
39
  }
40
  if ($path == 'admin/structure/menu' && module_exists('block')) {
41
    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>';
42
  }
43
44
}

45
/**
46
 * Implements hook_permission().
47
 */
48
function menu_permission() {
49
  return array(
50
    'administer menu' => array(
51
      'title' => t('Administer menus and menu items'),
52
    ),
53
  );
54
55
}

56
/**
57
 * Implements hook_menu().
58
 */
59
function menu_menu() {
60
  $items['admin/structure/menu'] = array(
61
    'title' => 'Menus',
62
    'description' => 'Add new menus to your site, edit existing menus, and rename and reorganize menu links.',
63
    'page callback' => 'menu_overview_page',
64
65
    'access callback' => 'user_access',
    'access arguments' => array('administer menu'),
66
    'file' => 'menu.admin.inc',
67
  );
68
69
70
71
72
73
  $items['admin/structure/menu/parents'] = array(
    'title' => 'Parent menu items',
    'page callback' => 'menu_parent_options_js',
    'type' => MENU_CALLBACK,
    'access arguments' => array(TRUE),
  );
74
  $items['admin/structure/menu/list'] = array(
75
    'title' => 'List menus',
76
    'type' => MENU_DEFAULT_LOCAL_TASK,
77
78
    'weight' => -10,
  );
79
  $items['admin/structure/menu/add'] = array(
80
81
82
    'title' => 'Add menu',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_edit_menu', 'add'),
83
    'access arguments' => array('administer menu'),
84
    'type' => MENU_LOCAL_ACTION,
85
    'file' => 'menu.admin.inc',
86
  );
87
  $items['admin/structure/menu/settings'] = array(
88
89
90
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_configure'),
91
    'access arguments' => array('administer menu'),
92
    'type' => MENU_LOCAL_TASK,
93
    'weight' => 5,
94
    'file' => 'menu.admin.inc',
95
  );
96
  $items['admin/structure/menu/manage/%menu'] = array(
97
    'title' => 'Customize menu',
98
    'page callback' => 'drupal_get_form',
99
    'page arguments' => array('menu_overview_form', 4),
100
    'title callback' => 'menu_overview_title',
101
    'title arguments' => array(4),
102
    'access arguments' => array('administer menu'),
103
    'file' => 'menu.admin.inc',
104
  );
105
  $items['admin/structure/menu/manage/%menu/list'] = array(
106
    'title' => 'List links',
107
    'weight' => -10,
108
    'type' => MENU_DEFAULT_LOCAL_TASK,
109
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
110
  );
111
  $items['admin/structure/menu/manage/%menu/add'] = array(
112
    'title' => 'Add link',
113
    'page callback' => 'drupal_get_form',
114
    'page arguments' => array('menu_edit_item', 'add', NULL, 4),
115
    'access arguments' => array('administer menu'),
116
    'type' => MENU_LOCAL_ACTION,
117
    'file' => 'menu.admin.inc',
118
  );
119
  $items['admin/structure/menu/manage/%menu/edit'] = array(
120
121
    'title' => 'Edit menu',
    'page callback' => 'drupal_get_form',
122
    'page arguments' => array('menu_edit_menu', 'edit', 4),
123
    'access arguments' => array('administer menu'),
124
    'type' => MENU_LOCAL_TASK,
125
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
126
    'file' => 'menu.admin.inc',
127
  );
128
  $items['admin/structure/menu/manage/%menu/delete'] = array(
129
130
    'title' => 'Delete menu',
    'page callback' => 'menu_delete_menu_page',
131
    'page arguments' => array(4),
132
    'access arguments' => array('administer menu'),
133
    'file' => 'menu.admin.inc',
134
  );
135
  $items['admin/structure/menu/item/%menu_link/edit'] = array(
136
    'title' => 'Edit menu link',
137
    'page callback' => 'drupal_get_form',
138
    'page arguments' => array('menu_edit_item', 'edit', 4, NULL),
139
    'access arguments' => array('administer menu'),
140
    'file' => 'menu.admin.inc',
141
  );
142
  $items['admin/structure/menu/item/%menu_link/reset'] = array(
143
    'title' => 'Reset menu link',
144
    'page callback' => 'drupal_get_form',
145
    'page arguments' => array('menu_reset_item_confirm', 4),
146
    'access arguments' => array('administer menu'),
147
    'file' => 'menu.admin.inc',
148
  );
149
  $items['admin/structure/menu/item/%menu_link/delete'] = array(
150
    'title' => 'Delete menu link',
151
152
    'page callback' => 'menu_item_delete_page',
    'page arguments' => array(4),
153
    'access arguments' => array('administer menu'),
154
    'file' => 'menu.admin.inc',
155
  );
156
  return $items;
157
}
158

159
/**
160
 * Implements hook_theme().
161
162
163
164
 */
function menu_theme() {
  return array(
    'menu_overview_form' => array(
165
      'file' => 'menu.admin.inc',
166
      'render element' => 'form',
167
    ),
168
    'menu_admin_overview' => array(
169
      'file' => 'menu.admin.inc',
170
      'variables' => array('title' => NULL, 'name' => NULL, 'description' => NULL),
171
    ),
172
173
174
  );
}

175
/**
176
 * Implements hook_enable().
177
 *
178
 * Add a link for each custom menu.
179
180
181
 */
function menu_enable() {
  menu_rebuild();
182
  $base_link = db_query("SELECT mlid AS plid, menu_name FROM {menu_links} WHERE link_path = 'admin/structure/menu' AND module = 'system'")->fetchAssoc();
183
  $base_link['router_path'] = 'admin/structure/menu/manage/%';
184
  $base_link['module'] = 'menu';
185
186
  $result = db_query("SELECT * FROM {menu_custom}", array(), array('fetch' => PDO::FETCH_ASSOC));
  foreach ($result as $menu) {
187
188
    // $link is passed by reference to menu_link_save(), so we make a copy of $base_link.
    $link = $base_link;
189
190
    $link['mlid'] = 0;
    $link['link_title'] = $menu['title'];
191
    $link['link_path'] = 'admin/structure/menu/manage/' . $menu['menu_name'];
192
193
194
195
196
197
    $menu_link = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path AND plid = :plid", array(
      ':path' => $link['link_path'],
      ':plid' => $link['plid']
    ))
    ->fetchField();
    if (!$menu_link) {
198
199
      menu_link_save($link);
    }
200
  }
201
  menu_cache_clear_all();
202
203
}

204
205
206
207
/**
 * Title callback for the menu overview page and links.
 */
function menu_overview_title($menu) {
Dries's avatar
Dries committed
208
  return $menu['title'];
209
210
}

211
212
/**
 * Load the data for a single custom menu.
213
214
215
 *
 * @param $menu_name
 *   The unique name of a custom menu to load.
216
217
 * @return
 *   Array defining the custom menu, or FALSE if the menu doesn't exist.
218
219
 */
function menu_load($menu_name) {
220
221
222
223
224
225
226
227
228
229
230
231
232
  $all_menus = menu_load_all();
  return isset($all_menus[$menu_name]) ? $all_menus[$menu_name] : FALSE;
}

/**
 * Load all custom menu data.
 *
 * @return
 *   Array of custom menu data.
 */
function menu_load_all() {
  $custom_menus = &drupal_static(__FUNCTION__);
  if (!isset($custom_menus)) {
233
    if ($cached = cache('menu')->get('menu_custom')) {
234
235
236
237
      $custom_menus = $cached->data;
    }
    else {
      $custom_menus = db_query('SELECT * FROM {menu_custom}')->fetchAllAssoc('menu_name', PDO::FETCH_ASSOC);
238
      cache('menu')->set('menu_custom', $custom_menus);
239
240
241
    }
  }
  return $custom_menus;
242
243
}

244
245
246
247
248
/**
 * Save a custom menu.
 *
 * @param $menu
 *   An array representing a custom menu:
249
250
 *   - menu_name: The unique name of the custom menu (composed of lowercase
 *     letters, numbers, and hyphens).
251
252
253
254
255
256
257
258
259
 *   - title: The human readable menu title.
 *   - description: The custom menu description.
 *
 * Modules should always pass a fully populated $menu when saving a custom
 * menu, so other modules are able to output proper status or watchdog messages.
 *
 * @see menu_load()
 */
function menu_save($menu) {
260
  $status = db_merge('menu_custom')
261
262
263
264
265
266
    ->key(array('menu_name' => $menu['menu_name']))
    ->fields(array(
      'title' => $menu['title'],
      'description' => $menu['description'],
    ))
    ->execute();
267
  menu_cache_clear_all();
268

269
270
  switch ($status) {
    case SAVED_NEW:
271
272
273
274
275
276
277
278
279
      // Make sure the menu is present in the active menus variable so that its
      // items may appear in the menu active trail.
      // @see menu_set_active_menu_names()
      $active_menus = variable_get('menu_default_active_menus', array_keys(menu_get_menus()));
      if (!in_array($menu['menu_name'], $active_menus)) {
        $active_menus[] = $menu['menu_name'];
        variable_set('menu_default_active_menus', $active_menus);
      }

280
281
282
283
284
285
      module_invoke_all('menu_insert', $menu);
      break;

    case SAVED_UPDATED:
      module_invoke_all('menu_update', $menu);
      break;
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
  }
}

/**
 * Delete a custom menu and all contained links.
 *
 * Note that this function deletes all menu links in a custom menu. While menu
 * links derived from router paths may be restored by rebuilding the menu, all
 * customized and custom links will be irreversibly gone. Therefore, this
 * function should usually be called from a user interface (form submit) handler
 * only, which allows the user to confirm the action.
 *
 * @param $menu
 *   An array representing a custom menu:
 *   - menu_name: The unique name of the custom menu.
 *   - title: The human readable menu title.
 *   - description: The custom menu description.
 *
 * Modules should always pass a fully populated $menu when deleting a custom
 * menu, so other modules are able to output proper status or watchdog messages.
 *
 * @see menu_load()
 *
309
 * menu_delete_links() will take care of clearing the page cache. Other modules
310
311
312
313
314
 * should take care of their menu-related data by implementing
 * hook_menu_delete().
 */
function menu_delete($menu) {
  // Delete all links from the menu.
315
  menu_delete_links($menu['menu_name']);
316

317
318
319
320
321
322
323
324
325
  // Remove menu from active menus variable.
  $active_menus = variable_get('menu_default_active_menus', array_keys(menu_get_menus()));
  foreach ($active_menus as $i => $menu_name) {
    if ($menu['menu_name'] == $menu_name) {
      unset($active_menus[$i]);
      variable_set('menu_default_active_menus', $active_menus);
    }
  }

326
327
328
329
330
  // Delete the custom menu.
  db_delete('menu_custom')
    ->condition('menu_name', $menu['menu_name'])
    ->execute();

331
  menu_cache_clear_all();
332
333
334
  module_invoke_all('menu_delete', $menu);
}

335
/**
336
 * Return a list of menu items that are valid possible parents for the given menu item.
337
 *
338
339
 * @param $menus
 *   An array of menu names and titles, such as from menu_get_menus().
340
 * @param $item
341
 *   The menu item or the node type for which to generate a list of parents.
342
 *   If $item['mlid'] == 0 then the complete tree is returned.
343
344
345
 * @param $type
 *   The node type for which to generate a list of parents.
 *   If $item itself is a node type then $type is ignored.
346
 * @return
347
348
 *   An array of menu link titles keyed on the a string containing the menu name
 *   and mlid. The list excludes the given item and its children.
349
350
351
 *
 * @todo This has to be turned into a #process form element callback. The
 *   'menu_override_parent_selector' variable is entirely superfluous.
352
 */
353
function menu_parent_options($menus, $item, $type = '') {
354
355
356
357
358
359
360
  // The menu_links table can be practically any size and we need a way to
  // allow contrib modules to provide more scalable pattern choosers.
  // hook_form_alter is too late in itself because all the possible parents are
  // retrieved here, unless menu_override_parent_selector is set to TRUE.
  if (variable_get('menu_override_parent_selector', FALSE)) {
    return array();
  }
361
362

  $available_menus = array();
363
364
365
366
367
368
369
370
  if (!is_array($item)) {
    // If $item is not an array then it is a node type.
    // Use it as $type and prepare a dummy menu item for _menu_get_options().
    $type = $item;
    $item = array('mlid' => 0);
  }
  if (empty($type)) {
    // If no node type is set, use all menus given to this function.
371
372
373
    $available_menus = $menus;
  }
  else {
374
375
    // If a node type is set, use all available menus for this type.
    $type_menus = variable_get('menu_options_' . $type, array('main-menu' => 'main-menu'));
376
377
378
379
380
381
382
383
384
385
    foreach ($type_menus as $menu) {
      $available_menus[$menu] = $menu;
    }
  }

  return _menu_get_options($menus, $available_menus, $item);
}

/**
 * Page callback.
386
 * Get all the available menus and menu items as a JavaScript array.
387
388
389
390
391
392
393
394
395
 */
function menu_parent_options_js() {
  $available_menus = array();
  if (isset($_POST['menus']) && count($_POST['menus'])) {
    foreach ($_POST['menus'] as $menu) {
      $available_menus[$menu] = $menu;
    }
  }
  $options = _menu_get_options(menu_get_menus(), $available_menus, array('mlid' => 0));
396
397

  drupal_json_output($options);
398
399
400
401
402
403
}

/**
 * Helper function to get the items of the given menu.
 */
function _menu_get_options($menus, $available_menus, $item) {
404
  // If the item has children, there is an added limit to the depth of valid parents.
405
406
407
408
409
410
  if (isset($item['parent_depth_limit'])) {
    $limit = $item['parent_depth_limit'];
  }
  else {
    $limit = _menu_parent_depth_limit($item);
  }
411

412
  $options = array();
413
  foreach ($menus as $menu_name => $title) {
414
415
416
417
418
    if (isset($available_menus[$menu_name])) {
      $tree = menu_tree_all_data($menu_name, NULL);
      $options[$menu_name . ':0'] = '<' . $title . '>';
      _menu_parents_recurse($tree, $menu_name, '--', $options, $item['mlid'], $limit);
    }
419
  }
420
  return $options;
421
422
423
}

/**
424
 * Recursive helper function for menu_parent_options().
425
 */
426
function _menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude, $depth_limit) {
427
  foreach ($tree as $data) {
428
429
430
431
    if ($data['link']['depth'] > $depth_limit) {
      // Don't iterate through any links on this level.
      break;
    }
432
    if ($data['link']['mlid'] != $exclude && $data['link']['hidden'] >= 0) {
433
      $title = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, FALSE);
434
      if ($data['link']['hidden']) {
435
        $title .= ' (' . t('disabled') . ')';
436
      }
437
      $options[$menu_name . ':' . $data['link']['mlid']] = $title;
438
      if ($data['below']) {
439
        _menu_parents_recurse($data['below'], $menu_name, $indent . '--', $options, $exclude, $depth_limit);
440
441
442
      }
    }
  }
443
444
}

445
/**
446
 * Reset a system-defined menu link.
447
 */
448
449
450
451
452
453
454
455
456
457
function menu_reset_item($link) {
  // To reset the link to its original values, we need to retrieve its
  // definition from hook_menu(). Otherwise, for example, the link's menu would
  // not be reset, because properties like the original 'menu_name' are not
  // stored anywhere else. Since resetting a link happens rarely and this is a
  // one-time operation, retrieving the full menu router does no harm.
  $menu = menu_get_router();
  $router_item = $menu[$link['router_path']];
  $new_link = _menu_link_build($router_item);
  // Merge existing menu link's ID and 'has_children' property.
458
  foreach (array('mlid', 'has_children') as $key) {
459
    $new_link[$key] = $link[$key];
460
  }
461
462
  menu_link_save($new_link);
  return $new_link;
463
464
}

465
/**
466
 * Implements hook_block_info().
467
 */
468
function menu_block_info() {
469
  $menus = menu_get_menus(FALSE);
470
471
472

  $blocks = array();
  foreach ($menus as $name => $title) {
473
    // Default "Navigation" block is handled by system.module.
474
475
476
    $blocks[$name]['info'] = check_plain($title);
    // Menu blocks can't be cached because each menu item can have
    // a custom access callback. menu.inc manages its own caching.
477
    $blocks[$name]['cache'] = DRUPAL_NO_CACHE;
478
  }
479
480
481
482
  return $blocks;
}

/**
483
 * Implements hook_block_view().
484
485
 */
function menu_block_view($delta = '') {
486
  $menus = menu_get_menus(FALSE);
487
488
  $data['subject'] = check_plain($menus[$delta]);
  $data['content'] = menu_tree($delta);
489
490
  // Add contextual links for this block.
  if (!empty($data['content'])) {
491
    $data['content']['#contextual_links']['menu'] = array('admin/structure/menu/manage', array($delta));
492
  }
493
  return $data;
494
}
495

496
/**
497
 * Implements hook_block_view_alter().
498
499
500
501
502
503
 */
function menu_block_view_alter(&$data, $block) {
  // Add contextual links for system menu blocks.
  if ($block->module == 'system' && !empty($data['content'])) {
    $system_menus = menu_list_system_menus();
    if (isset($system_menus[$block->delta])) {
504
      $data['content']['#contextual_links']['menu'] = array('admin/structure/menu/manage', array($block->delta));
505
506
507
508
    }
  }
}

509
/**
510
 * Implements hook_node_insert().
511
 */
512
function menu_node_insert($node) {
513
  menu_node_save($node);
514
515
516
}

/**
517
 * Implements hook_node_update().
518
 */
519
function menu_node_update($node) {
520
521
522
523
524
525
  menu_node_save($node);
}

/**
 * Helper for hook_node_insert() and hook_node_update().
 */
526
function menu_node_save($node) {
527
  if (isset($node->menu)) {
528
529
530
531
532
    $link = &$node->menu;
    if (empty($link['enabled'])) {
      if (!empty($link['mlid'])) {
        menu_link_delete($link['mlid']);
      }
533
    }
534
535
536
    elseif (trim($link['link_title'])) {
      $link['link_title'] = trim($link['link_title']);
      $link['link_path'] = "node/$node->nid";
537
538
539
540
541
542
543
      if (trim($link['description'])) {
        $link['options']['attributes']['title'] = trim($link['description']);
      }
      else {
        // If the description field was left empty, remove the title attribute
        // from the menu link.
        unset($link['options']['attributes']['title']);
544
      }
545
      if (!menu_link_save($link)) {
546
        drupal_set_message(t('There was an error saving the menu link.'), 'error');
547
      }
548
549
550
551
552
    }
  }
}

/**
553
 * Implements hook_node_predelete().
554
 */
555
function menu_node_predelete($node) {
556
  // Delete all menu module links that point to this node.
557
  $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));
558
  foreach ($result as $m) {
559
560
561
562
563
    menu_link_delete($m['mlid']);
  }
}

/**
564
 * Implements hook_node_prepare().
565
 */
566
function menu_node_prepare($node) {
567
568
  if (empty($node->menu)) {
    // Prepare the node for the edit form so that $node->menu always exists.
569
    $menu_name = strtok(variable_get('menu_parent_' . $node->type, 'main-menu:0'), ':');
570
571
    $item = array();
    if (isset($node->nid)) {
572
      $mlid = FALSE;
573
      // Give priority to the default menu
574
575
576
      $type_menus = variable_get('menu_options_' . $node->type, array('main-menu' => 'main-menu'));
      if (in_array($menu_name, $type_menus)) {
        $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(
577
          ':path' => 'node/' . $node->nid,
578
579
580
581
582
583
584
585
          ':menu_name' => $menu_name,
        ))->fetchField();
      }
      // Check all allowed menus if a link does not exist in the default menu.
      if (!$mlid && !empty($type_menus)) {
        $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(
          ':path' => 'node/' . $node->nid,
          ':type_menus' => array_values($type_menus),
586
        ))->fetchField();
587
588
589
590
591
592
      }
      if ($mlid) {
        $item = menu_link_load($mlid);
      }
    }
    // Set default values.
593
594
595
596
597
598
599
600
601
602
603
604
605
    $node->menu = $item + array(
      'link_title' => '',
      'mlid' => 0,
      'plid' => 0,
      'menu_name' => $menu_name,
      'weight' => 0,
      'options' => array(),
      'module' => 'menu',
      'expanded' => 0,
      'hidden' => 0,
      'has_children' => 0,
      'customized' => 0,
    );
606
607
608
609
  }
  // Find the depth limit for the parent select.
  if (!isset($node->menu['parent_depth_limit'])) {
    $node->menu['parent_depth_limit'] = _menu_parent_depth_limit($node->menu);
610
611
612
  }
}

613
614
615
616
617
618
619
/**
 * Find the depth limit for items in the parent select.
 */
function _menu_parent_depth_limit($item) {
  return MENU_MAX_DEPTH - 1 - (($item['mlid'] && $item['has_children']) ? menu_link_children_relative_depth($item) : 0);
}

620
/**
621
622
623
624
625
 * Implements hook_form_BASE_FORM_ID_alter().
 *
 * Adds menu item fields to the node form.
 *
 * @see menu_node_submit()
626
 */
627
function menu_form_node_form_alter(&$form, $form_state) {
628
  // Generate a list of possible parents (not including this link or descendants).
629
  // @todo This must be handled in a #process handler.
630
  $link = $form['#node']->menu;
631
  $type = $form['#node']->type;
632
633
634
  // menu_parent_options() is goofy and can actually handle either a menu link
  // or a node type both as second argument. Pick based on whether there is
  // a link already (menu_node_prepare() sets mlid default to 0).
635
  $options = menu_parent_options(menu_get_menus(), $link['mlid'] ? $link : $type, $type);
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
  // If no possible parent menu items were found, there is nothing to display.
  if (empty($options)) {
    return;
  }

  $form['menu'] = array(
    '#type' => 'fieldset',
    '#title' => t('Menu settings'),
    '#access' => user_access('administer menu'),
    '#collapsible' => TRUE,
    '#collapsed' => !$link['link_title'],
    '#group' => 'additional_settings',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.js'),
    ),
    '#tree' => TRUE,
    '#weight' => -2,
    '#attributes' => array('class' => array('menu-link-form')),
  );
  $form['menu']['enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Provide a menu link'),
    '#default_value' => (int) (bool) $link['mlid'],
  );
  $form['menu']['link'] = array(
    '#type' => 'container',
    '#parents' => array('menu'),
    '#states' => array(
      'invisible' => array(
        'input[name="menu[enabled]"]' => array('checked' => FALSE),
666
      ),
667
668
    ),
  );
669

670
671
672
673
  // Populate the element with the link data.
  foreach (array('mlid', 'module', 'hidden', 'has_children', 'customized', 'options', 'expanded', 'hidden', 'parent_depth_limit') as $key) {
    $form['menu']['link'][$key] = array('#type' => 'value', '#value' => $link[$key]);
  }
674

675
676
677
678
679
  $form['menu']['link']['link_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Menu link title'),
    '#default_value' => $link['link_title'],
  );
680

681
682
683
684
685
686
687
  $form['menu']['link']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => isset($link['options']['attributes']['title']) ? $link['options']['attributes']['title'] : '',
    '#rows' => 1,
    '#description' => t('Shown when hovering over the menu link.'),
  );
688

689
  $default = ($link['mlid'] ? $link['menu_name'] . ':' . $link['plid'] : variable_get('menu_parent_' . $type, 'main-menu:0'));
690
691
692
693
  // If the current parent menu item is not present in options, use the first
  // available option as default value.
  // @todo User should not be allowed to access menu link settings in such a
  // case.
694
  if (!isset($options[$default])) {
695
696
    $array = array_keys($options);
    $default = reset($array);
697
  }
698
699
700
701
702
703
704
705
706
707
708
709
710
711
  $form['menu']['link']['parent'] = array(
    '#type' => 'select',
    '#title' => t('Parent item'),
    '#default_value' => $default,
    '#options' => $options,
    '#attributes' => array('class' => array('menu-parent-select')),
  );
  $form['menu']['link']['weight'] = array(
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#delta' => 50,
    '#default_value' => $link['weight'],
    '#description' => t('Menu links with smaller weights are displayed before links with larger weights.'),
  );
712
713
}

714
/**
715
 * Implements hook_node_submit().
716
717
 *
 * @see menu_form_node_form_alter()
718
 */
719
function menu_node_submit($node, $form, $form_state) {
720
721
722
  // Decompose the selected menu parent option into 'menu_name' and 'plid', if
  // the form used the default parent selection widget.
  if (!empty($form_state['values']['menu']['parent'])) {
723
    list($node->menu['menu_name'], $node->menu['plid']) = explode(':', $form_state['values']['menu']['parent']);
724
725
726
  }
}

727
/**
728
729
 * Implements hook_form_FORM_ID_alter().
 *
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
 * Adds menu options to the node type form.
 */
function menu_form_node_type_form_alter(&$form, $form_state) {
  $menu_options = menu_get_menus();
  $type = $form['#node_type'];
  $form['menu'] = array(
    '#type' => 'fieldset',
    '#title' => t('Menu settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
    '#group' => 'additional_settings',
  );
  $form['menu']['menu_options'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Available menus'),
748
    '#default_value' => variable_get('menu_options_' . $type->type, array('main-menu')),
749
750
751
752
753
754
    '#options' => $menu_options,
    '#description' => t('The menus available to place links in for this content type.'),
  );
  // To avoid an 'illegal option' error after saving the form we have to load
  // all available menu items.
  // Otherwise it is not possible to dynamically add options to the list.
755
  // @todo Convert menu_parent_options() into a #process callback.
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
  $options = menu_parent_options(menu_get_menus(), array('mlid' => 0));
  $form['menu']['menu_parent'] = array(
    '#type' => 'select',
    '#title' => t('Default parent item'),
    '#default_value' => variable_get('menu_parent_' . $type->type, 'main-menu:0'),
    '#options' => $options,
    '#description' => t('Choose the menu item to be the default parent for a new link in the content authoring form.'),
    '#attributes' => array('class' => array('menu-title-select')),
  );

  // Call Drupal.menu_update_parent_list() to filter the list of
  // available default parent menu items based on the selected menus.
  drupal_add_js(
    '(function ($) { Drupal.menu_update_parent_list(); })(jQuery);',
    array('scope' => 'footer', 'type' => 'inline')
  );
}

774
775
776
777
778
779
780
781
782
783
/**
 * Return an associative array of the custom menus names.
 *
 * @param $all
 *   If FALSE return only user-added menus, or if TRUE also include
 *   the menus defined by the system.
 * @return
 *   An array with the machine-readable names as the keys, and human-readable
 *   titles as the values.
 */
784
function menu_get_menus($all = TRUE) {
785
786
787
788
789
790
791
792
  if ($custom_menus = menu_load_all()) {
    if (!$all) {
      $custom_menus = array_diff_key($custom_menus, menu_list_system_menus());
    }
    foreach ($custom_menus as $menu_name => $menu) {
      $custom_menus[$menu_name] = t($menu['title']);
    }
    asort($custom_menus);
793
  }
794
  return $custom_menus;
795
}
796
797
798
799
800
801
802
803
804

/**
 * Implements hook_preprocess_block().
 */
function menu_preprocess_block(&$variables) {
  if ($variables['block']->module == 'menu') {
    $variables['attributes_array']['role'] = 'navigation';
  }
}