Code coverage for /20080809/includes/menu.inc

Line #Times calledCode
1
<?php
2
// $Id: menu.inc,v 1.282 2008/07/10 10:58:01 dries Exp $
3
4
/**
5
 * @file
6
 * API for the Drupal menu system.
7
 */
8
9
/**
10
 * @defgroup menu Menu system
11
 * @{
12
 * Define the navigation menus, and route page requests to code based on
URLs.
13
 *
14
 * The Drupal menu system drives both the navigation system from a user
15
 * perspective and the callback system that Drupal uses to respond to URLs
16
 * passed from the browser. For this reason, a good understanding of the
17
 * menu system is fundamental to the creation of complex modules.
18
 *
19
 * Drupal's menu system follows a simple hierarchy defined by paths.
20
 * Implementations of hook_menu() define menu items and assign them to
21
 * paths (which should be unique). The menu system aggregates these items
22
 * and determines the menu hierarchy from the paths. For example, if the
23
 * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
24
 * would form the structure:
25
 * - a
26
 *   - a/b
27
 *     - a/b/c/d
28
 *     - a/b/h
29
 * - e
30
 * - f/g
31
 * Note that the number of elements in the path does not necessarily
32
 * determine the depth of the menu item in the tree.
33
 *
34
 * When responding to a page request, the menu system looks to see if the
35
 * path requested by the browser is registered as a menu item with a
36
 * callback. If not, the system searches up the menu tree for the most
37
 * complete match with a callback it can find. If the path a/b/i is
38
 * requested in the tree above, the callback for a/b would be used.
39
 *
40
 * The found callback function is called with any arguments specified
41
 * in the "page arguments" attribute of its menu item. The
42
 * attribute must be an array. After these arguments, any remaining
43
 * components of the path are appended as further arguments. In this
44
 * way, the callback for a/b above could respond to a request for
45
 * a/b/i differently than a request for a/b/j.
46
 *
47
 * For an illustration of this process, see page_example.module.
48
 *
49
 * Access to the callback functions is also protected by the menu system.
50
 * The "access callback" with an optional "access arguments" of each menu
51
 * item is called before the page callback proceeds. If this returns TRUE,
52
 * then access is granted; if FALSE, then access is denied. Menu items may
53
 * omit this attribute to use the value provided by an ancestor item.
54
 *
55
 * In the default Drupal interface, you will notice many links rendered as
56
 * tabs. These are known in the menu system as "local tasks", and they are
57
 * rendered as tabs by default, though other presentations are possible.
58
 * Local tasks function just as other menu items in most respects. It is
59
 * convention that the names of these tasks should be short verbs if
60
 * possible. In addition, a "default" local task should be provided for
61
 * each set. When visiting a local task's parent menu item, the default
62
 * local task will be rendered as if it is selected; this provides for a
63
 * normal tab user experience. This default task is special in that it
64
 * links not to its provided path, but to its parent item's path instead.
65
 * The default task's path is only used to place it appropriately in the
66
 * menu hierarchy.
67
 *
68
 * Everything described so far is stored in the menu_router table. The
69
 * menu_links table holds the visible menu links. By default these are
70
 * derived from the same hook_menu definitions, however you are free to
71
 * add more with menu_link_save().
72
 */
73
74
/**
75
 * @name Menu flags
76
 * @{
77
 * Flags for use in the "type" attribute of menu items.
78
 */
79
80
/**
81
 * Internal menu flag -- menu item is the root of the menu tree.
82
 */
832027
define('MENU_IS_ROOT', 0x0001);
84
85
/**
86
 * Internal menu flag -- menu item is visible in the menu tree.
87
 */
882027
define('MENU_VISIBLE_IN_TREE', 0x0002);
89
90
/**
91
 * Internal menu flag -- menu item is visible in the breadcrumb.
92
 */
932027
define('MENU_VISIBLE_IN_BREADCRUMB', 0x0004);
94
95
/**
96
 * Internal menu flag -- menu item links back to its parnet.
97
 */
982027
define('MENU_LINKS_TO_PARENT', 0x0008);
99
100
/**
101
 * Internal menu flag -- menu item can be modified by administrator.
102
 */
1032027
define('MENU_MODIFIED_BY_ADMIN', 0x0020);
104
105
/**
106
 * Internal menu flag -- menu item was created by administrator.
107
 */
1082027
define('MENU_CREATED_BY_ADMIN', 0x0040);
109
110
/**
111
 * Internal menu flag -- menu item is a local task.
112
 */
1132027
define('MENU_IS_LOCAL_TASK', 0x0080);
114
115
/**
116
 * @} End of "Menu flags".
117
 */
118
119
/**
120
 * @name Menu item types
121
 * @{
122
 * Menu item definitions provide one of these constants, which are
shortcuts for
123
 * combinations of the above flags.
124
 */
125
126
/**
127
 * Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.
128
 *
129
 * Normal menu items show up in the menu tree and can be moved/hidden by
130
 * the administrator. Use this for most menu items. It is the default value
if
131
 * no menu item type is specified.
132
 */
1332027
define('MENU_NORMAL_ITEM', MENU_VISIBLE_IN_TREE |
MENU_VISIBLE_IN_BREADCRUMB);
134
135
/**
136
 * Menu type -- A hidden, internal callback, typically used for API calls.
137
 *
138
 * Callbacks simply register a path so that the correct function is fired
139
 * when the URL is accessed. They are not shown in the menu.
140
 */
1412027
define('MENU_CALLBACK', MENU_VISIBLE_IN_BREADCRUMB);
142
143
/**
144
 * Menu type -- A normal menu item, hidden until enabled by an
administrator.
145
 *
146
 * Modules may "suggest" menu items that the administrator may enable. They
act
147
 * just as callbacks do until enabled, at which time they act like normal
items.
148
 * Note for the value: 0x0010 was a flag which is no longer used, but this
way
149
 * the values of MENU_CALLBACK and MENU_SUGGESTED_ITEM are separate.
150
 */
1512027
define('MENU_SUGGESTED_ITEM', MENU_VISIBLE_IN_BREADCRUMB | 0x0010);
152
153
/**
154
 * Menu type -- A task specific to the parent item, usually rendered as a
tab.
155
 *
156
 * Local tasks are menu items that describe actions to be performed on
their
157
 * parent item. An example is the path "node/52/edit", which performs the
158
 * "edit" task on "node/52".
159
 */
1602027
define('MENU_LOCAL_TASK', MENU_IS_LOCAL_TASK);
161
162
/**
163
 * Menu type -- The "default" local task, which is initially active.
164
 *
165
 * Every set of local tasks should provide one "default" task, that links
to the
166
 * same path as its parent when clicked.
167
 */
1682027
define('MENU_DEFAULT_LOCAL_TASK', MENU_IS_LOCAL_TASK |
MENU_LINKS_TO_PARENT);
169
170
/**
171
 * @} End of "Menu item types".
172
 */
173
174
/**
175
 * @name Menu status codes
176
 * @{
177
 * Status codes for menu callbacks.
178
 */
179
180
/**
181
 * Internal menu status code -- Menu item was found.
182
 */
1832027
define('MENU_FOUND', 1);
184
185
/**
186
 * Internal menu status code -- Menu item was not found.
187
 */
1882027
define('MENU_NOT_FOUND', 2);
189
190
/**
191
 * Internal menu status code -- Menu item access is denied.
192
 */
1932027
define('MENU_ACCESS_DENIED', 3);
194
195
/**
196
 * Internal menu status code -- Menu item inaccessible because site is
offline.
197
 */
1982027
define('MENU_SITE_OFFLINE', 4);
199
200
/**
201
 * @} End of "Menu status codes".
202
 */
203
204
/**
205
 * @Name Menu tree parameters
206
 * @{
207
 * Menu tree
208
 */
209
210
 /**
211
 * The maximum number of path elements for a menu callback
212
 */
2132027
define('MENU_MAX_PARTS', 7);
214
215
216
/**
217
 * The maximum depth of a menu links tree - matches the number of p
columns.
218
 */
2192027
define('MENU_MAX_DEPTH', 9);
220
221
222
/**
223
 * @} End of "Menu tree parameters".
224
 */
225
226
/**
227
 * Returns the ancestors (and relevant placeholders) for any given path.
228
 *
229
 * For example, the ancestors of node/12345/edit are:
230
 * - node/12345/edit
231
 * - node/12345/%
232
 * - node/%/edit
233
 * - node/%/%
234
 * - node/12345
235
 * - node/%
236
 * - node
237
 *
238
 * To generate these, we will use binary numbers. Each bit represents a
239
 * part of the path. If the bit is 1, then it represents the original
240
 * value while 0 means wildcard. If the path is node/12/edit/foo
241
 * then the 1011 bitstring represents node/%/edit/foo where % means that
242
 * any argument matches that part.  We limit ourselves to using binary
243
 * numbers that correspond the patterns of wildcards of router items that
244
 * actually exists.  This list of 'masks' is built in menu_rebuild().
245
 *
246
 * @param $parts
247
 *   An array of path parts, for the above example
248
 *   array('node', '12345', 'edit').
249
 * @return
250
 *   An array which contains the ancestors and placeholders. Placeholders
251
 *   simply contain as many '%s' as the ancestors.
252
 */
2532027
function menu_get_ancestors($parts) {
2542070
  $number_parts = count($parts);
2552070
  $placeholders = array();
2562070
  $ancestors = array();
2572070
  $length =  $number_parts - 1;
2582070
  $end = (1 << $number_parts) - 1;
2592070
  $masks = variable_get('menu_masks', array());
260
  // Only examine patterns that actually exist as router items (the
masks).
2612070
  foreach ($masks as $i) {
2622070
    if ($i > $end) {
263
      // Only look at masks that are not longer than the path of interest.
2642010
      continue;
2650
    }
2662070
    elseif ($i < (1 << $length)) {
267
      // We have exhausted the masks of a given length, so decrease the
length.
2681355
      --$length;
2691355
    }
2702070
    $current = '';
2712070
    for ($j = $length; $j >= 0; $j--) {
2722070
      if ($i & (1 << $j)) {
2732070
        $current .= $parts[$length - $j];
2742070
      }
275
      else {
2761355
        $current .= '%';
277
      }
2782070
      if ($j) {
2791355
        $current .= '/';
2801355
      }
2812070
    }
2822070
    $placeholders[] = "'%s'";
2832070
    $ancestors[] = $current;
2842070
  }
2852070
  return array($ancestors, $placeholders);
2860
}
287
288
/**
289
 * The menu system uses serialized arrays stored in the database for
290
 * arguments. However, often these need to change according to the
291
 * current path. This function unserializes such an array and does the
292
 * necessary change.
293
 *
294
 * Integer values are mapped according to the $map parameter. For
295
 * example, if unserialize($data) is array('view', 1) and $map is
296
 * array('node', '12345') then 'view' will not be changed because
297
 * it is not an integer, but 1 will as it is an integer. As $map[1]
298
 * is '12345', 1 will be replaced with '12345'. So the result will
299
 * be array('node_load', '12345').
300
 *
301
 * @param @data
302
 *   A serialized array.
303
 * @param @map
304
 *   An array of potential replacements.
305
 * @return
306
 *   The $data array unserialized and mapped.
307
 */
3082027
function menu_unserialize($data, $map) {
3092000
  if ($data = unserialize($data)) {
3101767
    foreach ($data as $k => $v) {
3111767
      if (is_int($v)) {
3121655
        $data[$k] = isset($map[$v]) ? $map[$v] : '';
3131655
      }
3141767
    }
3151767
    return $data;
3160
  }
317
  else {
3181765
    return array();
319
  }
3200
}
321
322
323
324
/**
325
 * Replaces the statically cached item for a given path.
326
 *
327
 * @param $path
328
 *   The path.
329
 * @param $router_item
330
 *   The router item. Usually you take a router entry from menu_get_item
and
331
 *   set it back either modified or to a different path. This lets you
modify the
332
 *   navigation block, the page title, the breadcrumb and the page help in
one
333
 *   call.
334
 */
3352027
function menu_set_item($path, $router_item) {
3360
  menu_get_item($path, $router_item);
3370
}
338
339
/**
340
 * Get a router item.
341
 *
342
 * @param $path
343
 *   The path, for example node/5. The function will find the
corresponding
344
 *   node/% item and return that.
345
 * @param $router_item
346
 *   Internal use only.
347
 * @return
348
 *   The router item, an associate array corresponding to one row in the
349
 *   menu_router table. The value of key map holds the loaded objects. The
350
 *   value of key access is TRUE if the current user can access this page.
351
 *   The values for key title, page_arguments, access_arguments will be
352
 *   filled in based on the database values and the objects loaded.
353
 */
