menu.module 17.8 KB
Newer Older
1
2
3
<?php
// $Id$

Dries's avatar
   
Dries committed
4
5
6
7
8
/**
 * @file
 * Allows administrators to customize the site navigation menu.
 */

9
10
11
12
/**
 * Maximum length of menu name as entered by the user. Database length is 32
 * and we add a menu- prefix.
 */
13
define('MENU_MAX_MENU_NAME_LENGTH_UI', 27);
14

15
16
17
/**
 * Implementation of hook_help().
 */
18
19
function menu_help($path, $arg) {
  switch ($path) {
20
    case 'admin/help#menu':
21
      $output = '<p>' . t("The menu module provides an interface to control and customize Drupal's powerful menu system. Menus are a hierarchical collection of links, or menu items, used to navigate a website, and are positioned and displayed using Drupal's flexible block system. By default, three menus are created during installation: <em>Navigation</em>, <em>Main menu</em>, and <em>Secondary menu</em>. The <em>Navigation</em> menu contains most links necessary for working with and navigating your site, and is often displayed in either the left or right sidebar. Most Drupal themes also provide support for the <em>Main menu</em> and <em>Secondary menu</em>, by displaying them in either the header or footer of each page. By default, the <em>Main menu</em> and <em>Secondary menu</em> contain no menu items but may be configured to contain custom menu items specific to your site.") . '</p>';
22
23
      $output .= '<p>' . t('The <a href="@menu">menus page</a> displays all menus currently available on your site. Select a menu from this list to add or edit a menu item, or to rearrange items within the menu. Create new menus using the <a href="@add-menu">add menu page</a> (the block containing a new menu must also be enabled on the <a href="@blocks">blocks administration page</a>).', array('@menu' => url('admin/build/menu'), '@add-menu' => url('admin/build/menu/add'), '@blocks' => url('admin/build/block'))) . '</p>';
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@menu">Menu module</a>.', array('@menu' => 'http://drupal.org/handbook/modules/menu/')) . '</p>';
24
      return $output;
25
    case 'admin/build/menu':
26
      return '<p>' . t('Menus are a collection of links (menu items) used to navigate a website. The menus currently available on your site are displayed below. Select a menu from this list to manage its menu items.') . '</p>';
27
    case 'admin/build/menu/add':
28
      return '<p>' . t('Enter the name for your new menu. Remember to enable the newly created block in the <a href="@blocks">blocks administration page</a>.', array('@blocks' => url('admin/build/block'))) . '</p>';
29
    case 'admin/build/menu-customize/%':
30
      return '<p>' . t('To rearrange menu items, grab a drag-and-drop handle under the <em>Menu item</em> column and drag the items (or group of items) to a new location in the list. (Grab a handle by clicking and holding the mouse while hovering over a handle icon.) Remember that your changes will not be saved until you click the <em>Save configuration</em> button at the bottom of the page.') . '</p>';
31
    case 'admin/build/menu/item/add':
32
      return '<p>' . t('Enter the title and path for your new menu item.') . '</p>';
33
34
35
  }
}

36
37
38
39
/**
 * Implementation of hook_perm().
 */
function menu_perm() {
40
  return array(
41
42
43
44
    'administer menu' => array(
      'title' => t('Administer menu'),
      'description' => t('Manage menus and menu items.'),
    ),
45
  );
46
47
}

48
/**
49
 * Implementation of hook_menu().
50
 */
