menu.inc 32.1 KB
Newer Older
Dries's avatar
   
Dries committed
1
<?php
Kjartan's avatar
Kjartan committed
2
3
/* $Id$ */

4
5
6
7
8
/**
 * @file
 * API for the Drupal menu system.
 */

Dries's avatar
   
Dries committed
9
10
11
/**
 * @defgroup menu Menu system
 * @{
Dries's avatar
   
Dries committed
12
 * Define the navigation menus, and route page requests to code based on URLs.
Dries's avatar
   
Dries committed
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
 *
 * The Drupal menu system drives both the navigation system from a user
 * perspective and the callback system that Drupal uses to respond to URLs
 * passed from the browser. For this reason, a good understanding of the
 * menu system is fundamental to the creation of complex modules.
 *
 * Drupal's menu system follows a simple hierarchy defined by paths.
 * Implementations of hook_menu() define menu items and assign them to
 * paths (which should be unique). The menu system aggregates these items
 * and determines the menu hierarchy from the paths. For example, if the
 * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
 * would form the structure:
 * - a
 *   - a/b
 *     - a/b/c/d
 *     - a/b/h
 * - e
 * - f/g
 * Note that the number of elements in the path does not necessarily
 * determine the depth of the menu item in the tree.
 *
 * When responding to a page request, the menu system looks to see if the
 * path requested by the browser is registered as a menu item with a
 * callback. If not, the system searches up the menu tree for the most
 * complete match with a callback it can find. If the path a/b/i is
 * requested in the tree above, the callback for a/b would be used.
 *
 * The found callback function is called with any arguments specified in
 * the "callback arguments" attribute of its menu item. After these
 * arguments, any remaining components of the path are appended as further
 * arguments. In this way, the callback for a/b above could respond to a
 * request for a/b/i differently than a request for a/b/j.
 *
 * For an illustration of this process, see page_example.module.
 *
 * Access to the callback functions is also protected by the menu system.
 * The "access" attribute of each menu item is checked as the search for a
 * callback proceeds. If this attribute is TRUE, then access is granted; if
 * FALSE, then access is denied. The first found "access" attribute
 * determines the accessibility of the target. Menu items may omit this
 * attribute to use the value provided by an ancestor item.
 *
 * In the default Drupal interface, you will notice many links rendered as
 * tabs. These are known in the menu system as "local tasks", and they are
 * rendered as tabs by default, though other presentations are possible.
 * Local tasks function just as other menu items in most respects. It is
 * convention that the names of these tasks should be short verbs if
 * possible. In addition, a "default" local task should be provided for
 * each set. When visiting a local task's parent menu item, the default
 * local task will be rendered as if it is selected; this provides for a
 * normal tab user experience. This default task is special in that it
 * links not to its provided path, but to its parent item's path instead.
 * The default task's path is only used to place it appropriately in the
 * menu hierarchy.
Dries's avatar
   
Dries committed
67
68
 */

Dries's avatar
   
Dries committed
69
/**
Dries's avatar
   
Dries committed
70
 * @name Menu flags
Dries's avatar
   
Dries committed
71
 * @{
Dries's avatar
   
Dries committed
72
73
 * Flags for use in the "type" attribute of menu items.
 */
Dries's avatar
   
Dries committed
74

Dries's avatar
   
Dries committed
75
76
77
78
79
80
81
82
define('MENU_IS_ROOT', 0x0001);
define('MENU_VISIBLE_IN_TREE', 0x0002);
define('MENU_VISIBLE_IN_BREADCRUMB', 0x0004);
define('MENU_VISIBLE_IF_HAS_CHILDREN', 0x0008);
define('MENU_MODIFIABLE_BY_ADMIN', 0x0010);
define('MENU_MODIFIED_BY_ADMIN', 0x0020);
define('MENU_CREATED_BY_ADMIN', 0x0040);
define('MENU_IS_LOCAL_TASK', 0x0080);
Dries's avatar
   
Dries committed
83
define('MENU_EXPANDED', 0x0100);
Dries's avatar
   
Dries committed
84
define('MENU_LINKS_TO_PARENT', 0x0200);
Dries's avatar
   
Dries committed
85

Dries's avatar
   
Dries committed
86
/**
Dries's avatar
   
Dries committed
87
 * @} End of "Menu flags".
Dries's avatar
   
Dries committed
88
89
90
 */

/**
Dries's avatar
   
Dries committed
91
 * @name Menu item types
Dries's avatar
   
Dries committed
92
93
94
95
 * @{
 * Menu item definitions provide one of these constants, which are shortcuts for
 * combinations of the above flags.
 */
Dries's avatar
   
Dries committed
96

Dries's avatar
   
Dries committed
97
98
/**
 * Normal menu items show up in the menu tree and can be moved/hidden by
Dries's avatar
   
Dries committed
99
100
 * the administrator. Use this for most menu items. It is the default value if
 * no menu item type is specified.
Dries's avatar
   
Dries committed
101
102
 */
