summaryrefslogtreecommitdiff
path: root/modules/menu/menu.module
blob: 45983e55e3eb4ad796ebaf0fba0e8e5ecac1d9ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<?php
// $Id$

/**
 * @file
 * Allows administrators to customize the site navigation menu.
 */

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

/**
 * Implement hook_help().
 */
function menu_help($path, $arg) {
  switch ($path) {
    case 'admin/help#menu':
      $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 used to navigate a website.  Each menu is rendered in a block that may be positioned and displayed using Drupal's flexible block system. Five menus are provided by Drupal and are always present: <em>Navigation</em>, <em>Management</em>, <em>User menu</em>, <em>Main menu</em>, and <em>Secondary menu</em>. The <em>Management</em> menu contains links for administration and content creation, while the <em>Navigation</em> menu is the default location for site navigation links created by newly enabled modules. Both of these are often displayed in either the left or right sidebar. Most Drupal themes also provide support for the <em>Main links</em> and <em>Secondary links</em>, by displaying them in either the header or footer of each page. The <em>Main menu</em> is the default source for the <em>Main links</em> and the <em>User menu</em> is the default source for the <em>Secondary links</em>.  By default, the <em>User menu</em> has links to take the current user to their account or allow them to log out, while the <em>Main menu</em> and <em>Secondary menu</em> contain no menu links but may be configured to contain custom menu items specific to your site. You may create an unlimited number of additional menus, each of which will automatically have an associated block.") . '</p>';
      $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 link, or to rearrange links 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/structure/menu'), '@add-menu' => url('admin/structure/menu/add'), '@blocks' => url('admin/structure/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>';
      return $output;
    case 'admin/structure/menu/add':
      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/structure/block'))) . '</p>';
    case 'admin/structure/menu/item/add':
      return '<p>' . t('Enter the title and path for your new menu link.') . '</p>';
  }
  if ($path == 'admin/structure/menu' && module_exists('block')) {
    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>';
  }
}

/**
 * Implement hook_permission().
 */
function menu_permission() {
  return array(
    'administer menu' => array(
      'title' => t('Administer menu'),
      'description' => t('Manage menus and menu items.'),
    ),
  );
}

/**
 * Implement hook_menu().
 */