51
function menu_menu() {
52
  $items['admin/build/menu'] = array(
53
    'title' => 'Menus',
54
    'description' => "Control your site's Navigation menu, Main menu and Secondary menu. as well as rename and reorganize menu items.",
55
    'page callback' => 'menu_overview_page',
56
57
58
59
    'access callback' => 'user_access',
    'access arguments' => array('administer menu'),
  );
  $items['admin/build/menu/list'] = array(
60
    'title' => 'List menus',
61
    'type' => MENU_DEFAULT_LOCAL_TASK,
62
63
    'weight' => -10,
  );
64
  $items['admin/build/menu/add'] = array(
65
66
67
    'title' => 'Add menu',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_edit_menu', 'add'),
68
    'access arguments' => array('administer menu'),
69
70
    'type' => MENU_LOCAL_TASK,
  );
71
72
73
74
  $items['admin/build/menu/settings'] = array(
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_configure'),
75
    'access arguments' => array('administer menu'),
76
    'type' => MENU_LOCAL_TASK,
77
78
    'weight' => 5,
  );
79
80
  $items['admin/build/menu-customize/%menu'] = array(
    'title' => 'Customize menu',
81
82
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_overview_form', 3),
83
84
    'title callback' => 'menu_overview_title',
    'title arguments' => array(3),
85
    'access arguments' => array('administer menu'),
86
87
    'type' => MENU_CALLBACK,
  );
88
89
90
  $items['admin/build/menu-customize/%menu/list'] = array(
    'title' => 'List items',
    'weight' => -10,
91
92
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
93
94
95
96
  $items['admin/build/menu-customize/%menu/add'] = array(
    'title' => 'Add item',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_edit_item', 'add', NULL, 3),
97
    'access arguments' => array('administer menu'),
98
99
    'type' => MENU_LOCAL_TASK,
  );
100
101
102
103
  $items['admin/build/menu-customize/%menu/edit'] = array(
    'title' => 'Edit menu',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_edit_menu', 'edit', 3),
104
    'access arguments' => array('administer menu'),
105
106
    'type' => MENU_LOCAL_TASK,
  );
107
108
109
110
  $items['admin/build/menu-customize/%menu/delete'] = array(
    'title' => 'Delete menu',
    'page callback' => 'menu_delete_menu_page',
    'page arguments' => array(3),
111
    'access arguments' => array('administer menu'),
112
113
    'type' => MENU_CALLBACK,
  );
114
  $items['admin/build/menu/item/%menu_link/edit'] = array(
115
    'title' => 'Edit menu item',
116
    'page callback' => 'drupal_get_form',
117
    'page arguments' => array('menu_edit_item', 'edit', 4, NULL),
118
    'access arguments' => array('administer menu'),
119
120
    'type' => MENU_CALLBACK,
  );
121
  $items['admin/build/menu/item/%menu_link/reset'] = array(
122
    'title' => 'Reset menu item',
123
    'page callback' => 'drupal_get_form',
124
    'page arguments' => array('menu_reset_item_confirm', 4),
125
    'access arguments' => array('administer menu'),
126
127
    'type' => MENU_CALLBACK,
  );
128
  $items['admin/build/menu/item/%menu_link/delete'] = array(
129
    'title' => 'Delete menu item',
130
131
    'page callback' => 'menu_item_delete_page',
    'page arguments' => array(4),
132
    'access arguments' => array('administer menu'),
133
134
    'type' => MENU_CALLBACK,
  );
135
  return $items;
136
}
137

138
139
140
141
142
143
144
145
146
147
148
149
/**
 * Implemenation of hook_theme().
 */
function menu_theme() {
  return array(
    'menu_overview_form' => array(
      'file' => 'menu.admin.inc',
      'arguments' => array('form' => NULL),
    ),
  );
}

150
/**
151
 * Implementation of hook_enable().
152
153
154
155
156
 *
 *  Add a link for each custom menu.
 */
function menu_enable() {
  menu_rebuild();
157
158
159
  $base_link = db_fetch_array(db_query("SELECT mlid AS plid, menu_name from {menu_links} WHERE link_path = 'admin/build/menu' AND module = 'system'"));
  $base_link['router_path'] = 'admin/build/menu-customize/%';
  $base_link['module'] = 'menu';
160
  $result = db_query("SELECT * FROM {menu_custom}");
161
  while ($menu = db_fetch_array($result)) {
162
163
    // $link is passed by reference to menu_link_save(), so we make a copy of $base_link.
    $link = $base_link;
164
165
    $link['mlid'] = 0;
    $link['link_title'] = $menu['title'];
166
    $link['link_path'] = 'admin/build/menu-customize/' . $menu['menu_name'];
167
168
169
    if (!db_result(db_query("SELECT mlid FROM {menu_links} WHERE link_path = '%s' AND plid = %d", $link['link_path'], $link['plid']))) {
      menu_link_save($link);
    }
170
  }
171
  menu_cache_clear_all();
172
173
}

174
175
176
177
/**
 * Title callback for the menu overview page and links.
 */
function menu_overview_title($menu) {
Dries's avatar
Dries committed
178
  return $menu['title'];
179
180
}

181
182
183
184
185
186
187
/**
 * Load the data for a single custom menu.
 */
function menu_load($menu_name) {
  return db_fetch_array(db_query("SELECT * FROM {menu_custom} WHERE menu_name = '%s'", $menu_name));
}

188
/**
189
 * Return a list of menu items that are valid possible parents for the given menu item.
190
 *
191
192
 * @param $menus
 *   An array of menu names and titles, such as from menu_get_menus().
193
194
 * @param $item
 *   The menu item for which to generate a list of parents.
195
 *   If $item['mlid'] == 0 then the complete tree is returned.
196
 * @return
197
198
 *   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.
199
 */
200
function menu_parent_options($menus, $item) {
201
202
203
204
205
206
207
  // 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();
  }
208
  // If the item has children, there is an added limit to the depth of valid parents.
209
210
211
212
213
214
  if (isset($item['parent_depth_limit'])) {
    $limit = $item['parent_depth_limit'];
  }
  else {
    $limit = _menu_parent_depth_limit($item);
  }
215

216
  foreach ($menus as $menu_name => $title) {
217
    $tree = menu_tree_all_data($menu_name, NULL);
218
    $options[$menu_name . ':0'] = '<' . $title . '>';
219
    _menu_parents_recurse($tree, $menu_name, '--', $options, $item['mlid'], $limit);
220
  }
221
  return $options;
222
223
224
}