define('MENU_NORMAL_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB | MENU_MODIFIABLE_BY_ADMIN);
103

Dries's avatar
   
Dries committed
104
105
/**
 * Item groupings are used for pages like "node/add" that simply list
Dries's avatar
   
Dries committed
106
107
 * subpages to visit. They are distinguished from other pages in that they will
 * disappear from the menu if no subpages exist.
Dries's avatar
   
Dries committed
108
109
 */
define('MENU_ITEM_GROUPING', MENU_VISIBLE_IF_HAS_CHILDREN | MENU_VISIBLE_IN_BREADCRUMB | MENU_MODIFIABLE_BY_ADMIN);
Dries's avatar
   
Dries committed
110

Dries's avatar
   
Dries committed
111
112
/**
 * Callbacks simply register a path so that the correct function is fired
Dries's avatar
   
Dries committed
113
 * when the URL is accessed. They are not shown in the menu.
Dries's avatar
   
Dries committed
114
115
 */
define('MENU_CALLBACK', MENU_VISIBLE_IN_BREADCRUMB);
Dries's avatar
   
Dries committed
116

117
/**
Dries's avatar
   
Dries committed
118
119
120
121
 * Dynamic menu items change frequently, and so should not be stored in the
 * database for administrative customization.
 */
define('MENU_DYNAMIC_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB);
Dries's avatar
   
Dries committed
122

Dries's avatar
   
Dries committed
123
/**
Dries's avatar
   
Dries committed
124
125
 * Modules may "suggest" menu items that the administrator may enable. They act
 * just as callbacks do until enabled, at which time they act like normal items.
Dries's avatar
   
Dries committed
126
127
128
129
 */
define('MENU_SUGGESTED_ITEM', MENU_MODIFIABLE_BY_ADMIN);

/**
Dries's avatar
   
Dries committed
130
131
132
 * Local tasks are rendered as tabs by default. Use this for menu items that
 * describe actions to be performed on their parent item. An example is the path
 * "node/52/edit", which performs the "edit" task on "node/52".
Dries's avatar
   
Dries committed
133
134
135
 */
define('MENU_LOCAL_TASK', MENU_IS_LOCAL_TASK);

Dries's avatar
   
Dries committed
136
137
138
139
140
141
/**
 * Every set of local tasks should provide one "default" task, that links to the
 * same path as its parent when clicked.
 */
define('MENU_DEFAULT_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT);

Dries's avatar
   
Dries committed
142
/**
Dries's avatar
   
Dries committed
143
144
 * Custom items are those defined by the administrator. Reserved for internal
 * use; do not return from hook_menu() implementations.
Dries's avatar
   
Dries committed
145
146
147
148
 */
define('MENU_CUSTOM_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB | MENU_CREATED_BY_ADMIN | MENU_MODIFIABLE_BY_ADMIN);

/**
Dries's avatar
   
Dries committed
149
150
 * Custom menus are those defined by the administrator. Reserved for internal
 * use; do not return from hook_menu() implementations.
Dries's avatar
   
Dries committed
151
152
153
154
 */
define('MENU_CUSTOM_MENU', MENU_IS_ROOT | MENU_VISIBLE_IN_TREE | MENU_CREATED_BY_ADMIN | MENU_MODIFIABLE_BY_ADMIN);

/**
Dries's avatar
   
Dries committed
155
 * @} End of "Menu item types".
Dries's avatar
   
Dries committed
156
157
158
159
160
 */

/**
 * @name Menu status codes
 * @{
Dries's avatar
   
Dries committed
161
162
 * Status codes for menu callbacks.
 */
Dries's avatar
   
Dries committed
163

Dries's avatar
   
Dries committed
164
165
166
define('MENU_FOUND', 1);
define('MENU_NOT_FOUND', 2);
define('MENU_ACCESS_DENIED', 3);
Dries's avatar
   
Dries committed
167

Dries's avatar
   
Dries committed
168
/**
Dries's avatar
   
Dries committed
169
 * @} End of "Menu status codes".
Dries's avatar
   
Dries committed
170
 */
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186

/**
 * Return the menu data structure.
 *
 * The returned structure contains much information that is useful only
 * internally in the menu system. External modules are likely to need only
 * the ['visible'] element of the returned array. All menu items that are
 * accessible to the current user and not hidden will be present here, so
 * modules and themes can use this structure to build their own representations
 * of the menu.
 *
 * $menu['visible'] will contain an associative array, the keys of which
 * are menu IDs. The values of this array are themselves associative arrays,
 * with the following key-value pairs defined:
 * - 'title' - The displayed title of the menu or menu item. It will already
 *   have been translated by the locale system.
Dries's avatar
   
Dries committed
187
188
 * - 'description' - The description (link title attribute) of the menu item.
 *   It will already have been translated by the locale system.
189
 * - 'path' - The Drupal path to the menu item. A link to a particular item
Dries's avatar
   
Dries committed
190
191
 *   can thus be constructed with
 *   l($item['title'], $item['path'], array('title' => $item['description'])).
192
193
194
195
196
197
198
199
 * - 'children' - A linear list of the menu ID's of this item's children.
 *
 * Menu ID 0 is the "root" of the menu. The children of this item are the
 * menus themselves (they will have no associated path). Menu ID 1 will
 * always be one of these children; it is the default "Navigation" menu.
 */
function menu_get_menu() {
  global $_menu;
Dries's avatar
   
Dries committed
200
  global $user;
201
  global $locale;
202
203

  if (!isset($_menu['items'])) {
Dries's avatar
   
Dries committed
204
205
    // _menu_build() may indirectly call this function, so prevent infinite loops.
    $_menu['items'] = array();
Dries's avatar
   
Dries committed
206

207
    $cid = "menu:$user->uid:$locale";
Dries's avatar
   
Dries committed
208
209
210
211
212
213
214
215
216
217
218
    if ($cached = cache_get($cid)) {
      $_menu = unserialize($cached->data);
    }
    else {
      _menu_build();
      // Cache the menu structure for this user, to expire after one day.
      cache_set($cid, serialize($_menu), time() + (60 * 60 * 24));
    }

    // Make sure items that cannot be cached are added.
    _menu_append_contextual_items();
219
  }
220

Dries's avatar
   
Dries committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
  return $_menu;
}

/**
 * Return the local task tree.
 *
 * Unlike the rest of the menu structure, the local task tree cannot be cached
 * nor determined too early in the page request, because the user's current
 * location may be changed by a menu_set_location() call, and the tasks shown
 * (just as the breadcrumb trail) need to reflect the changed location.
 */
function menu_get_local_tasks() {
  global $_menu;

Dries's avatar
   
Dries committed
235
236
237
238
239
240
  // Don't cache the local task tree, as it varies by location and tasks are
  // allowed to be dynamically determined.
  if (!isset($_menu['local tasks'])) {
    // _menu_build_local_tasks() may indirectly call this function, so prevent
    // infinite loops.
    $_menu['local tasks'] = array();
Dries's avatar
   
Dries committed
241
242
243
244
245
    $pid = menu_get_active_nontask_item();
    if (!_menu_build_local_tasks($pid)) {
      // If the build returned FALSE, the tasks need not be displayed.
      $_menu['local tasks'][$pid]['children'] = array();
    }
Dries's avatar
   
Dries committed
246
247
  }

Dries's avatar
   
Dries committed
248
  return $_menu['local tasks'];
Dries's avatar
   
Dries committed
249
}
Dries's avatar
   
Dries committed
250

251
/**
Dries's avatar
   
Dries committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
 * Change the current menu location of the user.
 *
 * Frequently, modules may want to make a page or node act as if it were
 * in the menu tree somewhere, even though it was not registered in a
 * hook_menu() implementation. If the administrator has rearranged the menu,
 * the newly set location should respect this in the breadcrumb trail and
 * expanded/collapsed status of menu items in the tree. This function
 * allows this behavior.
 *
 * @param $location
 *   An array specifying a complete or partial breadcrumb trail for the
 *   new location, in the same format as the return value of hook_menu().
 *   The last element of this array should be the new location itself.
 *
 * This function will set the new breadcrumb trail to the passed-in value,
 * but if any elements of this trail are visible in the site tree, the
 * trail will be "spliced in" to the existing site navigation at that point.
269
 */
Dries's avatar
   
Dries committed
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
function menu_set_location($location) {
  global $_menu;
  $temp_id = min(array_keys($_menu['items'])) - 1;
  $prev_id = 0;

  foreach (array_reverse($location) as $item) {
    if (isset($_menu['path index'][$item['path']])) {
      $mid = $_menu['path index'][$item['path']];
      if (isset ($_menu['visible'][$mid])) {
        // Splice in the breadcrumb at this location.
        if ($prev_id) {
          $_menu['items'][$prev_id]['pid'] = $mid;
        }
        $prev_id = 0;
        break;
      }
      else {
        // A hidden item; show it, but only temporarily.
        $_menu['items'][$mid]['type'] |= MENU_VISIBLE_IN_BREADCRUMB;
        if ($prev_id) {
          $_menu['items'][$prev_id]['pid'] = $mid;
        }
        $prev_id = $mid;
      }
    }
    else {
      $item['type'] |= MENU_VISIBLE_IN_BREADCRUMB;
      if ($prev_id) {
        $_menu['items'][$prev_id]['pid'] = $temp_id;
      }
      $_menu['items'][$temp_id] = $item;
      $_menu['path index'][$item['path']] = $temp_id;
Dries's avatar
   
Dries committed
302

Dries's avatar
   
Dries committed
303
304
305
306
      $prev_id = $temp_id;
      $temp_id--;
    }
  }
Dries's avatar
   
Dries committed
307

Dries's avatar
   
Dries committed
308
309
310
311
312
313
314
315
316
317
318
319
320
  if ($prev_id) {
    // Didn't find a home, so attach this to the main navigation menu.
    $_menu['items'][$prev_id]['pid'] = 1;
  }

  $final_item = array_pop($location);
  menu_set_active_item($final_item['path']);
}

/**
 * Execute the handler associated with the active menu item.
 *
 * This is called early in the page request. The active menu item is at
321
 * this point determined exclusively by the URL. The handler that is called
Dries's avatar
   
Dries committed
322
323
324
325
326
327
328
329
330
 * here may, as a side effect, change the active menu item so that later
 * menu functions (that display the menus and breadcrumbs, for example)
 * act as if the user were in a different location on the site.
 */
function menu_execute_active_handler() {
  $menu = menu_get_menu();

  // Determine the menu item containing the callback.
  $path = $_GET['q'];
Dries's avatar
   
Dries committed
331
  while ($path && (!array_key_exists($path, $menu['path index']) || empty($menu['items'][$menu['path index'][$path]]['callback']))) {
Dries's avatar
   
Dries committed
332
333
    $path = substr($path, 0, strrpos($path, '/'));
  }
Dries's avatar
   
Dries committed
334
335
336
  if (!array_key_exists($path, $menu['path index'])) {
    return MENU_NOT_FOUND;
  }
Dries's avatar
   
Dries committed
337
338
  $mid = $menu['path index'][$path];

Dries's avatar
   
Dries committed
339
  if (empty($menu['items'][$mid]['callback'])) {
Dries's avatar
   
Dries committed
340
    return MENU_NOT_FOUND;
Dries's avatar
   
Dries committed
341
342
  }

Dries's avatar
   
Dries committed
343
344
345
346
347
  if (!_menu_item_is_accessible(menu_get_active_item())) {
    return MENU_ACCESS_DENIED;
  }

  // We found one, and are allowed to execute it.
Dries's avatar
   
Dries committed
348
  $arguments = array_key_exists('callback arguments', $menu['items'][$mid]) ? $menu['items'][$mid]['callback arguments'] : array();
Dries's avatar
   
Dries committed
349
350
  $arg = substr($_GET['q'], strlen($menu['items'][$mid]['path']) + 1);
  if (strlen($arg)) {
351
    $arguments = array_merge($arguments, explode('/', $arg));
Dries's avatar
   
Dries committed
352
  }
353

Dries's avatar
   
Dries committed
354
  return call_user_func_array($menu['items'][$mid]['callback'], $arguments);
Dries's avatar
   
Dries committed
355
356
}

Dries's avatar
   
Dries committed
357
/**
358
 * Returns the ID of the active menu item.
Dries's avatar
   
Dries committed
359
360
 */
function menu_get_active_item() {
Dries's avatar
   
Dries committed
361
362
363
  return menu_set_active_item();
}

Dries's avatar
   
Dries committed
364
365
366
/**
 * Sets the path of the active menu item.
 */
Dries's avatar
   
Dries committed
367
function menu_set_active_item($path = NULL) {
368
369
  static $stored_mid;
  $menu = menu_get_menu();
Dries's avatar
   
Dries committed
370

371
  if (is_null($stored_mid) || !empty($path)) {
Dries's avatar
   
Dries committed
372
    if (empty($path)) {
373
      $path = $_GET['q'];
Dries's avatar
   
Dries committed
374
375
376
377
    }
    else {
      $_GET['q'] = $path;
    }
Dries's avatar
   
Dries committed
378

Dries's avatar
   
Dries committed
379
    while ($path && !array_key_exists($path, $menu['path index'])) {
380
      $path = substr($path, 0, strrpos($path, '/'));
Dries's avatar
   
Dries committed
381
    }
Dries's avatar
   
Dries committed
382
    $stored_mid = array_key_exists($path, $menu['path index']) ? $menu['path index'][$path] : 0;
Dries's avatar
   
Dries committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396

    // Search for default local tasks to activate instead of this item.
    $continue = TRUE;
    while ($continue) {
      $continue = FALSE;
      if (array_key_exists('children', $menu['items'][$stored_mid])) {
        foreach ($menu['items'][$stored_mid]['children'] as $cid) {
          if ($menu['items'][$cid]['type'] & MENU_LINKS_TO_PARENT) {
            $stored_mid = $cid;
            $continue = TRUE;
          }
        }
      }
    }
Dries's avatar
   
Dries committed
397
398
  }

399
  return $stored_mid;
Dries's avatar
   
Dries committed
400
401
}

Dries's avatar
   
Dries committed
402
403
404
405
406
407
408
409
410
/**
 * Returns the ID of the current menu item or, if the current item is a
 * local task, the menu item to which this task is attached.
 */
function menu_get_active_nontask_item() {
  $menu = menu_get_menu();
  $mid = menu_get_active_item();

  // Find the first non-task item:
Dries's avatar
   
Dries committed
411
  while ($mid && ($menu['items'][$mid]['type'] & MENU_IS_LOCAL_TASK)) {
Dries's avatar
   
Dries committed
412
413
414
415
416
417
418
419
    $mid = $menu['items'][$mid]['pid'];
  }

  if ($mid) {
    return $mid;
  }
}

Dries's avatar
   
Dries committed
420
/**
Dries's avatar
   
Dries committed
421
422
 * Returns the title of the active menu item.
 */
423
function menu_get_active_title() {
424
  $menu = menu_get_menu();
Dries's avatar
   
Dries committed
425

Dries's avatar
   
Dries committed
426
  if ($mid = menu_get_active_nontask_item()) {
Dries's avatar
   
Dries committed
427
    return $menu['items'][$mid]['title'];
428
429
  }
}
Dries's avatar
   
Dries committed
430

Dries's avatar
   
Dries committed
431
/**
Dries's avatar
   
Dries committed
432
433
 * Returns the help associated with the active menu item.
 */
434
function menu_get_active_help() {
Dries's avatar
   
Dries committed
435
436
  $path = $_GET['q'];
  $output = '';
Dries's avatar
   
Dries committed
437

Dries's avatar
   
Dries committed
438
439
440
441
  if (!_menu_item_is_accessible(menu_get_active_item())) {
    // Don't return help text for areas the user cannot access.
    return;
  }
Dries's avatar
   
Dries committed
442

Dries's avatar
   
Dries committed
443
444
445
446
447
  foreach (module_list() as $name) {
    if (module_hook($name, 'help')) {
      if ($temp = module_invoke($name, 'help', $path)) {
        $output .= $temp . "\n";
      }
448
449
450
451
452
      if (module_hook('help', 'page')) {
        if (substr($path, 0, 6) == "admin/") {
          if (module_invoke($name, 'help', 'admin/help#' . substr($path, 6))) {
            $output .= theme("more_help_link", url('admin/help/' . substr($path, 6)));
          }
Dries's avatar
   
Dries committed
453
454
        }
      }
Dries's avatar
   
Dries committed
455
    }
Dries's avatar
   
Dries committed
456
  }
Dries's avatar
   
Dries committed
457
  return $output;
458
459
}

Dries's avatar
   
Dries committed
460
461
462
463
/**
 * Returns an array of rendered menu items in the active breadcrumb trail.
 */
function menu_get_active_breadcrumb() {
464
  $menu = menu_get_menu();
Dries's avatar
   
Dries committed
465

466
  $links[] = l(t('Home'), '');
467

Dries's avatar
   
Dries committed
468
  $trail = _menu_get_active_trail();
469
  foreach ($trail as $mid) {
Dries's avatar
   
Dries committed
470
    if ($menu['items'][$mid]['type'] & MENU_VISIBLE_IN_BREADCRUMB) {
471
      $links[] = menu_item_link($mid);
472
    }
Dries's avatar
   
Dries committed
473
474
  }

Dries's avatar
   
Dries committed
475
476
477
  // The last item in the trail is the page title; don't display it here.
  array_pop($links);

Dries's avatar
   
Dries committed
478
  return $links;
479
480
}

Dries's avatar
   
Dries committed
481
/**
Dries's avatar
   
Dries committed
482
 * Returns true when the menu item is in the active trail.
Dries's avatar
   
Dries committed
483
 */
Dries's avatar
   
Dries committed
484
function menu_in_active_trail($mid) {
Dries's avatar
   
Dries committed
485
  $trail = _menu_get_active_trail();
Dries's avatar
   
Dries committed
486

Dries's avatar
   
Dries committed
487
  return in_array($mid, $trail);
Dries's avatar
   
Dries committed
488
489
}

490
/**
Dries's avatar
   
Dries committed
491
492
493
 * Populate the database representation of the menu.
 *
 * This need only be called at the start of pages that modify the menu.
494
 */
Dries's avatar
   
Dries committed
495
function menu_rebuild() {
Dries's avatar
   
Dries committed
496
  // Clear the page cache, so that changed menus are reflected for anonymous users.
Dries's avatar
   
Dries committed
497
  cache_clear_all();
Dries's avatar
   
Dries committed
498
499
  // Also clear the menu cache.
  cache_clear_all('menu:', TRUE);
Dries's avatar
   
Dries committed
500

501
502
  _menu_build();

Dries's avatar
   
Dries committed
503
504
  if (module_exist('menu')) {
    $menu = menu_get_menu();
Dries's avatar
   
Dries committed
505

Dries's avatar
   
Dries committed
506
507
508
509
    $new_items = array();
    foreach ($menu['items'] as $mid => $item) {
      if ($mid < 0 && ($item['type'] & MENU_MODIFIABLE_BY_ADMIN)) {
        $new_mid = db_next_id('{menu}_mid');
510
511
512
513
514
515
        // Check explicitly for mid 1. If the database was improperly prefixed,
        // this would cause a nasty infinite loop.
        // TODO: have automatic prefixing through an installer to prevent this.
        if ($new_mid == 1) {
          $new_mid = db_next_id('{menu}_mid');
        }
Dries's avatar
   
Dries committed
516
517
518
519
520
521
522
523
524
525
526
527
528
        if (isset($new_items[$item['pid']])) {
          $new_pid = $new_items[$item['pid']]['mid'];
        }
        else {
          $new_pid = $item['pid'];
        }

        // Fix parent IDs for menu items already added.
        if ($item['children']) {
          foreach ($item['children'] as $child) {
            if (isset($new_items[$child])) {
              $new_items[$child]['pid'] = $new_mid;
            }
Dries's avatar
   
Dries committed
529
530
531
          }
        }

Dries's avatar
   
Dries committed
532
533
        $new_items[$mid] = array('mid' => $new_mid, 'pid' => $new_pid, 'path' => $item['path'], 'title' => $item['title'], 'description' => array_key_exists('description', $item) ? $item['description'] : '', 'weight' => $item['weight'], 'type' => $item['type']);
      }
Dries's avatar
   
Dries committed
534
535
    }

536
    if (count($new_items)) {
537
538
539
540
541
542
      foreach ($new_items as $item) {
        db_query('INSERT INTO {menu} (mid, pid, path, title, description, weight, type) VALUES (%d, %d, \'%s\', \'%s\', \'%s\', %d, %d)', $item['mid'], $item['pid'], $item['path'], $item['title'], $item['description'], $item['weight'], $item['type']);
      }

      // Rebuild the menu to account for the changes.
      _menu_build();
Dries's avatar
   
Dries committed
543
    }
Dries's avatar
   
Dries committed
544
  }
Dries's avatar
   
Dries committed
545
546
}

Dries's avatar
   
Dries committed
547
/**
548
549
550
551
 * Generate the HTML for a menu tree.
 *
 * @param $pid
 *   The parent id of the menu.
Dries's avatar
   
Dries committed
552
553
 *
 * @ingroup themeable
Dries's avatar
   
Dries committed
554
 */
555
556
557
558
559
560
561
562
563
564
565
566
567
function theme_menu_tree($pid = 1) {
  if ($tree = menu_tree($pid)) {
    return "\n<ul>\n". $tree ."\n</ul>\n";
  }
}

/**
 * Returns a rendered menu tree.
 *
 * @param $pid
 *   The parent id of the menu.
 */
function menu_tree($pid = 1) {
568
569
  $menu = menu_get_menu();
  $output = '';
Dries's avatar
   
Dries committed
570

571
572
  if (isset($menu['visible'][$pid]) && $menu['visible'][$pid]['children']) {
    foreach ($menu['visible'][$pid]['children'] as $mid) {
573
      $output .= theme('menu_item', $mid, menu_in_active_trail($mid) || ($menu['visible'][$mid]['type'] & MENU_EXPANDED) ? theme('menu_tree', $mid) : '', count($menu['visible'][$mid]['children']) == 0);
Dries's avatar
   
Dries committed
574
575
576
    }
  }

577
  return $output;
Dries's avatar
   
Dries committed
578
579
}

Dries's avatar
   
Dries committed
580
/**
581
 * Generate the HTML output for a single menu item.
Dries's avatar
   
Dries committed
582
583
 *
 * @param $mid
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
 *   The menu id of the item.
 * @param $children
 *   A string containing any rendered child items of this menu.
 * @param $leaf
 *   A boolean indicating whether this menu item is a leaf.
 *
 * @ingroup themeable
 */
function theme_menu_item($mid, $children = '', $leaf = TRUE) {
  return '<li class="'. ($leaf ? 'leaf' : ($children ? 'expanded' : 'collapsed')) .'">'. menu_item_link($mid) . $children ."</li>\n";
}

/**
 * Generate the HTML representing a given menu item ID.
 *
 * @param $item
 *   The menu item to render.
 * @param $link_mid
 *   The menu item which should be used to find the correct path.
Dries's avatar
   
Dries committed
603
604
 *
 * @ingroup themeable
Dries's avatar
   
Dries committed
605
 */
606
function theme_menu_item_link($item, $link_item) {
607
  return l($item['title'], $link_item['path'], array_key_exists('description', $item) ? array('title' => $item['description']) : array());
608
609
610
611
612
613
614
615
616
}

/**
 * Returns the rendered link to a menu item.
 *
 * @param $mid
 *   The menu item id to render.
 */
function menu_item_link($mid) {
Dries's avatar
   
Dries committed
617
618
  $menu = menu_get_menu();

Dries's avatar
   
Dries committed
619
620
621
622
623
  $link_mid = $mid;
  while ($menu['items'][$link_mid]['type'] & MENU_LINKS_TO_PARENT) {
    $link_mid = $menu['items'][$link_mid]['pid'];
  }

624
  return theme('menu_item_link', $menu['items'][$mid], $menu['items'][$link_mid]);
Dries's avatar
   
Dries committed
625
626
627
628
629
}

/**
 * Returns the rendered local tasks. The default implementation renders
 * them as tabs.
Dries's avatar
   
Dries committed
630
631
 *
 * @ingroup themeable
Dries's avatar
   
Dries committed
632
633
 */
function theme_menu_local_tasks() {
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
  $output = '';

  if ($primary = menu_primary_local_tasks()) {
    $output .= "<ul class=\"tabs primary\">\n". $primary ."</ul>\n";
  }
  if ($secondary = menu_secondary_local_tasks()) {
    $output .= "<ul class=\"tabs secondary\">\n". $secondary ."</ul>\n";
  }

  return $output;
}

/**
 * Returns the rendered HTML of the primary local tasks.
 */
function menu_primary_local_tasks() {
Dries's avatar
   
Dries committed
650
  $local_tasks = menu_get_local_tasks();
Dries's avatar
   
Dries committed
651
  $pid = menu_get_active_nontask_item();
Dries's avatar
   
Dries committed
652
  $output = '';
Dries's avatar
   
Dries committed
653

Dries's avatar
   
Dries committed
654
655
  if (count($local_tasks[$pid]['children'])) {
    foreach ($local_tasks[$pid]['children'] as $mid) {
656
      $output .= theme('menu_local_task', $mid, menu_in_active_trail($mid), TRUE);
Dries's avatar
   
Dries committed
657
    }
658
659
660
661
662
663
664
665
666
667
668
669
  }

  return $output;
}

/**
 * Returns the rendered HTML of the secondary local tasks.
 */
function menu_secondary_local_tasks() {
  $local_tasks = menu_get_local_tasks();
  $pid = menu_get_active_nontask_item();
  $output = '';
Dries's avatar
   
Dries committed
670

671
  if (count($local_tasks[$pid]['children'])) {
Dries's avatar
   
Dries committed
672
    foreach ($local_tasks[$pid]['children'] as $mid) {
Dries's avatar
   
Dries committed
673
      if (menu_in_active_trail($mid) && count($local_tasks[$mid]['children']) > 1) {
Dries's avatar
   
Dries committed
674
        foreach ($local_tasks[$mid]['children'] as $cid) {
675
          $output .= theme('menu_local_task', $cid, menu_in_active_trail($cid), FALSE);
Dries's avatar
   
Dries committed
676
677
678
679
        }
      }
    }
  }
680

Dries's avatar
   
Dries committed
681
682
683
684
  return $output;
}

/**
Dries's avatar
   
Dries committed
685
 * Generate the HTML representing a given menu item ID as a tab.
Dries's avatar
   
Dries committed
686
687
688
689
690
 *
 * @param $mid
 *   The menu ID to render.
 * @param $active
 *   Whether this tab or a subtab is the active menu item.
691
692
 * @param $primary
 *   Whether this tab is a primary tab or a subtab.
Dries's avatar
   
Dries committed
693
694
 *
 * @ingroup themeable
Dries's avatar
   
Dries committed
695
 */
696
function theme_menu_local_task($mid, $active, $primary) {
Dries's avatar
   
Dries committed
697
  if ($active) {
698
    return '<li class="active">'. menu_item_link($mid) ."</li>\n";
Dries's avatar
   
Dries committed
699
700
  }
  else {
701
    return '<li>'. menu_item_link($mid) ."</li>\n";
Dries's avatar
   
Dries committed
702
703
704
  }
}

705
/**
Dries's avatar
   
Dries committed
706
 * @} End of "defgroup menu".
707
 */
Dries's avatar
   
Dries committed
708
709

/**
Dries's avatar
   
Dries committed
710
 * Returns an array with the menu items that lead to the current menu item.
Dries's avatar
   
Dries committed
711
 */
Dries's avatar
   
Dries committed
712
713
function _menu_get_active_trail() {
  static $trail;
Dries's avatar
   
Dries committed
714

Dries's avatar
   
Dries committed
715
716
  if (!isset($trail)) {
    $menu = menu_get_menu();
Dries's avatar
   
Dries committed
717

Dries's avatar
   
Dries committed
718
    $trail = array();
Dries's avatar
   
Dries committed
719

Dries's avatar
   
Dries committed
720
    $mid = menu_get_active_item();
Dries's avatar
   
Dries committed
721

Dries's avatar
   
Dries committed
722
723
724
725
726
727
    // Follow the parents up the chain to get the trail.
    while ($mid && $menu['items'][$mid]) {
      array_unshift($trail, $mid);
      $mid = $menu['items'][$mid]['pid'];
    }
  }
Dries's avatar
   
Dries committed
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
  return $trail;
}

/**
 * Comparator routine for use in sorting menu items.
 */
function _menu_sort($a, $b) {
  $menu = menu_get_menu();

  $a = &$menu['items'][$a];
  $b = &$menu['items'][$b];

  return $a['weight'] < $b['weight'] ? -1 : ($a['weight'] > $b['weight'] ? 1 : ($a['title'] < $b['title'] ? -1 : 1));
}

Dries's avatar
   
Dries committed
743
/**
744
 * Build the menu by querying both modules and the database.
Dries's avatar
   
Dries committed
745
 */
Dries's avatar
   
Dries committed
746
function _menu_build() {
747
748
  global $_menu;
  global $user;
Dries's avatar
   
Dries committed
749

750
751
752
753
754
  // Start from a clean slate.
  $_menu = array();

  $_menu['path index'] = array();
  // Set up items array, including default "Navigation" menu.
Dries's avatar
   
Dries committed
755
  $_menu['items'] = array(
Dries's avatar
   
Dries committed
756
757
    0 => array('path' => '', 'title' => '', 'type' => MENU_IS_ROOT),
    1 => array('pid' => 0, 'path' => '', 'title' => t('Navigation'), 'weight' => -50, 'access' => TRUE, 'type' => MENU_IS_ROOT | MENU_VISIBLE_IN_TREE)
Dries's avatar
   
Dries committed
758
759
760
    );

  // Build a sequential list of all menu items.
Dries's avatar
   
Dries committed
761
  $menu_item_list = module_invoke_all('menu', TRUE);
762
763
764
765

  // Menu items not in the DB get temporary negative IDs.
  $temp_mid = -1;

Dries's avatar
   
Dries committed
766
  foreach ($menu_item_list as $item) {
Dries's avatar
   
Dries committed
767
768
769
770
    if (!array_key_exists('path', $item)) {
      $item['path'] = '';
    }
    if (!array_key_exists('type', $item)) {
Dries's avatar
   
Dries committed
771
772
      $item['type'] = MENU_NORMAL_ITEM;
    }
Dries's avatar
   
Dries committed
773
774
775
    if (!array_key_exists('weight', $item)) {
      $item['weight'] = 0;
    }
776
    $mid = $temp_mid;
Dries's avatar
   
Dries committed
777
    if (array_key_exists($item['path'], $_menu['path index'])) {
Dries's avatar
   
Dries committed
778
779
780
781
782
      // Newer menu items overwrite older ones.
      unset($_menu['items'][$_menu['path index'][$item['path']]]);
    }
    $_menu['items'][$mid] = $item;
    $_menu['path index'][$item['path']] = $mid;
783
784

    $temp_mid--;
785
786
  }

787
788
  // Now fetch items from the DB, reassigning menu IDs as needed.
  if (module_exist('menu')) {
Dries's avatar
   
Dries committed
789
    $result = db_query('SELECT * FROM {menu} ORDER BY mid ASC');
790
    while ($item = db_fetch_object($result)) {
791
792
      // Handle URL aliases if entered in menu administration.
      $item->path = drupal_get_normal_path($item->path);
Dries's avatar
   
Dries committed
793
794
      if (array_key_exists($item->path, $_menu['path index'])) {
        // The path is already declared.
Dries's avatar
   
Dries committed
795
        $old_mid = $_menu['path index'][$item->path];
Dries's avatar
   
Dries committed
796
797
798
799
800
801
802
803
804
        if ($old_mid < 0) {
          // It had a temporary ID, so use a permanent one.
          $_menu['items'][$item->mid] = $_menu['items'][$old_mid];
          unset($_menu['items'][$old_mid]);
          $_menu['path index'][$item->path] = $item->mid;
        }
        else {
          // It has a permanent ID. Only replace with non-custom menu items.
          if ($item->type & MENU_CREATED_BY_ADMIN) {
Dries's avatar
   
Dries committed
805
            $_menu['items'][$item->mid] = array('path' => $item->path, 'access' => TRUE, 'callback' => '');
Dries's avatar
   
Dries committed
806
807
808
809
810
811
          }
          else {
            // Leave the old item around as a shortcut to this one.
            $_menu['items'][$item->mid] = $_menu['items'][$old_mid];
            $_menu['path index'][$item->path] = $item->mid;
          }
Dries's avatar
   
Dries committed
812
813
        }
      }
Dries's avatar
   
Dries committed
814
815
816
      else {
        // The path was not declared, so this is a custom item or an orphaned one.
        if ($item->type & MENU_CREATED_BY_ADMIN) {
Dries's avatar
   
Dries committed
817
          $_menu['items'][$item->mid] = array('path' => $item->path, 'access' => TRUE, 'callback' => '');
Dries's avatar
   
Dries committed
818
819
820
          if (!empty($item->path)) {
            $_menu['path index'][$item->path] = $item->mid;
          }
Dries's avatar
   
Dries committed
821
        }
Dries's avatar
   
Dries committed
822
      }
Dries's avatar
   
Dries committed
823
824
825
826
827
828
829
830
831

      // If the administrator has changed the item, reflect the change.
      if ($item->type & MENU_MODIFIED_BY_ADMIN) {
        $_menu['items'][$item->mid]['title'] = $item->title;
        $_menu['items'][$item->mid]['description'] = $item->description;
        $_menu['items'][$item->mid]['pid'] = $item->pid;
        $_menu['items'][$item->mid]['weight'] = $item->weight;
        $_menu['items'][$item->mid]['type'] = $item->type;
      }
832
833
834
    }
  }

Dries's avatar
   
Dries committed
835
836
  // Associate parent and child menu items.
  _menu_find_parents($_menu['items']);
Dries's avatar
   
Dries committed
837

838
  // Prepare to display trees to the user as required.
Dries's avatar
   
Dries committed
839
840
841
842
843
844
845
846
847
848
849
850
  _menu_build_visible_tree();
}

/**
 * Determine whether the given menu item is accessible to the current user.
 *
 * Use this instead of just checking the "access" property of a menu item
 * to properly handle items with fall-through semantics.
 */
function _menu_item_is_accessible($mid) {
  $menu = menu_get_menu();

Dries's avatar
   
Dries committed
851
  // Follow the path up to find the first "access" attribute.
Dries's avatar
   
Dries committed
852
  $path = $menu['items'][$mid]['path'];
Dries's avatar
   
Dries committed
853
  while ($path && (!array_key_exists($path, $menu['path index']) || !array_key_exists('access', $menu['items'][$menu['path index'][$path]]))) {
Dries's avatar
   
Dries committed
854
855
    $path = substr($path, 0, strrpos($path, '/'));
  }
Dries's avatar
   
Dries committed
856
857
858
  if (empty($path)) {
    return FALSE;
  }
Dries's avatar
   
Dries committed
859
  return $menu['items'][$menu['path index'][$path]]['access'];
Dries's avatar
   
Dries committed
860
861
}

Dries's avatar
   
Dries committed
862
/**
863
864
865
866
 * Find all visible items in the menu tree, for ease in displaying to user.
 *
 * Since this is only for display, we only need title, path, and children
 * for each item.
Dries's avatar
   
Dries committed
867
 */
Dries's avatar
   
Dries committed
868
function _menu_build_visible_tree($pid = 0) {
869
  global $_menu;
Dries's avatar
   
Dries committed
870

871
872
  if (isset($_menu['items'][$pid])) {
    $parent = $_menu['items'][$pid];
873

874
    $children = array();
Dries's avatar
   
Dries committed
875
    if (array_key_exists('children', $parent)) {
876
877
      usort($parent['children'], '_menu_sort');
      foreach ($parent['children'] as $mid) {
Dries's avatar
   
Dries committed
878
        $children = array_merge($children, _menu_build_visible_tree($mid));
Dries's avatar
   
Dries committed
879
880
      }
    }
Dries's avatar
   
Dries committed
881
882
883
    $visible = ($parent['type'] & MENU_VISIBLE_IN_TREE) ||
      ($parent['type'] & MENU_VISIBLE_IF_HAS_CHILDREN && count($children) > 0);
    $allowed = _menu_item_is_accessible($pid);
Dries's avatar
   
Dries committed
884

Dries's avatar
   
Dries committed
885
    if (($parent['type'] & MENU_IS_ROOT) || ($visible && $allowed)) {
Dries's avatar
   
Dries committed
886
      $_menu['visible'][$pid] = array('title' => $parent['title'], 'path' => $parent['path'], 'children' => $children, 'type' => $parent['type']);
Dries's avatar
   
Dries committed
887
888
889
      foreach ($children as $mid) {
        $_menu['visible'][$mid]['pid'] = $pid;
      }
890
891
892
893
894
895
      return array($pid);
    }
    else {
      return $children;
    }
  }
896

897
898
  return array();
}
899

Dries's avatar
   
Dries committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
/**
 * Account for menu items that are only defined at certain paths, so will not
 * be cached.
 *
 * We don't support the full range of menu item options for these menu items. We
 * don't support MENU_VISIBLE_IF_HAS_CHILDREN, and we require parent items to be
 * declared before their children.
 */
function _menu_append_contextual_items() {
  global $_menu;

  // Build a sequential list of all menu items.
  $menu_item_list = module_invoke_all('menu', FALSE);

  // Menu items not in the DB get temporary negative IDs.
  $temp_mid = min(array_keys($_menu['items'])) - 1;
  $new_items = array();

  foreach ($menu_item_list as $item) {
    if (array_key_exists($item['path'], $_menu['path index'])) {
      // The menu item already exists, so just add appropriate callback information.
      $mid = $_menu['path index'][$item['path']];

      $_menu['items'][$mid]['access'] = $item['access'];
      $_menu['items'][$mid]['callback'] = $item['callback'];
      $_menu['items'][$mid]['callback arguments'] = $item['callback arguments'];
    }
    else {
      if (!array_key_exists('path', $item)) {
        $item['path'] = '';
      }
      if (!array_key_exists('type', $item)) {
        $item['type'] = MENU_NORMAL_ITEM;
      }
      if (!array_key_exists('weight', $item)) {
        $item['weight'] = 0;
      }
      $_menu['items'][$temp_mid] = $item;
      $_menu['path index'][$item['path']] = $temp_mid;
      $new_items[$temp_mid] = $item;
      $temp_mid--;
    }
  }

  // Establish parent-child relationships.
  _menu_find_parents($new_items);

  // Add new items to the visible tree if necessary.
  foreach ($new_items as $mid => $item) {
    $item = $_menu['items'][$mid];
    if (($item['type'] & MENU_VISIBLE_IN_TREE) && _menu_item_is_accessible($mid)) {
      $pid = $item['pid'];
      while ($pid && !array_key_exists($pid, $_menu['visible'])) {
        $pid = $_menu['items'][$pid]['pid'];
      }
      $_menu['visible'][$mid] = array('title' => $item['title'], 'path' => $item['path'], 'pid' => $pid);
      $_menu['visible'][$pid]['children'][] = $mid;
      usort($_menu['visible'][$pid]['children'], '_menu_sort');
    }
  }
}

/**
 * Establish parent-child relationships.
 */
function _menu_find_parents(&$items) {
  global $_menu;

  foreach ($items as $mid => $item) {
    if (!isset($item['pid'])) {
      // Parent's location has not been customized, so figure it out using the path.
      $parent = $item['path'];
      do {
        $parent = substr($parent, 0, strrpos($parent, '/'));
      }
      while ($parent && !array_key_exists($parent, $_menu['path index']));

      $pid = $parent ? $_menu['path index'][$parent] : 1;
      $_menu['items'][$mid]['pid'] = $pid;
    }
    else {
      $pid = $item['pid'];
    }

    // Don't make root a child of itself.
    if ($mid) {
      if (isset ($_menu['items'][$pid])) {
        $_menu['items'][$pid]['children'][] = $mid;
      }
      else {
        // If parent is missing, it is a menu item that used to be defined
        // but is no longer. Default to a root-level "Navigation" menu item.
        $_menu['items'][1]['children'][] = $mid;
      }
    }
  }
}

Dries's avatar
   
Dries committed
998
999
1000
1001
1002
/**
 * Find all the items in the current local task tree.
 *
 * Since this is only for display, we only need title, path, and children
 * for each item.
Dries's avatar
   
Dries committed
1003
1004
1005
1006
1007
1008
1009
 *
 * At the close of this function, $_menu['local tasks'] is populated with the
 * menu items in the local task tree.
 *
 * @return
 *   TRUE if the local task tree is forked. It does not need to be displayed
 *   otherwise.
Dries's avatar
   
Dries committed
1010
 */
Dries's avatar
   
Dries committed
1011
function _menu_build_local_tasks($pid) {
Dries's avatar
   
Dries committed
1012
1013
  global $_menu;

Dries's avatar
   
Dries committed
1014
  $forked = FALSE;
Dries's avatar
   
Dries committed
1015

Dries's avatar
   
Dries committed
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
  if (isset($_menu['items'][$pid])) {
    $parent = $_menu['items'][$pid];

    $children = array();
    if (array_key_exists('children', $parent)) {
      foreach ($parent['children'] as $mid) {
        if (($_menu['items'][$mid]['type'] & MENU_IS_LOCAL_TASK) && _menu_item_is_accessible($mid)) {
          $children[] = $mid;
          // Beware short-circuiting || operator!
          $forked = _menu_build_local_tasks($mid) || $forked;
Dries's avatar
   
Dries committed
1026
1027
1028
        }
      }
    }
Dries's avatar
   
Dries committed
1029
1030
1031
1032
1033
1034
    usort($children, '_menu_sort');
    $forked = $forked || count($children) > 1;

    $_menu['local tasks'][$pid] = array('title' => $parent['title'], 'path' => $parent['path'], 'children' => $children);
    foreach ($children as $mid) {
      $_menu['local tasks'][$mid]['pid'] = $pid;
Dries's avatar
   
Dries committed
1035
1036
1037
    }
  }

Dries's avatar
   
Dries committed
1038
  return $forked;
Dries's avatar
   
Dries committed
1039
1040
}

Dries's avatar
   
Dries committed
1041
?>