function menu_menu() {
  $items['admin/structure/menu'] = array(
    'title' => 'Menus',
    'description' => 'Add new menus to your site, edit existing menus, and rename and reorganize menu links.',
    'page callback' => 'menu_overview_page',
    'access callback' => 'user_access',
    'access arguments' => array('administer menu'),
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu/list'] = array(
    'title' => 'List menus',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/structure/menu/add'] = array(
    'title' => 'Add menu',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_edit_menu', 'add'),
    'access arguments' => array('administer menu'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu/settings'] = array(
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_configure'),
    'access arguments' => array('administer menu'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu-customize/%menu'] = array(
    'title' => 'Customize menu',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_overview_form', 3),
    'title callback' => 'menu_overview_title',
    'title arguments' => array(3),
    'access arguments' => array('administer menu'),
    'type' => MENU_CALLBACK,
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu-customize/%menu/list'] = array(
    'title' => 'List links',
    'weight' => -10,
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/structure/menu-customize/%menu/add'] = array(
    'title' => 'Add link',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_edit_item', 'add', NULL, 3),
    'access arguments' => array('administer menu'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu-customize/%menu/edit'] = array(
    'title' => 'Edit menu',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_edit_menu', 'edit', 3),
    'access arguments' => array('administer menu'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu-customize/%menu/delete'] = array(
    'title' => 'Delete menu',
    'page callback' => 'menu_delete_menu_page',
    'page arguments' => array(3),
    'access arguments' => array('administer menu'),
    'type' => MENU_CALLBACK,
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu/item/%menu_link/edit'] = array(
    'title' => 'Edit menu link',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_edit_item', 'edit', 4, NULL),
    'access arguments' => array('administer menu'),
    'type' => MENU_CALLBACK,
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu/item/%menu_link/reset'] = array(
    'title' => 'Reset menu link',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_reset_item_confirm', 4),
    'access arguments' => array('administer menu'),
    'type' => MENU_CALLBACK,
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu/item/%menu_link/delete'] = array(
    'title' => 'Delete menu link',
    'page callback' => 'menu_item_delete_page',
    'page arguments' => array(4),
    'access arguments' => array('administer menu'),
    'type' => MENU_CALLBACK,
    'file' => 'menu.admin.inc',
  );
  return $items;
}

/**
 * Implement hook_theme().
 */
function menu_theme() {
  return array(
    'menu_overview_form' => array(
      'file' => 'menu.admin.inc',
      'arguments' => array('form' => NULL),
    ),
    'menu_admin_overview' => array(
      'file' => 'menu.admin.inc',
      'arguments' => array('title' => NULL, 'name' => NULL, 'description' => NULL),
    ),
  );
}

/**
 * Implement hook_enable().
 *
 * Add a link for each custom menu.
 */
function menu_enable() {
  menu_rebuild();
  $base_link = db_query("SELECT mlid AS plid, menu_name FROM {menu_links} WHERE link_path = 'admin/structure/menu' AND module = 'system'")->fetchAssoc();
  $base_link['router_path'] = 'admin/structure/menu-customize/%';
  $base_link['module'] = 'menu';
  $result = db_query("SELECT * FROM {menu_custom}", array(), array('fetch' => PDO::FETCH_ASSOC));
  foreach ($result as $menu) {
    // $link is passed by reference to menu_link_save(), so we make a copy of $base_link.
    $link = $base_link;
    $link['mlid'] = 0;
    $link['link_title'] = $menu['title'];
    $link['link_path'] = 'admin/structure/menu-customize/' . $menu['menu_name'];
    $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) {
      menu_link_save($link);
    }
  }
  menu_cache_clear_all();
}

/**
 * Title callback for the menu overview page and links.
 */
function menu_overview_title($menu) {
  return $menu['title'];
}

/**
 * Load the data for a single custom menu.
 */
function menu_load($menu_name) {
  return db_query("SELECT * FROM {menu_custom} WHERE menu_name = :menu", array(':menu' => $menu_name))->fetchAssoc();
}

/**
 * Return a list of menu items that are valid possible parents for the given menu item.
 *
 * @param $menus
 *   An array of menu names and titles, such as from menu_get_menus().
 * @param $item
 *   The menu item for which to generate a list of parents.
 *   If $item['mlid'] == 0 then the complete tree is returned.
 * @return
 *   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.
 */
function menu_parent_options($menus, $item) {
  // 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();
  }
  // If the item has children, there is an added limit to the depth of valid parents.
  if (isset($item['parent_depth_limit'])) {
    $limit = $item['parent_depth_limit'];
  }
  else {
    $limit = _menu_parent_depth_limit($item);
  }

  foreach ($menus as $menu_name => $title) {
    $tree = menu_tree_all_data($menu_name, NULL);
    $options[$menu_name . ':0'] = '<' . $title . '>';
    _menu_parents_recurse($tree, $menu_name, '--', $options, $item['mlid'], $limit);
  }
  return $options;
}

/**
 * Recursive helper function for menu_parent_options().
 */
function _menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude, $depth_limit) {
  foreach ($tree as $data) {
    if ($data['link']['depth'] > $depth_limit) {
      // Don't iterate through any links on this level.
      break;
    }
    if ($data['link']['mlid'] != $exclude && $data['link']['hidden'] >= 0) {
      $title = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, FALSE);
      if ($data['link']['hidden']) {
        $title .= ' (' . t('disabled') . ')';
      }
      $options[$menu_name . ':' . $data['link']['mlid']] = $title;
      if ($data['below']) {
        _menu_parents_recurse($data['below'], $menu_name, $indent . '--', $options, $exclude, $depth_limit);
      }
    }
  }
}

/**
 * Reset a system-defined menu item.
 */