/**
225
 * Recursive helper function for menu_parent_options().
226
 */
227
function _menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude, $depth_limit) {
228
  foreach ($tree as $data) {
229
230
231
232
    if ($data['link']['depth'] > $depth_limit) {
      // Don't iterate through any links on this level.
      break;
    }
233
    if ($data['link']['mlid'] != $exclude && $data['link']['hidden'] >= 0) {
234
      $title = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, FALSE);
235
      if ($data['link']['hidden']) {
236
        $title .= ' (' . t('disabled') . ')';
237
      }
238
      $options[$menu_name . ':' . $data['link']['mlid']] = $title;
239
      if ($data['below']) {
240
        _menu_parents_recurse($data['below'], $menu_name, $indent . '--', $options, $exclude, $depth_limit);
241
242
243
      }
    }
  }
244
245
}

246
247
248
249
/**
 * Reset a system-defined menu item.
 */
function menu_reset_item($item) {
250
251
252
253
254
255
  $router = menu_router_build();
  $new_item = _menu_link_build($router[$item['router_path']]);
  foreach (array('mlid', 'has_children') as $key) {
    $new_item[$key] = $item[$key];
  }
  menu_link_save($new_item);
256
  return $new_item;
257
258
}

259
/**
260
 * Implementation of hook_block().
261
 */
262
function menu_block($op = 'list', $delta = '') {
263
264
265
  $menus = menu_get_menus();
  // The Navigation menu is handled by the user module.
  unset($menus['navigation']);
266
267
  if ($op == 'list') {
    $blocks = array();
268
    foreach ($menus as $name => $title) {
269
      // Default "Navigation" block is handled by user.module.
270
      $blocks[$name]['info'] = check_plain($title);
271
272
273
      // Menu blocks can't be cached because each menu item can have
      // a custom access callback. menu.inc manages its own caching.
      $blocks[$name]['cache'] = BLOCK_NO_CACHE;
274
    }
275
    return $blocks;
276
  }
277
  elseif ($op == 'view') {
278
    $data['subject'] = check_plain($menus[$delta]);
279
    $data['content'] = menu_tree($delta);
280
281
282
    return $data;
  }
}
283

284
/**
285
 * Implementation of hook_nodeapi_insert().
286
 */
287
288
289
290
291
292
293
294
295
296
297
function menu_nodeapi_insert(&$node) {
  if (isset($node->menu)) {
    $item = $node->menu;
    if (!empty($item['delete'])) {
      menu_link_delete($item['mlid']);
    }
    elseif (trim($item['link_title'])) {
      $item['link_title'] = trim($item['link_title']);
      $item['link_path'] = "node/$node->nid";
      if (!$item['customized']) {
        $item['options']['attributes']['title'] = trim($node->title);
298
      }
299
300
      if (!menu_link_save($item)) {
        drupal_set_message(t('There was an error saving the menu link.'), 'error');
301
      }
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
    }
  }
}

/**
 * Implementation of hook_nodeapi_update().
 */
function menu_nodeapi_update(&$node) {
  if (isset($node->menu)) {
    $item = $node->menu;
    if (!empty($item['delete'])) {
      menu_link_delete($item['mlid']);
    }
    elseif (trim($item['link_title'])) {
      $item['link_title'] = trim($item['link_title']);
      $item['link_path'] = "node/$node->nid";
      if (!$item['customized']) {
        $item['options']['attributes']['title'] = trim($node->title);
320
      }
321
322
      if (!menu_link_save($item)) {
        drupal_set_message(t('There was an error saving the menu link.'), 'error');
323
      }
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
    }
  }
}

/**
 * Implementation of hook_nodeapi_delete().
 */
function menu_nodeapi_delete(&$node) {
  // Delete all menu module links that point to this node.
  $result = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path AND module = 'menu'", array(':path' => 'node/'. $node->nid));
  while ($m = db_fetch_array($result)) {
    menu_link_delete($m['mlid']);
  }
}

/**
 * Implementation of hook_nodeapi_prepare().
 */