3542027
function menu_get_item($path = NULL, $router_item = NULL) {
3552010
  static $router_items;
3562010
  if (!isset($path)) {
3572010
    $path = $_GET['q'];
3582010
  }
3592010
  if (isset($router_item)) {
3600
    $router_items[$path] = $router_item;
3610
  }
3622010
  if (!isset($router_items[$path])) {
3632010
    $original_map = arg(NULL, $path);
3642010
    $parts = array_slice($original_map, 0, MENU_MAX_PARTS);
3652010
    list($ancestors, $placeholders) = menu_get_ancestors($parts);
366
3672010
    if ($router_item = db_fetch_array(db_query_range('SELECT * FROM
{menu_router} WHERE path IN (' . implode (',', $placeholders) . ') ORDER BY
fit DESC', $ancestors, 0, 1))) {
3682005
      $map = _menu_translate($router_item, $original_map);
3692005
      if ($map === FALSE) {
3706
        $router_items[$path] = FALSE;
3716
        return FALSE;
3720
      }
3731999
      if ($router_item['access']) {
3741958
        $router_item['map'] = $map;
3751958
        $router_item['page_arguments'] =
array_merge(menu_unserialize($router_item['page_arguments'], $map),
array_slice($map, $router_item['number_parts']));
3761958
      }
3771999
    }
3782004
    $router_items[$path] = $router_item;
3792004
  }
3802010
  return $router_items[$path];
3810
}
382
383
/**
384
 * Execute the page callback associated with the current path
385
 */
3862027
function menu_execute_active_handler($path = NULL) {
3872010
  if (_menu_site_is_offline()) {
3880
    return MENU_SITE_OFFLINE;
3890
  }
3902010
  if (variable_get('menu_rebuild_needed', FALSE)) {
3910
    menu_rebuild();
3920
  }
3932010
  if ($router_item = menu_get_item($path)) {
3941999
    registry_load_path_files();
3951999
    if ($router_item['access']) {
3961958
      if (drupal_function_exists($router_item['page_callback'])) {
3971958
        return call_user_func_array($router_item['page_callback'],
$router_item['page_arguments']);
3980
      }
3990
    }
400
    else {
40141
      return MENU_ACCESS_DENIED;
402
    }
4030
  }
40411
  return MENU_NOT_FOUND;
4050
}
406
407
/**
408
 * Loads objects into the map as defined in the $item['load_functions'].
409
 *
410
 * @param $item
411
 *   A menu router or menu link item
412
 * @param $map
413
 *   An array of path arguments (ex: array('node', '5'))
414
 * @return
415
 *   Returns TRUE for success, FALSE if an object cannot be loaded.
416
 *   Names of object loading functions are placed in
$item['load_functions'].
417
 *   Loaded objects are placed in $map[]; keys are the same as keys in the
418
 *   $item['load_functions'] array.
419
 *   $item['access'] is set to FALSE if an object cannot be loaded.
420
 */
4212027
function _menu_load_objects(&$item, &$map) {
4222006
  if ($load_functions = $item['load_functions']) {
423
    // If someone calls this function twice, then unserialize will fail.
4241620
    if ($load_functions_unserialized = unserialize($load_functions)) {
4251620
      $load_functions = $load_functions_unserialized;
4261620
    }
4271620
    $path_map = $map;
4281620
    foreach ($load_functions as $index => $function) {
4291620
      if ($function) {
4301610
        $value = isset($path_map[$index]) ? $path_map[$index] : '';
4311610
        if (is_array($function)) {
432
          // Set up arguments for the load function. These were pulled
from
433
          // 'load arguments' in the hook_menu() entry, but they need
434
          // some processing. In this case the $function is the key to the
435
          // load_function array, and the value is the list of arguments.
436223
          list($function, $args) = each($function);
437223
          $load_functions[$index] = $function;
438
439
          // Some arguments are placeholders for dynamic items to process.
440223
          foreach ($args as $i => $arg) {
441223
            if ($arg === '%index') {
442
              // Pass on argument index to the load function, so multiple
443
              // occurances of the same placeholder can be identified.
444218
              $args[$i] = $index;
445218
            }
446223
            if ($arg === '%map') {
447
              // Pass on menu map by reference. The accepting function
must
448
              // also declare this as a reference if it wants to modify
449
              // the map.
450218
              $args[$i] = &$map;
451218
            }
452223
            if (is_int($arg)) {
4535
              $args[$i] = isset($path_map[$arg]) ? $path_map[$arg] : '';
4545
            }
455223
          }
456223
          array_unshift($args, $value);
457223
          $return = call_user_func_array($function, $args);
458223
        }
459
        else {
4601594
          $return = $function($value);
461
        }
462
        // If callback returned an error or there is no callback, trigger
404.
4631610
        if ($return === FALSE) {
46413
          $item['access'] = FALSE;
46513
          $map = FALSE;
46613
          return FALSE;
4670
        }
4681604
        $map[$index] = $return;
4691604
      }
4701614
    }
4711614
    $item['load_functions'] = $load_functions;
4721614
  }
4732000
  return TRUE;
4740
}
475
476
/**
477
 * Check access to a menu item using the access callback
478
 *
479
 * @param $item
480
 *   A menu router or menu link item
481
 * @param $map
482
 *   An array of path arguments (ex: array('node', '5'))
483
 * @return
484
 *   $item['access'] becomes TRUE if the item is accessible, FALSE
otherwise.
485
 */
4862027
function _menu_check_access(&$item, $map) {
487
  // Determine access callback, which will decide whether or not the
current
488
  // user has access to this path.
4892000
  $callback = empty($item['access_callback']) ? 0 :
trim($item['access_callback']);
490
  // Check for a TRUE or FALSE value.
4912000
  if (is_numeric($callback)) {
4921648
    $item['access'] = (bool)$callback;
4931648
  }
494
  else {
4951850
    $arguments = menu_unserialize($item['access_arguments'], $map);
496
    // As call_user_func_array is quite slow and user_access is a very
common
497
    // callback, it is worth making a special case for it.
4981850
    if ($callback == 'user_access') {
4991651
      $item['access'] = (count($arguments) == 1) ?
user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
5001651
    }
501
    else {
5021704
      $item['access'] = call_user_func_array($callback, $arguments);
503
    }
504
  }
5052000
}
506
507
/**
508
 * Localize the router item title using t() or another callback.
509
 *
510
 * Translate the title and description to allow storage of English title
511
 * strings in the database, yet display of them in the language required
512
 * by the current user.
513
 *
514
 * @param $item
515
 *   A menu router item or a menu link item.
516
 * @param $map
517
 *   The path as an array with objects already replaced. E.g., for path
518
 *   node/123 $map would be array('node', $node) where $node is the node
519
 *   object for node 123.
520
 * @param $link_translate
521
 *   TRUE if we are translating a menu link item; FALSE if we are
522
 *   translating a menu router item.
523
 * @return
524
 *   No return value.
525
 *   $item['title'] is localized according to $item['title_callback'].
526
 *   If an item's callback is check_plain(), $item['options']['html']
becomes
527
 *   TRUE.
528
 *   $item['description'] is translated using t().
529
 *   When doing link translation and the
$item['options']['attributes']['title']
530
 *   (link title attribute) matches the description, it is translated as
well.
531
 */
5322027
function _menu_item_localize(&$item, $map, $link_translate = FALSE) {
5332000
  $callback = $item['title_callback'];
5342000
  $item['localized_options'] = $item['options'];
535
  // If we are not doing link translation or if the title matches the
536
  // link title of its router item, localize it.
5372000
  if (!$link_translate || (!empty($item['title']) && ($item['title'] ==
$item['link_title']))) {
538
    // t() is a special case. Since it is used very close to all the time,
539
    // we handle it directly instead of using indirect, slower methods.
5402000
    if ($callback == 't') {
5411950
      if (empty($item['title_arguments'])) {
5421950
        $item['title'] = t($item['title']);
5431950
      }
544
      else {
5450
        $item['title'] = t($item['title'],
menu_unserialize($item['title_arguments'], $map));
546
      }
5471950
    }
5481116
    elseif ($callback) {
5491116
      if (empty($item['title_arguments'])) {
550179
        $item['title'] = $callback($item['title']);
551179
      }
552
      else {
5531079
        $item['title'] = call_user_func_array($callback,
menu_unserialize($item['title_arguments'], $map));
554
      }
555
      // Avoid calling check_plain again on l() function.
5561116
      if ($callback == 'check_plain') {
557226
        $item['localized_options']['html'] = TRUE;
558226
      }
5591116
    }
5602000
  }
5611510
  elseif ($link_translate) {
5621510
    $item['title'] = $item['link_title'];
5631510
  }
564
565
  // Translate description, see the motivation above.
5662000
  if (!empty($item['description'])) {
567537
    $original_description = $item['description'];
568537
    $item['description'] = t($item['description']);
569537
    if ($link_translate && isset($item['options']['attributes']['title'])
&& $item['options']['attributes']['title'] == $original_description) {
570217
      $item['localized_options']['attributes']['title'] =
$item['description'];
571217
    }
572537
  }
5732000
}
574
575
/**
576
 * Handles dynamic path translation and menu access control.
577
 *
578
 * When a user arrives on a page such as node/5, this function determines
579
 * what "5" corresponds to, by inspecting the page's menu path definition,
580
 * node/%node. This will call node_load(5) to load the corresponding node
581
 * object.
582
 *
583
 * It also works in reverse, to allow the display of tabs and menu items
which
584
 * contain these dynamic arguments, translating node/%node to node/5.
585
 *
586
 * Translation of menu item titles and descriptions are done here to
587
 * allow for storage of English strings in the database, and translation
588
 * to the language required to generate the current page
589
 *
590
 * @param $router_item
591
 *   A menu router item
592
 * @param $map
593
 *   An array of path arguments (ex: array('node', '5'))
594
 * @param $to_arg
595
 *   Execute $item['to_arg_functions'] or not. Use only if you want to
render a
596
 *   path from the menu table, for example tabs.
597
 * @return
598
 *   Returns the map with objects loaded as defined in the
599
 *   $item['load_functions. $item['access'] becomes TRUE if the item is
600
 *   accessible, FALSE otherwise. $item['href'] is set according to the
map.
601
 *   If an error occurs during calling the load_functions (like trying to
load
602
 *   a non existing node) then this function return FALSE.
603
 */
6042027
function _menu_translate(&$router_item, $map, $to_arg = FALSE) {
6052005
  $path_map = $map;
6062005
  if (!_menu_load_objects($router_item, $map)) {
607
    // An error occurred loading an object.
60813
    $router_item['access'] = FALSE;
60913
    return FALSE;
6100
  }
6111999
  if ($to_arg) {
6121437
    _menu_link_map_translate($path_map, $router_item['to_arg_functions']);
6131437
  }
614
615
  // Generate the link path for the page request or local tasks.
6161999
  $link_map = explode('/', $router_item['path']);
6171999
  for ($i = 0; $i < $router_item['number_parts']; $i++) {
6181999
    if ($link_map[$i] == '%') {
619713
      $link_map[$i] = $path_map[$i];
620713
    }
6211999
  }
6221999
  $router_item['href'] = implode('/', $link_map);
6231999
  $router_item['options'] = array();
6241999
  _menu_check_access($router_item, $map);
625
626
  // For performance, don't localize an item the user can't access.
6271999
  if ($router_item['access']) {
6281958
    _menu_item_localize($router_item, $map);
6291958
  }
630
6311999
  return $map;
6320
}
633
634
/**
635
 * This function translates the path elements in the map using any to_arg
636
 * helper function. These functions take an argument and return an object.
637
 * See http://drupal.org/node/109153 for more information.
638
 *
639
 * @param map
640
 *   An array of path arguments (ex: array('node', '5'))
641
 * @param $to_arg_functions
642
 *   An array of helper function (ex: array(2 => 'menu_tail_to_arg'))
643
 */
6442027
function _menu_link_map_translate(&$map, $to_arg_functions) {
6451510
  if ($to_arg_functions) {
6461498
    $to_arg_functions = unserialize($to_arg_functions);
6471498
    foreach ($to_arg_functions as $index => $function) {
648
      // Translate place-holders into real values.
6491498
      $arg = $function(!empty($map[$index]) ? $map[$index] : '', $map,
$index);
6501498
      if (!empty($map[$index]) || isset($arg)) {
6511498
        $map[$index] = $arg;
6521498
      }
653
      else {
6540
        unset($map[$index]);
655
      }
6561498
    }
6571498
  }
6581510
}
659
6602027
function menu_tail_to_arg($arg, $map, $index) {
6613
  return implode('/', array_slice($map, $index));
6620
}
663
664
/**
665
 * This function is similar to _menu_translate() but does link-specific
666
 * preparation such as always calling to_arg functions
667
 *
668
 * @param $item
669
 *   A menu link
670
 * @return
671
 *   Returns the map of path arguments with objects loaded as defined in
the
672
 *   $item['load_functions'].
673
 *   $item['access'] becomes TRUE if the item is accessible, FALSE
otherwise.
674
 *   $item['href'] is generated from link_path, possibly by to_arg
functions.
675
 *   $item['title'] is generated from link_title, and may be localized.
676
 *   $item['options'] is unserialized; it is also changed within the call
here
677
 *   to $item['localized_options'] by _menu_item_localize().
678
 */
6792027
function _menu_link_translate(&$item) {
6801510
  $item['options'] = unserialize($item['options']);
6811510
  if ($item['external']) {
6820
    $item['access'] = 1;
6830
    $map = array();
6840
    $item['href'] = $item['link_path'];
6850
    $item['title'] = $item['link_title'];
6860
    $item['localized_options'] = $item['options'];
6870
  }
688
  else {
6891510
    $map = explode('/', $item['link_path']);
6901510
    _menu_link_map_translate($map, $item['to_arg_functions']);
6911510
    $item['href'] = implode('/', $map);
692
693
    // Note - skip callbacks without real values for their arguments.
6941510
    if (strpos($item['href'], '%') !== FALSE) {
6951498
      $item['access'] = FALSE;
6961498
      return FALSE;
6970
    }
698
    // menu_tree_check_access() may set this ahead of time for links to
nodes.
6991510
    if (!isset($item['access'])) {
7001504
      if (!_menu_load_objects($item, $map)) {
701
        // An error occurred loading an object.
7020
        $item['access'] = FALSE;
7030
        return FALSE;
7040
      }
7051504
      _menu_check_access($item, $map);
7061504
    }
707
    // For performance, don't localize a link the user can't access.
7081510
    if ($item['access']) {
7091510
      _menu_item_localize($item, $map, TRUE);
7101510
    }
711
  }
712
713
  // Allow other customizations - e.g. adding a page-specific query string
to the
714
  // options array. For performance reasons we only invoke this hook if the
link
715
  // has the 'alter' flag set in the options array.
7161510
  if (!empty($item['options']['alter'])) {
7170
    drupal_alter('translated_menu_link', $item, $map);
7180
  }
719
7201510
  return $map;
7210
}
722
723
/**
724
 * Get a loaded object from a router item.
725
 *
726
 * menu_get_object() will provide you the current node on paths like
node/5,
727
 * node/5/revisions/48 etc. menu_get_object('user') will give you the user
728
 * account on user/5 etc. Note - this function should never be called
within a
729
 * _to_arg function (like user_current_to_arg()) since this may result in
an
730
 * infinite recursion.
731
 *
732
 * @param $type
733
 *   Type of the object. These appear in hook_menu definitons as %type.
Core
734
 *   provides aggregator_feed, aggregator_category, contact,
filter_format,
735
 *   forum_term, menu, menu_link, node, taxonomy_vocabulary, user. See the
736
 *   relevant {$type}_load function for more on each. Defaults to node.
737
 * @param $position
738
 *   The expected position for $type object. For node/%node this is 1, for
739
 *   comment/reply/%node this is 2. Defaults to 1.
740
 * @param $path
741
 *   See menu_get_item() for more on this. Defaults to the current path.
742
 */
7432027
function menu_get_object($type = 'node', $position = 1, $path = NULL) {
7441489
  $router_item = menu_get_item($path);
7451489
  if (isset($router_item['load_functions'][$position]) &&
!empty($router_item['map'][$position]) &&
$router_item['load_functions'][$position] == $type . '_load') {
746223
    return $router_item['map'][$position];
7470
  }
7481266
}
749
750
/**
751
 * Render a menu tree based on the current path.
752
 *
753
 * The tree is expanded based on the current path and dynamic paths are
also
754
 * changed according to the defined to_arg functions (for example the 'My
account'
755
 * link is changed from user/% to a link with the current user's uid).
756
 *
757
 * @param $menu_name
758
 *   The name of the menu.
759
 * @return
760
 *   The rendered HTML of that menu on the current page.
761
 */
7622027
function menu_tree($menu_name = 'navigation') {
7631476
  static $menu_output = array();
764
7651476
  if (!isset($menu_output[$menu_name])) {
7661476
    $tree = menu_tree_page_data($menu_name);
7671476
    $menu_output[$menu_name] = menu_tree_output($tree);
7681476
  }
7691476
  return $menu_output[$menu_name];
7700
}
771
772
/**
773
 * Returns a rendered menu tree.
774
 *
775
 * @param $tree
776
 *   A data structure representing the tree as returned from
menu_tree_data.
777
 * @return
778
 *   The rendered HTML of that data structure.
779
 */
7802027
function menu_tree_output($tree) {
7811476
  $output = '';
7821476
  $items = array();
783
784
  // Pull out just the menu items we are going to render so that we
785
  // get an accurate count for the first/last classes.
7861476
  foreach ($tree as $data) {
7871476
    if (!$data['link']['hidden']) {
7881070
      $items[] = $data;
7891070
    }
7901476
  }
791
7921476
  $num_items = count($items);
7931476
  foreach ($items as $i => $data) {
7941070
    $extra_class = NULL;
7951070
    if ($i == 0) {
7961070
      $extra_class = 'first';
7971070
    }
7981070
    if ($i == $num_items - 1) {
7991070
      $extra_class = 'last';
8001070
    }
8011070
    $link = theme('menu_item_link', $data['link']);
8021070
    if ($data['below']) {
803210
      $output .= theme('menu_item', $link, $data['link']['has_children'],
menu_tree_output($data['below']), $data['link']['in_active_trail'],
$extra_class);
804210
    }
805
    else {
8061070
      $output .= theme('menu_item', $link, $data['link']['has_children'],
'', $data['link']['in_active_trail'], $extra_class);
807
    }
8081070
  }
8091476
  return $output ? theme('menu_tree', $output) : '';
8100
}
811
812
/**
813
 * Get the data structure representing a named menu tree.
814
 *
815
 * Since this can be the full tree including hidden items, the data
returned
816
 * may be used for generating an an admin interface or a select.
817
 *
818
 * @param $menu_name
819
 *   The named menu links to return
820
 * @param $item
821
 *   A fully loaded menu link, or NULL.  If a link is supplied, only the
822
 *   path to root will be included in the returned tree- as if this link
823
 *   represented the current page in a visible menu.
824
 * @return
825
 *   An tree of menu links in an array, in the order they should be
rendered.
826
 */
8272027
function menu_tree_all_data($menu_name = 'navigation', $item = NULL) {
828141
  static $tree = array();
829
830
  // Use $mlid as a flag for whether the data being loaded is for the whole
tree.
831141
  $mlid = isset($item['mlid']) ? $item['mlid'] : 0;
832
  // Generate a cache ID (cid) specific for this $menu_name and $item.
833141
  $cid = 'links:' . $menu_name . ':all-cid:' . $mlid;
834
835141
  if (!isset($tree[$cid])) {
836
    // If the static variable doesn't have the data, check {cache_menu}.
837141
    $cache = cache_get($cid, 'cache_menu');
838141
    if ($cache && isset($cache->data)) {
839
      // If the cache entry exists, it will just be the cid for the actual
data.
840
      // This avoids duplication of large amounts of data.
841108
      $cache = cache_get($cache->data, 'cache_menu');
842108
      if ($cache && isset($cache->data)) {
843108
        $data = $cache->data;
844108
      }
845108
    }
846
    // If the tree data was not in the cache, $data will be NULL.
847141
    if (!isset($data)) {
848
      // Build and run the query, and build the tree.
84952
      if ($mlid) {
850
        // The tree is for a single item, so we need to match the values in
its
851
        // p columns and 0 (the top level) with the plid values of other
links.
85211
        $args = array(0);
85311
        for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
85411
          $args[] = $item["p$i"];
85511
        }
85611
        $args = array_unique($args);
85711
        $placeholders = implode(', ', array_fill(0, count($args), '%d'));
85811
        $where = ' AND ml.plid IN (' . $placeholders . ')';
85911
        $parents = $args;
86011
        $parents[] = $item['mlid'];
86111
      }
862
      else {
863
        // Get all links in this menu.
86441
        $where = '';
86541
        $args = array();
86641
        $parents = array();
867
      }
86852
      array_unshift($args, $menu_name);
869
      // Select the links from the table, and recursively build the tree. 
We
870
      // LEFT JOIN since there is no match in {menu_router} for an
external
871
      // link.
87252
      $data['tree'] = menu_tree_data(db_query("
873
        SELECT m.load_functions, m.to_arg_functions, m.access_callback,
m.access_arguments, m.page_callback, m.page_arguments, m.title,
m.title_callback, m.title_arguments, m.type, m.description, ml.*
874
        FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path =
ml.router_path
87552
        WHERE ml.menu_name = '%s'" . $where . "
87652
        ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8
ASC, p9 ASC", $args), $parents);
87752
      $data['node_links'] = array();
87852
      menu_tree_collect_node_links($data['tree'], $data['node_links']);
879
      // Cache the data, if it is not already in the cache.
88052
      $tree_cid = _menu_tree_cid($menu_name, $data);
88152
      if (!cache_get($tree_cid, 'cache_menu')) {
88245
        cache_set($tree_cid, $data, 'cache_menu');
88345
      }
884
      // Cache the cid of the (shared) data using the menu and
item-specific cid.
88552
      cache_set($cid, $tree_cid, 'cache_menu');
88652
    }
887
    // Check access for the current user to each item in the tree.
888141
    menu_tree_check_access($data['tree'], $data['node_links']);
889141
    $tree[$cid] = $data['tree'];
890141
  }
891
892141
  return $tree[$cid];
8930
}
894
895
/**
896
 * Get the data structure representing a named menu tree, based on the
current page.
897
 *
898
 * The tree order is maintained by storing each parent in an individual
899
 * field, see http://drupal.org/node/141866 for more.
900
 *
901
 * @param $menu_name
902
 *   The named menu links to return
903
 * @return
904
 *   An array of menu links, in the order they should be rendered. The
array
905
 *   is a list of associative arrays -- these have two keys, link and
below.
906
 *   link is a menu item, ready for theming as a link. Below represents
the
907
 *   submenu below the link if there is one, and it is a subtree that has
the
908
 *   same structure described for the top-level array.
909
 */
9102027
function menu_tree_page_data($menu_name = 'navigation') {
9111491
  static $tree = array();
912
913
  // Load the menu item corresponding to the current page.
9141491
  if ($item = menu_get_item()) {
915
    // Generate a cache ID (cid) specific for this page.
9161480
    $cid = 'links:' . $menu_name . ':page-cid:' . $item['href'] . ':' .
(int)$item['access'];
917
9181480
    if (!isset($tree[$cid])) {
919
      // If the static variable doesn't have the data, check {cache_menu}.
9201480
      $cache = cache_get($cid, 'cache_menu');
9211480
      if ($cache && isset($cache->data)) {
922
        // If the cache entry exists, it will just be the cid for the
actual data.
923
        // This avoids duplication of large amounts of data.
924835
        $cache = cache_get($cache->data, 'cache_menu');
925835
        if ($cache && isset($cache->data)) {
926835
          $data = $cache->data;
927835
        }
928835
      }
929
      // If the tree data was not in the cache, $data will be NULL.
9301480
      if (!isset($data)) {
931
        // Build and run the query, and build the tree.
932703
        if ($item['access']) {
933
          // Check whether a menu link exists that corresponds to the
current path.
934671
          $args = array($menu_name, $item['href']);
935671
          $placeholders = "'%s'";
936671
          if (drupal_is_front_page()) {
93789
            $args[] = '<front>';
93889
            $placeholders .= ", '%s'";
93989
          }
940671
          $parents = db_fetch_array(db_query("SELECT p1, p2, p3, p4, p5,
p6, p7, p8 FROM {menu_links} WHERE menu_name = '%s' AND link_path IN (" .
$placeholders . ")", $args));
941
942671
          if (empty($parents)) {
943
            // If no link exists, we may be on a local task that's not in
the links.
944
            // TODO: Handle the case like a local task on a specific node
in the menu.
945649
            $parents = db_fetch_array(db_query("SELECT p1, p2, p3, p4, p5,
p6, p7, p8 FROM {menu_links} WHERE menu_name = '%s' AND link_path = '%s'",
$menu_name, $item['tab_root']));
946649
          }
947
          // We always want all the top-level links with plid == 0.
948671
          $parents[] = '0';
949
950
          // Use array_values() so that the indices are numeric for
array_merge().
951671
          $args = $parents = array_unique(array_values($parents));
952671
          $placeholders = implode(', ', array_fill(0, count($args),
'%d'));
953671
          $expanded = variable_get('menu_expanded', array());
954
          // Check whether the current menu has any links set to be
expanded.
955671
          if (in_array($menu_name, $expanded)) {
956
            // Collect all the links set to be expanded, and then add all
of
957
            // their children to the list as well.
958
            do {
95966
              $result = db_query("SELECT mlid FROM {menu_links} WHERE
menu_name = '%s' AND expanded = 1 AND has_children = 1 AND plid IN (" .
$placeholders . ') AND mlid NOT IN (' . $placeholders . ')',
array_merge(array($menu_name), $args, $args));
96066
              $num_rows = FALSE;
96166
              while ($item = db_fetch_array($result)) {
96248
                $args[] = $item['mlid'];
96348
                $num_rows = TRUE;
96448
              }
96566
              $placeholders = implode(', ', array_fill(0, count($args),
'%d'));
9660
            } while ($num_rows);
96766
          }
968671
          array_unshift($args, $menu_name);
969671
        }
970
        else {
971
          // Show only the top-level menu items when access is denied.
97232
          $args = array($menu_name, '0');
97332
          $placeholders = '%d';
97432
          $parents = array();
975
        }
976
        // Select the links from the table, and recursively build the tree.
We
977
        // LEFT JOIN since there is no match in {menu_router} for an
external
978
        // link.
979703
        $data['tree'] = menu_tree_data(db_query("
980
          SELECT m.load_functions, m.to_arg_functions, m.access_callback,
m.access_arguments, m.page_callback, m.page_arguments, m.title,
m.title_callback, m.title_arguments, m.type, m.description, ml.*
981
          FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path =
ml.router_path
982703
          WHERE ml.menu_name = '%s' AND ml.plid IN (" . $placeholders . ")
983703
          ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC,
p8 ASC, p9 ASC", $args), $parents);
984703
        $data['node_links'] = array();
985703
        menu_tree_collect_node_links($data['tree'], $data['node_links']);
986
        // Cache the data, if it is not already in the cache.
987703
        $tree_cid = _menu_tree_cid($menu_name, $data);
988703
        if (!cache_get($tree_cid, 'cache_menu')) {
989506
          cache_set($tree_cid, $data, 'cache_menu');
990506
        }
991
        // Cache the cid of the (shared) data using the page-specific cid.
992703
        cache_set($cid, $tree_cid, 'cache_menu');
993703
      }
994
      // Check access for the current user to each item in the tree.
9951480
      menu_tree_check_access($data['tree'], $data['node_links']);
9961480
      $tree[$cid] = $data['tree'];
9971480
    }
9981480
    return $tree[$cid];
9990
  }
1000
100111
  return array();
10020
}
1003
1004
/**
1005
 * Helper function - compute the real cache ID for menu tree data.
1006
 */
10072027
function _menu_tree_cid($menu_name, $data) {
1008710
  return 'links:' . $menu_name . ':tree-data:' . md5(serialize($data));
10090
}
1010
1011
/**
1012
 * Recursive helper function - collect node links.
1013
 */
10142027
function menu_tree_collect_node_links(&$tree, &$node_links) {
1015722
  foreach ($tree as $key => $v) {
1016719
    if ($tree[$key]['link']['router_path'] == 'node/%') {
1017719
      $nid = substr($tree[$key]['link']['link_path'], 5);
1018719
      if (is_numeric($nid)) {
101995
        $node_links[$nid][$tree[$key]['link']['mlid']] =
&$tree[$key]['link'];
102095
        $tree[$key]['link']['access'] = FALSE;
102195
      }
1022719
    }
1023719
    if ($tree[$key]['below']) {
1024426
      menu_tree_collect_node_links($tree[$key]['below'], $node_links);
1025426
    }
1026719
  }
1027722
}
1028
1029
/**
1030
 * Check access and perform other dynamic operations for each link in the
tree.
1031
 */
10322027
function menu_tree_check_access(&$tree, $node_links = array()) {
1033
10341504
  if ($node_links) {
1035
    // Use db_rewrite_sql to evaluate view access without loading each full
node.
1036137
    $nids = array_keys($node_links);
1037137
    $placeholders = '%d' . str_repeat(', %d', count($nids) - 1);
1038137
    $result = db_query(db_rewrite_sql("SELECT n.nid FROM {node} n WHERE
n.status = 1 AND n.nid IN (" . $placeholders . ")"), $nids);
1039137
    while ($node = db_fetch_array($result)) {
1040137
      $nid = $node['nid'];
1041137
      foreach ($node_links[$nid] as $mlid => $link) {
1042137
        $node_links[$nid][$mlid]['access'] = TRUE;
1043137
      }
1044137
    }
1045137
  }
10461504
  _menu_tree_check_access($tree);
10471504
  return;
10480
}
1049
1050
/**
1051
 * Recursive helper function for menu_tree_check_access()
1052
 */
10532027
function _menu_tree_check_access(&$tree) {
10541504
  $new_tree = array();
10551504
  foreach ($tree as $key => $v) {
10561504
    $item = &$tree[$key]['link'];
10571504
    _menu_link_translate($item);
10581504
    if ($item['access']) {
10591504
      if ($tree[$key]['below']) {
1060502
        _menu_tree_check_access($tree[$key]['below']);
1061502
      }
1062
      // The weights are made a uniform 5 digits by adding 50000 as an
offset.
1063
      // After _menu_link_translate(), $item['title'] has the localized
link title.
1064
      // Adding the mlid to the end of the index insures that it is
unique.
10651504
      $new_tree[(50000 + $item['weight']) . ' ' . $item['title'] . ' ' .
$item['mlid']] = $tree[$key];
10661504
    }
10671504
  }
1068
  // Sort siblings in the tree based on the weights and localized titles.
10691504
  ksort($new_tree);
10701504
  $tree = $new_tree;
10711504
}
1072
1073
/**
1074
 * Build the data representing a menu tree.
1075
 *
1076
 * @param $result
1077
 *   The database result.
1078
 * @param $parents
1079
 *   An array of the plid values that represent the path from the current
page
1080
 *   to the root of the menu tree.
1081
 * @param $depth
1082
 *   The depth of the current menu tree.
1083
 * @return
1084
 *   See menu_tree_page_data for a description of the data structure.
1085
 */
10862027
function menu_tree_data($result = NULL, $parents = array(), $depth = 1) {
1087722
  list(, $tree) = _menu_tree_data($result, $parents, $depth);
1088722
  return $tree;
10890
}
1090
1091
/**
1092
 * Recursive helper function to build the data representing a menu tree.
1093
 *
1094
 * The function is a bit complex because the rendering of an item depends
on
1095
 * the next menu item. So we are always rendering the element previously
1096
 * processed not the current one.
1097
 */
10982027
function _menu_tree_data($result, $parents, $depth, $previous_element = '')
{
1099722
  $remnant = NULL;
1100722
  $tree = array();
1101722
  while ($item = db_fetch_array($result)) {
1102
    // We need to determine if we're on the path to root so we can later
build
1103
    // the correct active trail and breadcrumb.
1104719
    $item['in_active_trail'] = in_array($item['mlid'], $parents);
1105
    // The current item is the first in a new submenu.
1106719
    if ($item['depth'] > $depth) {
1107
      // _menu_tree returns an item and the menu tree structure.
1108426
      list($item, $below) = _menu_tree_data($result, $parents,
$item['depth'], $item);
1109426
      if ($previous_element) {
1110426
        $tree[$previous_element['mlid']] = array(
1111426
          'link' => $previous_element,
1112426
          'below' => $below,
1113
        );
1114426
      }
1115
      else {
11160
        $tree = $below;
1117
      }
1118
      // We need to fall back one level.
1119426
      if (!isset($item) || $item['depth'] < $depth) {
1120146
        return array($item, $tree);
11210
      }
1122
      // This will be the link to be output in the next iteration.
1123385
      $previous_element = $item;
1124385
    }
1125
    // We are at the same depth, so we use the previous element.
1126719
    elseif ($item['depth'] == $depth) {
1127719
      if ($previous_element) {
1128
        // Only the first time.
1129690
        $tree[$previous_element['mlid']] = array(
1130690
          'link' => $previous_element,
1131690
          'below' => FALSE,
1132
        );
1133690
      }
1134
      // This will be the link to be output in the next iteration.
1135719
      $previous_element = $item;
1136719
    }
1137
    // The submenu ended with the previous item, so pass back the current
item.
1138
    else {
1139385
      $remnant = $item;
1140385
      break;
1141
    }
1142719
  }
1143722
  if ($previous_element) {
1144
    // We have one more link dangling.
1145719
    $tree[$previous_element['mlid']] = array(
1146719
      'link' => $previous_element,
1147719
      'below' => FALSE,
1148
    );
1149719
  }
1150722
  return array($remnant, $tree);
11510
}
1152
1153
/**
1154
 * Generate the HTML output for a single menu link.
1155
 *
1156
 * @ingroup themeable
1157
 */
11582027
function theme_menu_item_link($link) {
11591293
  if (empty($link['localized_options'])) {
11601291
    $link['localized_options'] = array();
11611291
  }
1162
11631293
  return l($link['title'], $link['href'], $link['localized_options']);
11640
}
1165
1166
/**
1167
 * Generate the HTML output for a menu tree
1168
 *
1169
 * @ingroup themeable
1170
 */
11712027
function theme_menu_tree($tree) {
11721070
  return '<ul class="menu">' . $tree . '</ul>';
11730
}
1174
1175
/**
1176
 * Generate the HTML output for a menu item and submenu.
1177
 *
1178
 * @ingroup themeable
1179
 */
11802027
function theme_menu_item($link, $has_children, $menu = '', $in_active_trail
= FALSE, $extra_class = NULL) {
11811070
  $class = ($menu ? 'expanded' : ($has_children ? 'collapsed' : 'leaf'));
11821070
  if (!empty($extra_class)) {
11831070
    $class .= ' ' . $extra_class;
11841070
  }
11851070
  if ($in_active_trail) {
1186360
    $class .= ' active-trail';
1187360
  }
11881070
  return '<li class="' . $class . '">' . $link . $menu . "</li>\n";
11890
}
1190
1191
/**
1192
 * Generate the HTML output for a single local task link.
1193
 *
1194
 * @ingroup themeable
1195
 */
11962027
function theme_menu_local_task($link, $active = FALSE) {
1197930
  return '<li ' . ($active ? 'class="active" ' : '') . '>' . $link .
"</li>\n";
11980
}
1199
1200
/**
1201
 * Generates elements for the $arg array in the help hook.
1202
 */
12032027
function drupal_help_arg($arg = array()) {
1204
  // Note - the number of empty elements should be > MENU_MAX_PARTS.
12051491
  return $arg + array('', '', '', '', '', '', '', '', '', '', '', '');
12060
}
1207
1208
/**
1209
 * Returns the help associated with the active menu item.
1210
 */
12112027
function menu_get_active_help() {
12121489
  $output = '';
12131489
  $router_path = menu_tab_root_path();
1214
12151489
  $arg = drupal_help_arg(arg(NULL));
12161489
  $empty_arg = drupal_help_arg();
1217
12181489
  foreach (module_list() as $name) {
12191489
    if (module_hook($name, 'help')) {
1220
      // Lookup help for this path.
12211489
      if ($help = module_invoke($name, 'help', $router_path, $arg)) {
1222294
        $output .= $help . "\n";
1223294
      }
1224
      // Add "more help" link on admin pages if the module provides a
1225
      // standalone help page.
12261489
      if ($arg[0] == "admin" && module_exists('help') &&
module_invoke($name, 'help', 'admin/help#' . $arg[2], $empty_arg) && $help)
{
1227175
        $output .= theme("more_help_link", url('admin/help/' . $arg[2]));
1228175
      }
12291489
    }
12301489
  }
12311489
  return $output;
12320
}
1233
1234
/**
1235
 * Build a list of named menus.
1236
 */
12372027
function menu_get_names($reset = FALSE) {
12380
  static $names;
1239
12400
  if ($reset || empty($names)) {
12410
    $names = array();
12420
    $result = db_query("SELECT DISTINCT(menu_name) FROM {menu_links} ORDER
BY menu_name");
12430
    while ($name = db_fetch_array($result)) {
12440
      $names[] = $name['menu_name'];
12450
    }
12460
  }
12470
  return $names;
12480
}
1249
1250
/**
1251
 * Return an array containing the names of system-defined (default) menus.
1252
 */
12532027
function menu_list_system_menus() {
1254212
  return array('navigation', 'main-menu', 'secondary-menu');
12550
}
1256
1257
/**
1258
 * Return an array of links to be rendered as the Main menu.
1259
 */
12602027
function menu_main_menu() {
12611489
  return menu_navigation_links(variable_get('menu_main_menu_source',
'main-menu'));
12620
}
1263
1264
/**
1265
 * Return an array of links to be rendered as the Secondary links.
1266
 */
12672027
function menu_secondary_menu() {
1268
1269
  // If the secondary menu source is set as the primary menu, we display
the
1270
  // second level of the primary menu.
12711489
  if (variable_get('menu_secondary_menu_source', 'secondary-menu') ==
variable_get('menu_main_menu_source', 'main-menu')) {
12720
    return menu_navigation_links(variable_get('menu_main_menu_source',
'main-menu'), 1);
12730
  }
1274
  else {
12751489
    return menu_navigation_links(variable_get('menu_secondary_menu_source',
'secondary-menu'), 0);
1276
  }
12770
}
1278
1279
/**
1280
 * Return an array of links for a navigation menu.
1281
 *
1282
 * @param $menu_name
1283
 *   The name of the menu.
1284
 * @param $level
1285
 *   Optional, the depth of the menu to be returned.
1286
 * @return
1287
 *   An array of links of the specified menu and level.
1288
 */
12892027
function menu_navigation_links($menu_name, $level = 0) {
1290
  // Don't even bother querying the menu table if no menu is specified.
12911489
  if (empty($menu_name)) {
12920
    return array();
12930
  }
1294
1295
  // Get the menu hierarchy for the current page.
12961489
  $tree = menu_tree_page_data($menu_name);
1297
1298
  // Go down the active trail until the right level is reached.
12991489
  while ($level-- > 0 && $tree) {
1300
    // Loop through the current level's items until we find one that is in
trail.
13010
    while ($item = array_shift($tree)) {
13020
      if ($item['link']['in_active_trail']) {
1303
        // If the item is in the active trail, we continue in the subtree.
13040
        $tree = empty($item['below']) ? array() : $item['below'];
13050
        break;
13060
      }
13070
    }
13080
  }
1309
1310
  // Create a single level of links.
13111489
  $links = array();
13121489
  foreach ($tree as $item) {
13130
    if (!$item['link']['hidden']) {
13140
      $l = $item['link']['localized_options'];
13150
      $l['href'] = $item['link']['href'];
13160
      $l['title'] = $item['link']['title'];
13170
      if ($item['link']['in_active_trail']) {
13180
        if (empty($l['attributes']['class'])) {
13190
          $l['attributes']['class'] = 'active-trail';
13200
        }
1321
        else {
13220
          $l['attributes']['class'] .= ' active-trail';
1323
        }
13240
      }
1325
      // Keyed with unique menu id to generate classes from theme_links().
13260
      $links['menu-' . $item['link']['mlid']] = $l;
13270
    }
13280
  }
13291489
  return $links;
13300
}
1331
1332
/**
1333
 * Collects the local tasks (tabs) for a given level.
1334
 *
1335
 * @param $level
1336
 *   The level of tasks you ask for. Primary tasks are 0, secondary are 1.
1337
 * @param $return_root
1338
 *   Whether to return the root path for the current page.
1339
 * @return
1340
 *   Themed output corresponding to the tabs of the requested level, or
1341
 *   router path if $return_root == TRUE. This router path corresponds to
1342
 *   a parent tab, if the current page is a default local task.
1343
 */
13442027
function menu_local_tasks($level = 0, $return_root = FALSE) {
13451489
  static $tabs;
13461489
  static $root_path;
1347
13481489
  if (!isset($tabs)) {
13491489
    $tabs = array();
1350
13511489
    $router_item = menu_get_item();
13521489
    if (!$router_item || !$router_item['access']) {
135352
      return '';
13540
    }
1355
    // Get all tabs and the root page.
13561437
    $result = db_query("SELECT * FROM {menu_router} WHERE tab_root = '%s'
ORDER BY weight, title", $router_item['tab_root']);
13571437
    $map = arg();
13581437
    $children = array();
13591437
    $tasks = array();
13601437
    $root_path = $router_item['path'];
1361
13621437
    while ($item = db_fetch_array($result)) {
13631437
      _menu_translate($item, $map, TRUE);
13641437
      if ($item['tab_parent']) {
1365
        // All tabs, but not the root page.
1366930
        $children[$item['tab_parent']][$item['path']] = $item;
1367930
      }
1368
      // Store the translated item for later use.
13691437
      $tasks[$item['path']] = $item;
13701437
    }
1371
1372
    // Find all tabs below the current path.
13731437
    $path = $router_item['path'];
1374
    // Tab parenting may skip levels, so the number of parts in the path
may not
1375
    // equal the depth. Thus we use the $depth counter (offset by 1000 for
ksort).
13761437
    $depth = 1001;
13771437
    while (isset($children[$path])) {
1378709
      $tabs_current = '';
1379709
      $next_path = '';
1380709
      $count = 0;
1381709
      foreach ($children[$path] as $item) {
1382709
        if ($item['access']) {
1383709
          $count++;
1384
          // The default task is always active.
1385709
          if ($item['type'] == MENU_DEFAULT_LOCAL_TASK) {
1386
            // Find the first parent which is not a default local task.
1387707
            for ($p = $item['tab_parent']; $tasks[$p]['type'] ==
MENU_DEFAULT_LOCAL_TASK; $p = $tasks[$p]['tab_parent']);
1388707
            $link = theme('menu_item_link', array('href' =>
$tasks[$p]['href']) + $item);
1389707
            $tabs_current .= theme('menu_local_task', $link, TRUE);
1390707
            $next_path = $item['path'];
1391707
          }
1392
          else {
1393588
            $link = theme('menu_item_link', $item);
1394588
            $tabs_current .= theme('menu_local_task', $link);
1395
          }
1396709
        }
1397709
      }
1398709
      $path = $next_path;
1399709
      $tabs[$depth]['count'] = $count;
1400709
      $tabs[$depth]['output'] = $tabs_current;
1401709
      $depth++;
1402709
    }
1403
1404
    // Find all tabs at the same level or above the current one.
14051437
    $parent = $router_item['tab_parent'];
14061437
    $path = $router_item['path'];
14071437
    $current = $router_item;
14081437
    $depth = 1000;
14091437
    while (isset($children[$parent])) {
1410233
      $tabs_current = '';
1411233
      $next_path = '';
1412233
      $next_parent = '';
1413233
      $count = 0;
1414233
      foreach ($children[$parent] as $item) {
1415233
        if ($item['access']) {
1416233
          $count++;
1417233
          if ($item['type'] == MENU_DEFAULT_LOCAL_TASK) {
1418
            // Find the first parent which is not a default local task.
1419189
            for ($p = $item['tab_parent']; $tasks[$p]['type'] ==
MENU_DEFAULT_LOCAL_TASK; $p = $tasks[$p]['tab_parent']);
1420189
            $link = theme('menu_item_link', array('href' =>
$tasks[$p]['href']) + $item);
1421189
            if ($item['path'] == $router_item['path']) {
14220
              $root_path = $tasks[$p]['path'];
14230
            }
1424189
          }
1425
          else {
1426233
            $link = theme('menu_item_link', $item);
1427
          }
1428
          // We check for the active tab.
1429233
          if ($item['path'] == $path) {
1430233
            $tabs_current .= theme('menu_local_task', $link, TRUE);
1431233
            $next_path = $item['tab_parent'];
1432233
            if (isset($tasks[$next_path])) {
1433233
              $next_parent = $tasks[$next_path]['tab_parent'];
1434233
            }
1435233
          }
1436
          else {
1437231
            $tabs_current .= theme('menu_local_task', $link);
1438
          }
1439233
        }
1440233
      }
1441233
      $path = $next_path;
1442233
      $parent = $next_parent;
1443233
      $tabs[$depth]['count'] = $count;
1444233
      $tabs[$depth]['output'] = $tabs_current;
1445233
      $depth--;
1446233
    }
1447
    // Sort by depth.
14481437
    ksort($tabs);
1449
    // Remove the depth, we are interested only in their relative
placement.
14501437
    $tabs = array_values($tabs);
14511437
  }
1452
14531489
  if ($return_root) {
14541437
    return $root_path;
14550
  }
1456
  else {
1457
    // We do not display single tabs.
14581489
    return (isset($tabs[$level]) && $tabs[$level]['count'] > 1) ?
$tabs[$level]['output'] : '';
1459
  }
14600
}
1461
1462
/**
1463
 * Returns the rendered local tasks at the top level.
1464
 */
14652027
function menu_primary_local_tasks() {
14661489
  return menu_local_tasks(0);
14670
}
1468
1469
/**
1470
 * Returns the rendered local tasks at the second level.
1471
 */
14722027
function menu_secondary_local_tasks() {
14731489
  return menu_local_tasks(1);
14740
}
1475
1476
/**
1477
 * Returns the router path, or the path of the parent tab of a default
local task.
1478
 */
14792027
function menu_tab_root_path() {
14801489
  return menu_local_tasks(0, TRUE);
14810
}
1482
1483
/**
1484
 * Returns the rendered local tasks. The default implementation renders
them as tabs.
1485
 *
1486
 * @ingroup themeable
1487
 */
14882027
function theme_menu_local_tasks() {
14890
  $output = '';
1490
14910
  if ($primary = menu_primary_local_tasks()) {
14920
    $output .= "<ul class=\"tabs primary\">\n" . $primary . "</ul>\n";
14930
  }
14940
  if ($secondary = menu_secondary_local_tasks()) {
14950
    $output .= "<ul class=\"tabs secondary\">\n" . $secondary . "</ul>\n";
14960
  }
1497
14980
  return $output;
14990
}
1500
1501
/**
1502
 * Set (or get) the active menu for the current page - determines the
active trail.
1503
 */
15042027
function menu_set_active_menu_name($menu_name = NULL) {
15051148
  static $active;
1506
15071148
  if (isset($menu_name)) {
150812
    $active = $menu_name;
150912
  }
15101136
  elseif (!isset($active)) {
15111136
    $active = 'navigation';
15121136
  }
15131148
  return $active;
15140
}
1515
1516
/**
1517
 * Get the active menu for the current page - determines the active trail.
1518
 */
15192027
function menu_get_active_menu_name() {
15201136
  return menu_set_active_menu_name();
15210
}
1522
1523
/**
1524
 * Set the active path, which determines which page is loaded.
1525
 *
1526
 * @param $path
1527
 *   A Drupal path - not a path alias.
1528
 *
1529
 * Note that this may not have the desired effect unless invoked very
early
1530
 * in the page load, such as during hook_boot, or unless you call
1531
 * menu_execute_active_handler() to generate your page output.
1532
 */
15332027
function menu_set_active_item($path) {
15341
  $_GET['q'] = $path;
15351
}
1536
1537
/**
1538
 * Set (or get) the active trail for the current page - the path to root in
the menu tree.
1539
 */
15402027
function menu_set_active_trail($new_trail = NULL) {
15411148
  static $trail;
1542
15431148
  if (isset($new_trail)) {
154412
    $trail = $new_trail;
154512
  }
15461148
  elseif (!isset($trail)) {
15471136
    $trail = array();
15481136
    $trail[] = array('title' => t('Home'), 'href' => '<front>',
'localized_options' => array(), 'type' => 0);
15491136
    $item = menu_get_item();
1550
1551
    // Check whether the current item is a local task (displayed as a
tab).
15521136
    if ($item['tab_parent']) {
1553
      // The title of a local task is used for the tab, never the page
title.
1554
      // Thus, replace it with the item corresponding to the root path to
get
1555
      // the relevant href and title.  For example, the menu item
corresponding
1556
      // to 'admin' is used when on the 'By module' tab at
'admin/by-module'.
1557233
      $parts = explode('/', $item['tab_root']);
1558233
      $args = arg();
1559
      // Replace wildcards in the root path using the current path.
1560233
      foreach ($parts as $index => $part) {
1561233
        if ($part == '%') {
1562109
          $parts[$index] = $args[$index];
1563109
        }
1564233
      }
1565
      // Retrieve the menu item using the root path after wildcard
replacement.
1566233
      $root_item = menu_get_item(implode('/', $parts));
1567233
      if ($root_item && $root_item['access']) {
1568232
        $item = $root_item;
1569232
      }
1570233
    }
1571
15721136
    $tree = menu_tree_page_data(menu_get_active_menu_name());
15731136
    list($key, $curr) = each($tree);
1574
15751136
    while ($curr) {
1576
      // Terminate the loop when we find the current path in the active
trail.
15771136
      if ($curr['link']['href'] == $item['href']) {
1578569
        $trail[] = $curr['link'];
1579569
        $curr = FALSE;
1580569
      }
1581
      else {
1582
        // Add the link if it's in the active trail, then move to the link
below.
15831136
        if ($curr['link']['in_active_trail']) {
1584160
          $trail[] = $curr['link'];
1585160
          $tree = $curr['below'] ? $curr['below'] : array();
1586160
        }
15871136
        list($key, $curr) = each($tree);
1588
      }
15891136
    }
1590
    // Make sure the current page is in the trail (needed for the page
title),
1591
    // but exclude tabs and the front page.
15921136
    $last = count($trail) - 1;
15931136
    if ($trail[$last]['href'] != $item['href'] && !(bool)($item['type'] &
MENU_IS_LOCAL_TASK) && !drupal_is_front_page()) {
1594566
      $trail[] = $item;
1595566
    }
15961136
  }
15971148
  return $trail;
15980
}
1599
1600
/**
1601
 * Get the active trail for the current page - the path to root in the menu
tree.
1602
 */
16032027
function menu_get_active_trail() {
16041148
  return menu_set_active_trail();
16050
}
1606
1607
/**
1608
 * Get the breadcrumb for the current page, as determined by the active
trail.
1609
 */
16102027
function menu_get_active_breadcrumb() {
16111386
  $breadcrumb = array();
1612
1613
  // No breadcrumb for the front page.
16141386
  if (drupal_is_front_page()) {
1615204
    return $breadcrumb;
16160
  }
1617
16181182
  $item = menu_get_item();
16191182
  if ($item && $item['access']) {
16201130
    $active_trail = menu_get_active_trail();
1621
16221130
    foreach ($active_trail as $parent) {
16231130
      $breadcrumb[] = l($parent['title'], $parent['href'],
$parent['localized_options']);
16241130
    }
16251130
    $end = end($active_trail);
1626
1627
    // Don't show a link to the current page in the breadcrumb trail.
16281130
    if ($item['href'] == $end['href'] || ($item['type'] ==
MENU_DEFAULT_LOCAL_TASK && $end['href'] != '<front>')) {
1629897
      array_pop($breadcrumb);
1630897
    }
16311130
  }
16321182
  return $breadcrumb;
16330
}
1634
1635
/**
1636
 * Get the title of the current page, as determined by the active trail.
1637
 */
16382027
function menu_get_active_title() {
1639645
  $active_trail = menu_get_active_trail();
1640
1641645
  foreach (array_reverse($active_trail) as $item) {
1642645
    if (!(bool)($item['type'] & MENU_IS_LOCAL_TASK)) {
1643645
      return $item['title'];
16440
    }
16450
  }
16460
}
1647
1648
/**
1649
 * Get a menu link by its mlid, access checked and link translated for
rendering.
1650
 *
1651
 * This function should never be called from within node_load() or any
other
1652
 * function used as a menu object load function since an infinite recursion
may
1653
 * occur.
1654
 *
1655
 * @param $mlid
1656
 *   The mlid of the menu item.
1657
 * @return
1658
 *   A menu link, with $item['access'] filled and link translated for
1659
 *   rendering.
1660
 */
16612027
function menu_link_load($mlid) {
166238
  if (is_numeric($mlid) && $item = db_fetch_array(db_query("SELECT m.*,
ml.* FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path =
ml.router_path WHERE ml.mlid = %d", $mlid))) {
166338
    _menu_link_translate($item);
166438
    return $item;
16650
  }
16660
  return FALSE;
16670
}
1668
1669
/**
1670
 * Clears the cached cached data for a single named menu.
1671
 */
16722027
function menu_cache_clear($menu_name = 'navigation') {
1673113
  static $cache_cleared = array();
1674
1675113
  if (empty($cache_cleared[$menu_name])) {
1676113
    cache_clear_all('links:' . $menu_name . ':', 'cache_menu', TRUE);
1677113
    $cache_cleared[$menu_name] = 1;
1678113
  }
167983
  elseif ($cache_cleared[$menu_name] == 1) {
168083
    register_shutdown_function('cache_clear_all', 'links:' . $menu_name .
':', 'cache_menu', TRUE);
168183
    $cache_cleared[$menu_name] = 2;
168283
  }
1683113
}
1684
1685
/**
1686
 * Clears all cached menu data.  This should be called any time broad
changes
1687
 * might have been made to the router items or menu links.
1688
 */
16892027
function menu_cache_clear_all() {
169082
  cache_clear_all('*', 'cache_menu', TRUE);
169182
}
1692
1693
/**
1694
 * (Re)populate the database tables used by various menu functions.
1695
 *
1696
 * This function will clear and populate the {menu_router} table, add
entries
1697
 * to {menu_links} for new router items, then remove stale items from
1698
 * {menu_links}. If called from update.php or install.php, it will also
1699
 * schedule a call to itself on the first real page load from
1700
 * menu_execute_active_handler(), because the maintenance page environment
1701
 * is different and leaves stale data in the menu tables.
1702
 */
17032027
function menu_rebuild() {
170481
  variable_del('menu_rebuild_needed');
170581
  menu_cache_clear_all();
170681
  $menu = menu_router_build(TRUE);
170781
  _menu_navigation_links_rebuild($menu);
1708
  // Clear the page and block caches.
170981
  _menu_clear_page_cache();
171081
  if (defined('MAINTENANCE_MODE')) {
17110
    variable_set('menu_rebuild_needed', TRUE);
17120
  }
171381
}
1714
1715
/**
1716
 * Collect, alter and store the menu definitions.
1717
 */
17182027
function menu_router_build($reset = FALSE) {
1719110
  static $menu;
1720
1721110
  if (!isset($menu) || $reset) {
1722110
    if (!$reset && ($cache = cache_get('router:', 'cache_menu')) &&
isset($cache->data)) {
172328
      $menu = $cache->data;
172428
    }
1725
    else {
1726
      // We need to manually call each module so that we can know which
module
1727
      // a given item came from.
172882
      $callbacks = array();
172982
      foreach (module_implements('menu', NULL, TRUE) as $module) {
173082
        $router_items = call_user_func($module . '_menu');
173182
        if (isset($router_items) && is_array($router_items)) {
173282
          foreach (array_keys($router_items) as $path) {
173382
            $router_items[$path]['module'] = $module;
173482
          }
173582
          $callbacks = array_merge($callbacks, $router_items);
173682
        }
173782
      }
1738
      // Alter the menu as defined in modules, keys are like user/%user.
173982
      drupal_alter('menu', $callbacks);
174082
      $menu = _menu_router_build($callbacks);
1741
    }
1742110
  }
1743110
  return $menu;
17440
}
1745
1746
/**
1747
 * Builds a link from a router item.
1748
 */
17492027
function _menu_link_build($item) {
175082
  if ($item['type'] == MENU_CALLBACK) {
175181
    $item['hidden'] = -1;
175281
  }
175382
  elseif ($item['type'] == MENU_SUGGESTED_ITEM) {
175481
    $item['hidden'] = 1;
175581
  }
1756
  // Note, we set this as 'system', so that we can be sure to distinguish
all
1757
  // the menu links generated automatically from entries in {menu_router}.
175882
  $item['module'] = 'system';
1759
  $item += array(
176082
    'menu_name' => 'navigation',
176182
    'link_title' => $item['title'],
176282
    'link_path' => $item['path'],
176382
    'hidden' => 0,
176482
    'options' => empty($item['description']) ? array() : array('attributes'
=> array('title' => $item['description'])),
17650
  );
176682
  return $item;
17670
}
1768
1769
/**
1770
 * Helper function to build menu links for the items in the menu router.
1771
 */
17722027
function _menu_navigation_links_rebuild($menu) {
1773
  // Add normal and suggested items as links.
177481
  $menu_links = array();
177581
  foreach ($menu as $path => $item) {
177681
    if ($item['_visible']) {
177781
      $item = _menu_link_build($item);
177881
      $menu_links[$path] = $item;
177981
      $sort[$path] = $item['_number_parts'];
178081
    }
178181
  }
178281
  if ($menu_links) {
1783
    // Make sure no child comes before its parent.
178481
    array_multisort($sort, SORT_NUMERIC, $menu_links);
1785
178681
    foreach ($menu_links as $item) {
178781
      $existing_item = db_fetch_array(db_query("SELECT mlid, menu_name,
plid, customized, has_children, updated FROM {menu_links} WHERE link_path =
'%s' AND module = '%s'", $item['link_path'], 'system'));
178881
      if ($existing_item) {
178981
        $item['mlid'] = $existing_item['mlid'];
179081
        $item['menu_name'] = $existing_item['menu_name'];
179181
        $item['plid'] = $existing_item['plid'];
179281
        $item['has_children'] = $existing_item['has_children'];
179381
        $item['updated'] = $existing_item['updated'];
179481
      }
179581
      if (!$existing_item || !$existing_item['customized']) {
179681
        menu_link_save($item);
179781
      }
179881
    }
179981
  }
180081
  $placeholders = db_placeholders($menu, 'varchar');
180181
  $paths = array_keys($menu);
1802
  // Updated and customized items whose router paths are gone need new
ones.
180381
  $result = db_query("SELECT ml.link_path, ml.mlid, ml.router_path,
ml.updated FROM {menu_links} ml WHERE ml.updated = 1 OR (router_path NOT IN
($placeholders) AND external = 0 AND customized = 1)", $paths);
180481
  while ($item = db_fetch_array($result)) {
18050
    $router_path = _menu_find_router_path($menu, $item['link_path']);
18060
    if (!empty($router_path) && ($router_path != $item['router_path'] ||
$item['updated'])) {
1807
      // If the router path and the link path matches, it's surely a
working
1808
      // item, so we clear the updated flag.
18090
      $updated = $item['updated'] && $router_path != $item['link_path'];
18100
      db_query("UPDATE {menu_links} SET router_path = '%s', updated = %d
WHERE mlid = %d", $router_path, $updated, $item['mlid']);
18110
    }
18120
  }
1813
  // Find any item whose router path does not exist any more.
181481
  $result = db_query("SELECT * FROM {menu_links} WHERE router_path NOT IN
($placeholders) AND external = 0 AND updated = 0 AND customized = 0 ORDER
BY depth DESC", $paths);
1815
  // Remove all such items. Starting from those with the greatest depth
will
1816
  // minimize the amount of re-parenting done by menu_link_delete().
181781
  while ($item = db_fetch_array($result)) {
18181
    _menu_delete_item($item, TRUE);
18191
  }
182081
}
1821
1822
/**
1823
 * Delete one or several menu links.
1824
 *
1825
 * @param $mlid
1826
 *   A valid menu link mlid or NULL. If NULL, $path is used.
1827
 * @param $path
1828
 *   The path to the menu items to be deleted. $mlid must be NULL.
1829
 */
18302027
function menu_link_delete($mlid, $path = NULL) {
18315
  if (isset($mlid)) {
18325
    _menu_delete_item(db_fetch_array(db_query("SELECT * FROM {menu_links}
WHERE mlid = %d", $mlid)));
18335
  }
1834
  else {
18350
    $result = db_query("SELECT * FROM {menu_links} WHERE link_path = '%s'",
$path);
18360
    while ($link = db_fetch_array($result)) {
18370
      _menu_delete_item($link);
18380
    }
1839
  }
18405
}
1841
1842
/**
1843
 * Helper function for menu_link_delete; deletes a single menu link.
1844
 *
1845
 * @param $item
1846
 *   Item to be deleted.
1847
 * @param $force
1848
 *   Forces deletion. Internal use only, setting to TRUE is discouraged.
1849
 */
18502027
function _menu_delete_item($item, $force = FALSE) {
18516
  if ($item && ($item['module'] != 'system' || $item['updated'] || $force))
{
1852
    // Children get re-attached to the item's parent.
18536
    if ($item['has_children']) {
18543
      $result = db_query("SELECT mlid FROM {menu_links} WHERE plid = %d",
$item['mlid']);
18553
      while ($m = db_fetch_array($result)) {
18562
        $child = menu_link_load($m['mlid']);
18572
        $child['plid'] = $item['plid'];
18582
        menu_link_save($child);
18592
      }
18603
    }
18616
    db_query('DELETE FROM {menu_links} WHERE mlid = %d', $item['mlid']);
1862
1863
    // Update the has_children status of the parent.
18646
    _menu_update_parental_status($item);
18656
    menu_cache_clear($item['menu_name']);
18666
    _menu_clear_page_cache();
18676
  }
18686
}
1869
1870
/**
1871
 * Save a menu link.
1872
 *
1873
 * @param $item
1874
 *   An array representing a menu link item. The only mandatory keys are
1875
 *   link_path and link_title. Possible keys are:
1876
 *   - menu_name   default is navigation
1877
 *   - weight      default is 0
1878
 *   - expanded    whether the item is expanded.
1879
 *   - options     An array of options, @see l for more.
1880
 *   - mlid        Set to an existing value, or 0 or NULL to insert a new
link.
1881
 *   - plid        The mlid of the parent.
1882
 *   - router_path The path of the relevant router item.
1883
 */
18842027
function menu_link_save(&$item) {
1885110
  $menu = menu_router_build();
1886
1887110
  drupal_alter('menu_link', $item, $menu);
1888
1889
  // This is the easiest way to handle the unique internal path '<front>',
1890
  // since a path marked as external does not need to match a router path.
1891110
  $item['_external'] = menu_path_is_external($item['link_path'])  ||
$item['link_path'] == '<front>';
1892
  // Load defaults.
1893
  $item += array(
1894110
    'menu_name' => 'navigation',
1895110
    'weight' => 0,
1896110
    'link_title' => '',
1897110
    'hidden' => 0,
1898110
    'has_children' => 0,
1899110
    'expanded' => 0,
1900110
    'options' => array(),
1901110
    'module' => 'menu',
1902110
    'customized' => 0,
1903110
    'updated' => 0,
19040
  );
1905110
  $existing_item = FALSE;
1906110
  if (isset($item['mlid'])) {
1907102
    $existing_item = db_fetch_array(db_query("SELECT * FROM {menu_links}
WHERE mlid = %d", $item['mlid']));
1908102
  }
1909
1910110
  if (isset($item['plid'])) {
1911108
    $parent = db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE
mlid = %d", $item['plid']));
1912108
  }
1913
  else {
1914
    // Find the parent - it must be unique.
191566
    $parent_path = $item['link_path'];
191666
    $where = "WHERE link_path = '%s'";
1917
    // Only links derived from router items should have module == 'system',
and
1918
    // we want to find the parent even if it's in a different menu.
191966
    if ($item['module'] == 'system') {
192065
      $where .= " AND module = '%s'";
192165
      $arg2 = 'system';
192265
    }
1923
    else {
1924
      // If not derived from a router item, we respect the specified menu
name.
19251
      $where .= " AND menu_name = '%s'";
19261
      $arg2 = $item['menu_name'];
1927
    }
1928
    do {
192966
      $parent = FALSE;
193066
      $parent_path = substr($parent_path, 0, strrpos($parent_path, '/'));
193166
      $result = db_query("SELECT COUNT(*) FROM {menu_links} " . $where,
$parent_path, $arg2);
1932
      // Only valid if we get a unique result.
193366
      if (db_result($result) == 1) {
193465
        $parent = db_fetch_array(db_query("SELECT * FROM {menu_links} " .
$where, $parent_path, $arg2));
193565
      }
193666
    } while ($parent === FALSE && $parent_path);
1937
  }
1938110
  if ($parent !== FALSE) {
193996
    $item['menu_name'] = $parent['menu_name'];
194096
  }
1941110
  $menu_name = $item['menu_name'];
1942
  // Menu callbacks need to be in the links table for breadcrumbs, but
can't
1943
  // be parents if they are generated directly from a router item.
1944110
  if (empty($parent['mlid']) || $parent['hidden'] < 0) {
194595
    $item['plid'] =  0;
194695
  }
1947
  else {
194896
    $item['plid'] = $parent['mlid'];
1949
  }
1950
1951110
  if (!$existing_item) {
195276
    db_query("INSERT INTO {menu_links} (
1953
       menu_name, plid, link_path,
1954
      hidden, external, has_children,
1955
      expanded, weight,
1956
      module, link_title, options,
1957
      customized, updated) VALUES (
1958
      '%s', %d, '%s',
1959
      %d, %d, %d,
1960
      %d, %d,
196176
      '%s', '%s', '%s', %d, %d)",
196276
      $item['menu_name'], $item['plid'], $item['link_path'],
196376
      $item['hidden'], $item['_external'], $item['has_children'],
196476
      $item['expanded'], $item['weight'],
196576
      $item['module'],  $item['link_title'], serialize($item['options']),
196676
      $item['customized'], $item['updated']);
196776
    $item['mlid'] = db_last_insert_id('menu_links', 'mlid');
196876
  }
1969
1970110
  if (!$item['plid']) {
197195
    $item['p1'] = $item['mlid'];
197295
    for ($i = 2; $i <= MENU_MAX_DEPTH; $i++) {
197395
      $item["p$i"] = 0;
197495
    }
197595
    $item['depth'] = 1;
197695
  }
1977
  else {
1978
    // Cannot add beyond the maximum depth.
197996
    if ($item['has_children'] && $existing_item) {
198081
      $limit = MENU_MAX_DEPTH -
menu_link_children_relative_depth($existing_item) - 1;
198181
    }
1982
    else {
198396
      $limit = MENU_MAX_DEPTH - 1;
1984
    }
198596
    if ($parent['depth'] > $limit) {
19860
      return FALSE;
19870
    }
198896
    $item['depth'] = $parent['depth'] + 1;
198996
    _menu_link_parents_set($item, $parent);
1990
  }
1991
  // Need to check both plid and menu_name, since plid can be 0 in any
menu.
1992110
  if ($existing_item && ($item['plid'] != $existing_item['plid'] ||
$menu_name != $existing_item['menu_name'])) {
19932
    _menu_link_move_children($item, $existing_item);
19942
  }
1995
  // Find the callback. During the menu update we store empty paths to be
1996
  // fixed later, so we skip this.
1997110
  if (!isset($_SESSION['system_update_6021']) &&
(empty($item['router_path'])  || !$existing_item ||
($existing_item['link_path'] != $item['link_path']))) {
1998107
    if ($item['_external']) {
19990
      $item['router_path'] = '';
20000
    }
2001
    else {
2002
      // Find the router path which will serve this path.
2003107
      $item['parts'] = explode('/', $item['link_path'], MENU_MAX_PARTS);
2004107
      $item['router_path'] = _menu_find_router_path($menu,
$item['link_path']);
2005
    }
2006107
  }
2007110
  db_query("UPDATE {menu_links} SET menu_name = '%s', plid = %d, link_path
= '%s',
2008
    router_path = '%s', hidden = %d, external = %d, has_children = %d,
2009
    expanded = %d, weight = %d, depth = %d,
2010
    p1 = %d, p2 = %d, p3 = %d, p4 = %d, p5 = %d, p6 = %d, p7 = %d, p8 = %d,
p9 = %d,
2011110
    module = '%s', link_title = '%s', options = '%s', customized = %d WHERE
mlid = %d",
2012110
    $item['menu_name'], $item['plid'], $item['link_path'],
2013110
    $item['router_path'], $item['hidden'], $item['_external'],
$item['has_children'],
2014110
    $item['expanded'], $item['weight'],  $item['depth'],
2015110
    $item['p1'], $item['p2'], $item['p3'], $item['p4'], $item['p5'],
$item['p6'], $item['p7'], $item['p8'], $item['p9'],
2016110
    $item['module'],  $item['link_title'], serialize($item['options']),
$item['customized'], $item['mlid']);
2017
  // Check the has_children status of the parent.
2018110
  _menu_update_parental_status($item);
2019110
  menu_cache_clear($menu_name);
2020110
  if ($existing_item && $menu_name != $existing_item['menu_name']) {
20210
    menu_cache_clear($existing_item['menu_name']);
20220
  }
2023
2024110
  _menu_clear_page_cache();
2025110
  return $item['mlid'];
20260
}
2027
2028
/**
2029
 * Helper function to clear the page and block caches at most twice per
page load.
2030
 */
20312027
function _menu_clear_page_cache() {
2032113
  static $cache_cleared = 0;
2033
2034
  // Clear the page and block caches, but at most twice, including at
2035
  //  the end of the page load when there are multple links saved or
deleted.
2036113
  if (empty($cache_cleared)) {
2037113
    cache_clear_all();
2038
    // Keep track of which menus have expanded items.
2039113
    _menu_set_expanded_menus();
2040113
    $cache_cleared = 1;
2041113
  }
204283
  elseif ($cache_cleared == 1) {
204383
    register_shutdown_function('cache_clear_all');
2044
    // Keep track of which menus have expanded items.
204583
    register_shutdown_function('_menu_set_expanded_menus');
204683
    $cache_cleared = 2;
204783
  }
2048113
}
2049
2050
/**
2051
 * Helper function to update a list of menus with expanded items
2052
 */
20532027
function _menu_set_expanded_menus() {
2054113
  $names = array();
2055113
  $result = db_query("SELECT menu_name FROM {menu_links} WHERE expanded !=
0 GROUP BY menu_name");
2056113
  while ($n = db_fetch_array($result)) {
205720
    $names[] = $n['menu_name'];
205820
  }
2059113
  variable_set('menu_expanded', $names);
2060113
}
2061
2062
/**
2063
 * Find the router path which will serve this path.
2064
 *
2065
 * @param $menu
2066
 *  The full built menu.
2067
 * @param $link_path
2068
 *  The path for we are looking up its router path.
2069
 * @return
2070
 *  A path from $menu keys or empty if $link_path points to a nonexisting
2071
 *  place.
2072
 */
20732027
function _menu_find_router_path($menu, $link_path) {
2074107
  $parts = explode('/', $link_path, MENU_MAX_PARTS);
2075107
  $router_path = $link_path;
2076107
  if (!isset($menu[$router_path])) {
207786
    list($ancestors) = menu_get_ancestors($parts);
207886
    $ancestors[] = '';
207986
    foreach ($ancestors as $key => $router_path) {
208086
      if (isset($menu[$router_path])) {
208186
        break;
20820
      }
208386
    }
208486
  }
2085107
  return $router_path;
20860
}
2087
2088
/**
2089
 * Insert, update or delete an uncustomized menu link related to a module.
2090
 *
2091
 * @param $module
2092
 *   The name of the module.
2093
 * @param $op
2094
 *   Operation to perform: insert, update or delete.
2095
 * @param $link_path
2096
 *   The path this link points to.
2097
 * @param $link_title
2098
 *   Title of the link to insert or new title to update the link to.
2099
 *   Unused for delete.
2100
 * @return
2101
 *   The insert op returns the mlid of the new item. Others op return
NULL.
2102
 */
21032027
function menu_link_maintain($module, $op, $link_path, $link_title) {
2104
  switch ($op) {
21051
    case 'insert':
2106
      $menu_link = array(
21071
        'link_title' => $link_title,
21081
        'link_path' => $link_path,
21091
        'module' => $module,
21101
      );
21111
      return menu_link_save($menu_link);
21120
      break;
21130
    case 'update':
21140
      db_query("UPDATE {menu_links} SET link_title = '%s' WHERE link_path =
'%s' AND customized = 0 AND module = '%s'", $link_title, $link_path,
$module);
21150
      $result = db_query("SELECT menu_name FROM {menu_links} WHERE
link_path = '%s' AND customized = 0 AND module = '%s'", $link_path,
$module);
21160
      while ($item = db_fetch_array($result)) {
21170
        menu_cache_clear($item['menu_name']);
21180
      }
21190
      break;
21200
    case 'delete':
21210
      menu_link_delete(NULL, $link_path);
21220
      break;
21230
  }
21240
}
2125
2126
/**
2127
 * Find the depth of an item's children relative to its depth.
2128
 *
2129
 * For example, if the item has a depth of 2, and the maximum of any child
in
2130
 * the menu link tree is 5, the relative depth is 3.
2131
 *
2132
 * @param $item
2133
 *   An array representing a menu link item.
2134
 * @return
2135
 *   The relative depth, or zero.
2136
 *
2137
 */
21382027
function menu_link_children_relative_depth($item) {
213993
  $i = 1;
214093
  $match = '';
214193
  $args[] = $item['menu_name'];
214293
  $p = 'p1';
214393
  while ($i <= MENU_MAX_DEPTH && $item[$p]) {
214493
    $match .= " AND $p = %d";
214593
    $args[] = $item[$p];
214693
    $p = 'p' . ++$i;
214793
  }
2148
214993
  $max_depth = db_result(db_query_range("SELECT depth FROM {menu_links}
WHERE menu_name = '%s'" . $match . " ORDER BY depth DESC", $args, 0, 1));
2150
215193
  return ($max_depth > $item['depth']) ? $max_depth - $item['depth'] : 0;
21520
}
2153
2154
/**
2155
 * Update the children of a menu link that's being moved.
2156
 *
2157
 * The menu name, parents (p1 - p6), and depth are updated for all children
of
2158
 * the link, and the has_children status of the previous parent is
updated.
2159
 */
21602027
function _menu_link_move_children($item, $existing_item) {
2161
21622
  $args[] = $item['menu_name'];
21632
  $set[] = "menu_name = '%s'";
2164
21652
  $i = 1;
21662
  while ($i <= $item['depth']) {
21672
    $p = 'p' . $i++;
21682
    $set[] = "$p = %d";
21692
    $args[] = $item[$p];
21702
  }
21712
  $j = $existing_item['depth'] + 1;
21722
  while ($i <= MENU_MAX_DEPTH && $j <= MENU_MAX_DEPTH) {
21732
    $set[] = 'p' . $i++ . ' = p' . $j++;
21742
  }
21752
  while ($i <= MENU_MAX_DEPTH) {
21762
    $set[] = 'p' . $i++ . ' = 0';
21772
  }
2178
21792
  $shift = $item['depth'] - $existing_item['depth'];
21802
  if ($shift < 0) {
21812
    $args[] = -$shift;
21822
    $set[] = 'depth = depth - %d';
21832
  }
21840
  elseif ($shift > 0) {
2185
    // The order of $set must be reversed so the new values don't overwrite
the
2186
    // old ones before they can be used because "Single-table UPDATE
2187
    // assignments are generally evaluated from left to right"
2188
    // see: http://dev.mysql.com/doc/refman/5.0/en/update.html
21890
    $set = array_reverse($set);
21900
    $args = array_reverse($args);
2191
21920
    $args[] = $shift;
21930
    $set[] = 'depth = depth + %d';
21940
  }
21952
  $where[] = "menu_name = '%s'";
21962
  $args[] = $existing_item['menu_name'];
21972
  $p = 'p1';
21982
  for ($i = 1; $i <= MENU_MAX_DEPTH && $existing_item[$p]; $p = 'p' . ++$i)
{
21992
    $where[] = "$p = %d";
22002
    $args[] = $existing_item[$p];
22012
  }
2202
22032
  db_query("UPDATE {menu_links} SET " . implode(', ', $set) . " WHERE " .
implode(' AND ', $where), $args);
2204
  // Check the has_children status of the parent, while excluding this
item.
22052
  _menu_update_parental_status($existing_item, TRUE);
22062
}
2207
2208
/**
2209
 * Check and update the has_children status for the parent of a link.
2210
 */
22112027
function _menu_update_parental_status($item, $exclude = FALSE) {
2212
  // If plid == 0, there is nothing to update.
2213113
  if ($item['plid']) {
2214
    // We may want to exclude the passed link as a possible child.
221599
    $where = $exclude ? " AND mlid != %d" : '';
2216
    // Check if at least one visible child exists in the table.
221799
    $parent_has_children = (bool)db_result(db_query_range("SELECT mlid FROM
{menu_links} WHERE menu_name = '%s' AND plid = %d AND hidden = 0" . $where,
$item['menu_name'], $item['plid'], $item['mlid'], 0, 1));
221899
    db_query("UPDATE {menu_links} SET has_children = %d WHERE mlid = %d",
$parent_has_children, $item['plid']);
221999
  }
2220113
}
2221
2222
/**
2223
 * Helper function that sets the p1..p9 values for a menu link being
saved.
2224
 */
22252027
function _menu_link_parents_set(&$item, $parent) {
222696
  $i = 1;
222796
  while ($i < $item['depth']) {
222896
    $p = 'p' . $i++;
222996
    $item[$p] = $parent[$p];
223096
  }
223196
  $p = 'p' . $i++;
2232
  // The parent (p1 - p9) corresponding to the depth always equals the
mlid.
223396
  $item[$p] = $item['mlid'];
223496
  while ($i <= MENU_MAX_DEPTH) {
223596
    $p = 'p' . $i++;
223696
    $item[$p] = 0;
223796
  }
223896
}
2239
2240
/**
2241
 * Helper function to build the router table based on the data from
hook_menu.
2242
 */
22432027
function _menu_router_build($callbacks) {
2244
  // First pass: separate callbacks from paths, making paths ready for
2245
  // matching. Calculate fitness, and fill some default values.
224682
  $menu = array();
224782
  foreach ($callbacks as $path => $item) {
224882
    $load_functions = array();
224982
    $to_arg_functions = array();
225082
    $fit = 0;
225182
    $move = FALSE;
2252
225382
    $parts = explode('/', $path, MENU_MAX_PARTS);
225482
    $number_parts = count($parts);
2255
    // We store the highest index of parts here to save some work in the
fit
2256
    // calculation loop.
225782
    $slashes = $number_parts - 1;
2258
    // Extract load and to_arg functions.
225982
    foreach ($parts as $k => $part) {
226082
      $match = FALSE;
226182
      if (preg_match('/^%([a-z_]*)$/', $part, $matches)) {
226282
        if (empty($matches[1])) {
226382
          $match = TRUE;
226482
          $load_functions[$k] = NULL;
226582
        }
2266
        else {
226782
          if (drupal_function_exists($matches[1] . '_to_arg')) {
226882
            $to_arg_functions[$k] = $matches[1] . '_to_arg';
226982
            $load_functions[$k] = NULL;
227082
            $match = TRUE;
227182
          }
227282
          if (drupal_function_exists($matches[1] . '_load')) {
227382
            $function = $matches[1] . '_load';
2274
            // Create an array of arguments that will be passed to the
_load
2275
            // function when this menu path is checked, if 'load
arguments'
2276
            // exists.
227782
            $load_functions[$k] = isset($item['load arguments']) ?
array($function => $item['load arguments']) : $function;
227882
            $match = TRUE;
227982
          }
2280
        }
228182
      }
228282
      if ($match) {
228382
        $parts[$k] = '%';
228482
      }
2285
      else {
228682
        $fit |=  1 << ($slashes - $k);
2287
      }
228882
    }
228982
    if ($fit) {
229082
      $move = TRUE;
229182
    }
2292
    else {
2293
      // If there is no %, it fits maximally.
22940
      $fit = (1 << $number_parts) - 1;
2295
    }
229682
    $masks[$fit] = 1;
229782
    $item['load_functions'] = empty($load_functions) ? '' :
serialize($load_functions);
229882
    $item['to_arg_functions'] = empty($to_arg_functions) ? '' :
serialize($to_arg_functions);
2299
    $item += array(
230082
      'title' => '',
230182
      'weight' => 0,
230282
      'type' => MENU_NORMAL_ITEM,
230382
      '_number_parts' => $number_parts,
230482
      '_parts' => $parts,
230582
      '_fit' => $fit,
23060
    );
2307
    $item += array(
230882
      '_visible' => (bool)($item['type'] & MENU_VISIBLE_IN_BREADCRUMB),
230982
      '_tab' => (bool)($item['type'] & MENU_IS_LOCAL_TASK),
23100
    );
231182
    if ($move) {
231282
      $new_path = implode('/', $item['_parts']);
231382
      $menu[$new_path] = $item;
231482
      $sort[$new_path] = $number_parts;
231582
    }
2316
    else {
23170
      $menu[$path] = $item;
23180
      $sort[$path] = $number_parts;
2319
    }
232082
  }
232182
  array_multisort($sort, SORT_NUMERIC, $menu);
2322
232382
  if ($menu) {
2324
    // Delete the existing router since we have some data to replace it.
232582
    db_query('DELETE FROM {menu_router}');
232682
  }
2327
  // Apply inheritance rules.
232882
  foreach ($menu as $path => $v) {
232982
    $item = &$menu[$path];
233082
    if (!$item['_tab']) {
2331
      // Non-tab items.
233282
      $item['tab_parent'] = '';
233382
      $item['tab_root'] = $path;
233482
    }
233582
    for ($i = $item['_number_parts'] - 1; $i; $i--) {
233682
      $parent_path = implode('/', array_slice($item['_parts'], 0, $i));
233782
      if (isset($menu[$parent_path])) {
2338
233982
        $parent = $menu[$parent_path];
2340
234182
        if (!isset($item['tab_parent'])) {
2342
          // Parent stores the parent of the path.
234382
          $item['tab_parent'] = $parent_path;
234482
        }
234582
        if (!isset($item['tab_root']) && !$parent['_tab']) {
234682
          $item['tab_root'] = $parent_path;
234782
        }
2348
        // If an access callback is not found for a default local task we
use
2349
        // the callback from the parent, since we expect them to be
identical.
2350
        // In all other cases, the access parameters must be specified.
235182
        if (($item['type'] == MENU_DEFAULT_LOCAL_TASK) &&
!isset($item['access callback']) && isset($parent['access callback'])) {
235282
          $item['access callback'] = $parent['access callback'];
235382
          if (!isset($item['access arguments']) && isset($parent['access
arguments'])) {
235482
            $item['access arguments'] = $parent['access arguments'];
235582
          }
235682
        }
2357
        // Same for page callbacks.
235882
        if (!isset($item['page callback']) && isset($parent['page
callback'])) {
235982
          $item['page callback'] = $parent['page callback'];
236082
          if (!isset($item['page arguments']) && isset($parent['page
arguments'])) {
236182
            $item['page arguments'] = $parent['page arguments'];
236282
          }
236382
        }
236482
      }
236582
    }
236682
    if (!isset($item['access callback']) && isset($item['access
arguments'])) {
2367
      // Default callback.
236882
      $item['access callback'] = 'user_access';
236982
    }
237082
    if (!isset($item['access callback']) || empty($item['page callback']))
{
23710
      $item['access callback'] = 0;
23720
    }
237382
    if (is_bool($item['access callback'])) {
237482
      $item['access callback'] = intval($item['access callback']);
237582
    }
2376
2377
    $item += array(
237882
      'access arguments' => array(),
237982
      'access callback' => '',
238082
      'page arguments' => array(),
238182
      'page callback' => '',
238282
      'block callback' => '',
238382
      'title arguments' => array(),
238482
      'title callback' => 't',
238582
      'description' => '',
238682
      'position' => '',
238782
      'tab_parent' => '',
238882
      'tab_root' => $path,
238982
      'path' => $path,
23900
    );
2391
239282
    $title_arguments = $item['title arguments'] ? serialize($item['title
arguments']) : '';
239382
    db_query("INSERT INTO {menu_router}
2394
      (path, load_functions, to_arg_functions, access_callback,
2395
      access_arguments, page_callback, page_arguments, fit,
2396
      number_parts, tab_parent, tab_root,
2397
      title, title_callback, title_arguments,
2398
      type, block_callback, description, position, weight)
2399
      VALUES ('%s', '%s', '%s', '%s',
2400
      '%s', '%s', '%s', %d,
2401
      %d, '%s', '%s',
2402
      '%s', '%s', '%s',
240382
      %d, '%s', '%s', '%s', %d)",
240482
      $path, $item['load_functions'], $item['to_arg_functions'],
$item['access callback'],
240582
      serialize($item['access arguments']), $item['page callback'],
serialize($item['page arguments']), $item['_fit'],
240682
      $item['_number_parts'], $item['tab_parent'], $item['tab_root'],
240782
      $item['title'], $item['title callback'], $title_arguments,
240882
      $item['type'], $item['block callback'], $item['description'],
$item['position'], $item['weight']);
240982
  }
2410
  // Sort the masks so they are in order of descending fit, and store
them.
241182
  $masks = array_keys($masks);
241282
  rsort($masks);
241382
  variable_set('menu_masks', $masks);
241482
  cache_set('router:', $menu, 'cache_menu');
241582
  return $menu;
24160
}
2417
2418
/**
2419
 * Returns TRUE if a path is external (e.g. http://example.com).
2420
 */
24212027
function menu_path_is_external($path) {
2422114
  $colonpos = strpos($path, ':');
2423114
  return $colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0,
$colonpos)) && filter_xss_bad_protocol($path, FALSE) ==
check_plain($path);
24240
}
2425
2426
/**
2427
 * Checks whether the site is offline for maintenance.
2428
 *
2429
 * This function will log the current user out and redirect to front page
2430
 * if the current user has no 'administer site configuration' permission.
2431
 *
2432
 * @return
2433
 *   FALSE if the site is not offline or its the login page or the user
has
2434
 *     'administer site configuration' permission.
2435
 *   TRUE for anonymous users not on the login page if the site is
offline.
2436
 */
24372027
function _menu_site_is_offline() {
2438
  // Check if site is set to offline mode.
24392010
  if (variable_get('site_offline', 0)) {
2440
    // Check if the user has administration privileges.
24410
    if (user_access('administer site configuration')) {
2442
      // Ensure that the offline message is displayed only once [allowing
for
2443
      // page redirects], and specifically suppress its display on the
site
2444
      // maintenance page.
24450
      if (drupal_get_normal_path($_GET['q']) !=
'admin/settings/site-maintenance') {
24460
        drupal_set_message(t('Operating in offline mode.'), 'status',
FALSE);
24470
      }
24480
    }
2449
    else {
2450
      // Anonymous users get a FALSE at the login prompt, TRUE otherwise.
24510
      if (user_is_anonymous()) {
24520
        return $_GET['q'] != 'user' && $_GET['q'] != 'user/login';
24530
      }
2454
      // Logged in users are unprivileged here, so they are logged out.
24550
      require_once drupal_get_path('module', 'user') . '/user.pages.inc';
24560
      user_logout();
2457
    }
24580
  }
24592010
  return FALSE;
24600
}
2461
2462
/**
2463
 * Validates the path of a menu link being created or edited.
2464
 *
2465
 * @return
2466
 *   TRUE if it is a valid path AND the current user has access
permission,
2467
 *   FALSE otherwise.
2468
 */
24692027
function menu_valid_path($form_item) {
247021
  global $menu_admin;
247121
  $item = array();
247221
  $path = $form_item['link_path'];
2473
  // We indicate that a menu administrator is running the menu access
check.
247421
  $menu_admin = TRUE;
247521
  if ($path == '<front>' || menu_path_is_external($path)) {
24760
    $item = array('access' => TRUE);
24770
  }
247821
  elseif (preg_match('/\/\%/', $path)) {
2479
    // Path is dynamic (ie 'user/%'), so check directly against menu_router
table.
24800
    if ($item = db_fetch_array(db_query("SELECT * FROM {menu_router} where
path = '%s' ", $path))) {
24810
      $item['link_path']  = $form_item['link_path'];
24820
      $item['link_title'] = $form_item['link_title'];
24830
      $item['external']   = FALSE;
24840
      $item['options'] = '';
24850
      _menu_link_translate($item);
24860
    }
24870
  }
2488
  else {
248921
    $item = menu_get_item($path);
2490
  }
249121
  $menu_admin = FALSE;
249221
  return $item && $item['access'];
24930
}
2494
2495
/**
2496
 * @} End of "defgroup menu".
2497
 */
24982027