function menu_reset_item($item) {
  $new_item = _menu_link_build(menu_get_item($item['router_path']));
  foreach (array('mlid', 'has_children') as $key) {
    $new_item[$key] = $item[$key];
  }
  menu_link_save($new_item);
  return $new_item;
}

/**
 * Implement hook_block_list().
 */
function menu_block_list() {
  $menus = menu_get_menus(FALSE);

  $blocks = array();
  foreach ($menus as $name => $title) {
    // Default "Navigation" block is handled by user.module.
    $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.
    $blocks[$name]['cache'] = BLOCK_NO_CACHE;
  }
  return $blocks;
}

/**
 * Implement hook_block_view().
 */
function menu_block_view($delta = '') {
  $menus = menu_get_menus(FALSE);
  $data['subject'] = check_plain($menus[$delta]);
  $data['content'] = menu_tree($delta);
  return $data;
}

/**
 * Implement hook_node_insert().
 */
function menu_node_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);
      }
      if (!menu_link_save($item)) {
        drupal_set_message(t('There was an error saving the menu link.'), 'error');
      }
    }
  }
}

/**
 * Implement hook_node_update().
 */
function menu_node_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);
      }
      if (!menu_link_save($item)) {
        drupal_set_message(t('There was an error saving the menu link.'), 'error');
      }
    }
  }
}

/**
 * Implement hook_node_delete().
 */
function menu_node_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), array('fetch' => PDO::FETCH_ASSOC));
  foreach ($result as $m) {
    menu_link_delete($m['mlid']);
  }
}

/**
 * Implement hook_node_prepare().
 */
function menu_node_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_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)
      ->fetchField();
      // Check all menus if a link does not exist in the default menu.
      if (!$mlid) {
        $mlid = 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)
        ->fetchField();
      }
      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);
  }
}

/**
 * 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);
}

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

    $form['menu'] = array(
      '#type' => 'fieldset',
      '#title' => t('Menu settings'),
      '#access' => user_access('administer menu'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#group' => 'additional_settings',
      '#attached_js' => array(drupal_get_path('module', 'menu') . '/menu.js'),
      '#tree' => TRUE,
      '#weight' => -2,
      '#attributes' => array('class' => array('menu-item-form')),
    );
    $item = $form['#node']->menu;

    if ($item['mlid']) {
      // There is an existing link.
      $form['menu']['delete'] = array(
        '#type' => 'checkbox',
        '#title' => t('Delete this menu item.'),
      );
    }
    if (!$item['link_title']) {
      $form['menu']['#collapsed'] = TRUE;
    }

    foreach (array('mlid', 'module', 'hidden', 'has_children', 'customized', 'options', 'expanded', 'hidden', 'parent_depth_limit') as $key) {
      $form['menu'][$key] = array('#type' => 'value', '#value' => $item[$key]);
    }
    $form['menu']['#item'] = $item;

    $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).
    $options = menu_parent_options(menu_get_menus(), $item);
    $default = $item['menu_name'] . ':' . $item['plid'];
    if (!isset($options[$default])) {
      $default = 'main-menu:0';
    }
    $form['menu']['parent'] = array(
      '#type' => 'select',
      '#title' => t('Parent item'),
      '#default_value' => $default,
      '#options' => $options,
      '#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)),
      '#attributes' => array('class' => array('menu-title-select')),
    );
    $form['#submit'][] = 'menu_node_form_submit';

    $form['menu']['weight'] = array(
      '#type' => 'weight',
      '#title' => t('Weight'),
      '#delta' => 50,
      '#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.'),
    );
  }
}

/**
 * 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']);
}

/**
 * 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.
 */
function menu_get_menus($all = TRUE) {
  $system_menus = array_keys(menu_list_system_menus());
  $query = db_select('menu_custom');
  $query->addField('menu_custom', 'menu_name', 'menu_name');
  $query->addField('menu_custom', 'title', 'title');
  if (!$all) {
    $query->condition('menu_name', $system_menus, 'NOT IN');
  }
  $query->orderBy('title');

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