function menu_nodeapi_prepare(&$node) {
  if (empty($node->menu)) {
    // Prepare the node for the edit form so that $node->menu always exists.
    $menu_name = variable_get('menu_default_node_menu', 'main-menu');
    $item = array();
    if (isset($node->nid)) {
      // Give priority to the default menu
      $mlid = db_result(db_query_range("SELECT mlid FROM {menu_links} WHERE link_path = :path AND menu_name = :menu_name AND module = 'menu' ORDER BY mlid ASC", array(
        ':path' => 'node/'. $node->nid,
        ':menu_name' => $menu_name,
      ), 0, 1));
      // Check all menus if a link does not exist in the default menu.
      if (!$mlid) {
        $mlid = db_result(db_query_range("SELECT mlid FROM {menu_links} WHERE link_path = :path AND module = 'menu' ORDER BY mlid ASC", array(
          ':path' => 'node/'. $node->nid,
        ), 0, 1));
      }
      if ($mlid) {
        $item = menu_link_load($mlid);
      }
    }
    // Set default values.
    $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);
  }
  // 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);
369
370
371
  }
}

372
373
374
375
376
377
378
/**
 * 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);
}

379
/**
380
 * Implementation of hook_form_alter(). Adds menu item fields to the node form.
381
 */
382
function menu_form_alter(&$form, $form_state, $form_id) {
383
  if (!empty($form['#node_edit_form'])) {
384
385
386
    // Note - doing this to make sure the delete checkbox stays in the form.
    $form['#cache'] = TRUE;

387
388
    $form['menu'] = array(
      '#type' => 'fieldset',
389
390
391
      '#title' => t('Menu settings'),
      '#access' => user_access('administer menu'),
      '#collapsible' => TRUE,
392
      '#collapsed' => FALSE,
393
      '#tree' => TRUE,
394
      '#weight' => -2,
395
      '#attributes' => array('class' => 'menu-item-form'),
396
    );
397
398
399
    $item = $form['#node']->menu;

    if ($item['mlid']) {
400
      // There is an existing link.
401
      $form['menu']['delete'] = array(
402
        '#type' => 'checkbox',
403
        '#title' => t('Delete this menu item.'),
404
      );
405
    }
406
    if (!$item['link_title']) {
407
408
      $form['menu']['#collapsed'] = TRUE;
    }
409

410
    foreach (array('mlid', 'module', 'hidden', 'has_children', 'customized', 'options', 'expanded', 'hidden', 'parent_depth_limit') as $key) {
411
412
      $form['menu'][$key] = array('#type' => 'value', '#value' => $item[$key]);
    }
413
    $form['menu']['#item'] = $item;
414
415
416
417
418
419
420
421

    $form['menu']['link_title'] = array('#type' => 'textfield',
      '#title' => t('Menu link title'),
      '#default_value' => $item['link_title'],
      '#description' => t('The link text corresponding to this item that should appear in the menu. Leave blank if you do not wish to add this post to the menu.'),
      '#required' => FALSE,
    );
    // Generate a list of possible parents (not including this item or descendants).
422
    $options = menu_parent_options(menu_get_menus(), $item);
423
    $default = $item['menu_name'] . ':' . $item['plid'];
424
    if (!isset($options[$default])) {
425
      $default = 'main-menu:0';
426
427
    }
    $form['menu']['parent'] = array(
428
429
      '#type' => 'select',
      '#title' => t('Parent item'),
430
      '#default_value' => $default,
431
      '#options' => $options,
432
      '#description' => t('The maximum depth for an item and all its children is fixed at !maxdepth. Some menu items may not be available as parents if selecting them would exceed this limit.', array('!maxdepth' => MENU_MAX_DEPTH)),
433
      '#attributes' => array('class' => 'menu-title-select'),
434
    );
435
436
    $form['#submit'][] = 'menu_node_form_submit';

437
438
439
    $form['menu']['weight'] = array(
      '#type' => 'weight',
      '#title' => t('Weight'),
440
      '#delta' => 50,
441
442
443
      '#default_value' => $item['weight'],
      '#description' => t('Optional. In the menu, the heavier items will sink and the lighter items will be positioned nearer the top.'),
    );
444
445
446
  }
}

447
448
449
450
451
452
453
/**
 * Decompose the selected menu parent option into the menu_name and plid.
 */
function menu_node_form_submit($form, &$form_state) {
  list($form_state['values']['menu']['menu_name'], $form_state['values']['menu']['plid']) = explode(':', $form_state['values']['menu']['parent']);
}

454
455
456
457
458
459
460
461
462
463
/**
 * 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.
 */
464
function menu_get_menus($all = TRUE) {
465
  $system_menus = menu_list_system_menus();
466
467
468
  $query = db_select('menu_custom');
  $query->addField('menu_custom', 'menu_name', 'menu_name');
  $query->addField('menu_custom', 'title', 'title');
469
  if (!$all) {
470
    $query->condition('menu_name', $system_menus, 'NOT IN');
471
  }
472
473
474
  $query->orderBy('title');

  return $query->execute()->fetchAllKeyed();
475
}