Projet

Général

Profil

Paste
Télécharger (139 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / menu.inc @ 01dfd3b5

1
<?php
2

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

    
8
/**
9
 * @defgroup menu Menu system
10
 * @{
11
 * Define the navigation menus, and route page requests to code based on URLs.
12
 *
13
 * The Drupal menu system drives both the navigation system from a user
14
 * perspective and the callback system that Drupal uses to respond to URLs
15
 * passed from the browser. For this reason, a good understanding of the
16
 * menu system is fundamental to the creation of complex modules. As a note,
17
 * this is related to, but separate from menu.module, which allows menus
18
 * (which in this context are hierarchical lists of links) to be customized from
19
 * the Drupal administrative interface.
20
 *
21
 * Drupal's menu system follows a simple hierarchy defined by paths.
22
 * Implementations of hook_menu() define menu items and assign them to
23
 * paths (which should be unique). The menu system aggregates these items
24
 * and determines the menu hierarchy from the paths. For example, if the
25
 * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
26
 * would form the structure:
27
 * - a
28
 *   - a/b
29
 *     - a/b/c/d
30
 *     - a/b/h
31
 * - e
32
 * - f/g
33
 * Note that the number of elements in the path does not necessarily
34
 * determine the depth of the menu item in the tree.
35
 *
36
 * When responding to a page request, the menu system looks to see if the
37
 * path requested by the browser is registered as a menu item with a
38
 * callback. If not, the system searches up the menu tree for the most
39
 * complete match with a callback it can find. If the path a/b/i is
40
 * requested in the tree above, the callback for a/b would be used.
41
 *
42
 * The found callback function is called with any arguments specified
43
 * in the "page arguments" attribute of its menu item. The
44
 * attribute must be an array. After these arguments, any remaining
45
 * components of the path are appended as further arguments. In this
46
 * way, the callback for a/b above could respond to a request for
47
 * a/b/i differently than a request for a/b/j.
48
 *
49
 * For an illustration of this process, see page_example.module.
50
 *
51
 * Access to the callback functions is also protected by the menu system.
52
 * The "access callback" with an optional "access arguments" of each menu
53
 * item is called before the page callback proceeds. If this returns TRUE,
54
 * then access is granted; if FALSE, then access is denied. Default local task
55
 * menu items (see next paragraph) may omit this attribute to use the value
56
 * provided by the parent item.
57
 *
58
 * In the default Drupal interface, you will notice many links rendered as
59
 * tabs. These are known in the menu system as "local tasks", and they are
60
 * rendered as tabs by default, though other presentations are possible.
61
 * Local tasks function just as other menu items in most respects. It is
62
 * convention that the names of these tasks should be short verbs if
63
 * possible. In addition, a "default" local task should be provided for
64
 * each set. When visiting a local task's parent menu item, the default
65
 * local task will be rendered as if it is selected; this provides for a
66
 * normal tab user experience. This default task is special in that it
67
 * links not to its provided path, but to its parent item's path instead.
68
 * The default task's path is only used to place it appropriately in the
69
 * menu hierarchy.
70
 *
71
 * Everything described so far is stored in the menu_router table. The
72
 * menu_links table holds the visible menu links. By default these are
73
 * derived from the same hook_menu definitions, however you are free to
74
 * add more with menu_link_save().
75
 */
76

    
77
/**
78
 * @defgroup menu_flags Menu flags
79
 * @{
80
 * Flags for use in the "type" attribute of menu items.
81
 */
82

    
83
/**
84
 * Internal menu flag -- menu item is the root of the menu tree.
85
 */
86
define('MENU_IS_ROOT', 0x0001);
87

    
88
/**
89
 * Internal menu flag -- menu item is visible in the menu tree.
90
 */
91
define('MENU_VISIBLE_IN_TREE', 0x0002);
92

    
93
/**
94
 * Internal menu flag -- menu item is visible in the breadcrumb.
95
 */
96
define('MENU_VISIBLE_IN_BREADCRUMB', 0x0004);
97

    
98
/**
99
 * Internal menu flag -- menu item links back to its parent.
100
 */
101
define('MENU_LINKS_TO_PARENT', 0x0008);
102

    
103
/**
104
 * Internal menu flag -- menu item can be modified by administrator.
105
 */
106
define('MENU_MODIFIED_BY_ADMIN', 0x0020);
107

    
108
/**
109
 * Internal menu flag -- menu item was created by administrator.
110
 */
111
define('MENU_CREATED_BY_ADMIN', 0x0040);
112

    
113
/**
114
 * Internal menu flag -- menu item is a local task.
115
 */
116
define('MENU_IS_LOCAL_TASK', 0x0080);
117

    
118
/**
119
 * Internal menu flag -- menu item is a local action.
120
 */
121
define('MENU_IS_LOCAL_ACTION', 0x0100);
122

    
123
/**
124
 * @} End of "Menu flags".
125
 */
126

    
127
/**
128
 * @defgroup menu_item_types Menu item types
129
 * @{
130
 * Definitions for various menu item types.
131
 *
132
 * Menu item definitions provide one of these constants, which are shortcuts for
133
 * combinations of @link menu_flags Menu flags @endlink.
134
 */
135

    
136
/**
137
 * Menu type -- A "normal" menu item that's shown in menu and breadcrumbs.
138
 *
139
 * Normal menu items show up in the menu tree and can be moved/hidden by
140
 * the administrator. Use this for most menu items. It is the default value if
141
 * no menu item type is specified.
142
 */
143
define('MENU_NORMAL_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB);
144

    
145
/**
146
 * Menu type -- A hidden, internal callback, typically used for API calls.
147
 *
148
 * Callbacks simply register a path so that the correct function is fired
149
 * when the URL is accessed. They do not appear in menus or breadcrumbs.
150
 */
151
define('MENU_CALLBACK', 0x0000);
152

    
153
/**
154
 * Menu type -- A normal menu item, hidden until enabled by an administrator.
155
 *
156
 * Modules may "suggest" menu items that the administrator may enable. They act
157
 * just as callbacks do until enabled, at which time they act like normal items.
158
 * Note for the value: 0x0010 was a flag which is no longer used, but this way
159
 * the values of MENU_CALLBACK and MENU_SUGGESTED_ITEM are separate.
160
 */
161
define('MENU_SUGGESTED_ITEM', MENU_VISIBLE_IN_BREADCRUMB | 0x0010);
162

    
163
/**
164
 * Menu type -- A task specific to the parent item, usually rendered as a tab.
165
 *
166
 * Local tasks are menu items that describe actions to be performed on their
167
 * parent item. An example is the path "node/52/edit", which performs the
168
 * "edit" task on "node/52".
169
 */
170
define('MENU_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_VISIBLE_IN_BREADCRUMB);
171

    
172
/**
173
 * Menu type -- The "default" local task, which is initially active.
174
 *
175
 * Every set of local tasks should provide one "default" task, that links to the
176
 * same path as its parent when clicked.
177
 */
178
define('MENU_DEFAULT_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT | MENU_VISIBLE_IN_BREADCRUMB);
179

    
180
/**
181
 * Menu type -- An action specific to the parent, usually rendered as a link.
182
 *
183
 * Local actions are menu items that describe actions on the parent item such
184
 * as adding a new user, taxonomy term, etc.
185
 */
186
define('MENU_LOCAL_ACTION', MENU_IS_LOCAL_TASK | MENU_IS_LOCAL_ACTION | MENU_VISIBLE_IN_BREADCRUMB);
187

    
188
/**
189
 * @} End of "Menu item types".
190
 */
191

    
192
/**
193
 * @defgroup menu_context_types Menu context types
194
 * @{
195
 * Flags for use in the "context" attribute of menu router items.
196
 */
197

    
198
/**
199
 * Internal menu flag: Invisible local task.
200
 *
201
 * This flag may be used for local tasks like "Delete", so custom modules and
202
 * themes can alter the default context and expose the task by altering menu.
203
 */
204
define('MENU_CONTEXT_NONE', 0x0000);
205

    
206
/**
207
 * Internal menu flag: Local task should be displayed in page context.
208
 */
209
define('MENU_CONTEXT_PAGE', 0x0001);
210

    
211
/**
212
 * Internal menu flag: Local task should be displayed inline.
213
 */
214
define('MENU_CONTEXT_INLINE', 0x0002);
215

    
216
/**
217
 * @} End of "Menu context types".
218
 */
219

    
220
/**
221
 * @defgroup menu_status_codes Menu status codes
222
 * @{
223
 * Status codes for menu callbacks.
224
 */
225

    
226
/**
227
 * Internal menu status code -- Menu item was found.
228
 */
229
define('MENU_FOUND', 1);
230

    
231
/**
232
 * Menu status code -- Not found.
233
 *
234
 * This can be used as the return value from a page callback, although it is
235
 * preferable to use a load function to accomplish this; see the hook_menu()
236
 * documentation for details.
237
 */
238
define('MENU_NOT_FOUND', 2);
239

    
240
/**
241
 * Menu status code -- Access denied.
242
 *
243
 * This can be used as the return value from a page callback, although it is
244
 * preferable to use an access callback to accomplish this; see the hook_menu()
245
 * documentation for details.
246
 */
247
define('MENU_ACCESS_DENIED', 3);
248

    
249
/**
250
 * Internal menu status code -- Menu item inaccessible because site is offline.
251
 */
252
define('MENU_SITE_OFFLINE', 4);
253

    
254
/**
255
 * Internal menu status code -- Everything is working fine.
256
 */
257
define('MENU_SITE_ONLINE', 5);
258

    
259
/**
260
 * @} End of "Menu status codes".
261
 */
262

    
263
/**
264
 * @defgroup menu_tree_parameters Menu tree parameters
265
 * @{
266
 * Parameters for a menu tree.
267
 */
268

    
269
 /**
270
 * The maximum number of path elements for a menu callback
271
 */
272
define('MENU_MAX_PARTS', 9);
273

    
274

    
275
/**
276
 * The maximum depth of a menu links tree - matches the number of p columns.
277
 */
278
define('MENU_MAX_DEPTH', 9);
279

    
280

    
281
/**
282
 * @} End of "Menu tree parameters".
283
 */
284

    
285
/**
286
 * Reserved key to identify the most specific menu link for a given path.
287
 *
288
 * The value of this constant is a hash of the constant name. We use the hash
289
 * so that the reserved key is over 32 characters in length and will not
290
 * collide with allowed menu names:
291
 * @code
292
 * sha1('MENU_PREFERRED_LINK') = 1cf698d64d1aa4b83907cf6ed55db3a7f8e92c91
293
 * @endcode
294
 *
295
 * @see menu_link_get_preferred()
296
 */
297
define('MENU_PREFERRED_LINK', '1cf698d64d1aa4b83907cf6ed55db3a7f8e92c91');
298

    
299
/**
300
 * Returns the ancestors (and relevant placeholders) for any given path.
301
 *
302
 * For example, the ancestors of node/12345/edit are:
303
 * - node/12345/edit
304
 * - node/12345/%
305
 * - node/%/edit
306
 * - node/%/%
307
 * - node/12345
308
 * - node/%
309
 * - node
310
 *
311
 * To generate these, we will use binary numbers. Each bit represents a
312
 * part of the path. If the bit is 1, then it represents the original
313
 * value while 0 means wildcard. If the path is node/12/edit/foo
314
 * then the 1011 bitstring represents node/%/edit/foo where % means that
315
 * any argument matches that part. We limit ourselves to using binary
316
 * numbers that correspond the patterns of wildcards of router items that
317
 * actually exists. This list of 'masks' is built in menu_rebuild().
318
 *
319
 * @param $parts
320
 *   An array of path parts; for the above example, 
321
 *   array('node', '12345', 'edit').
322
 *
323
 * @return
324
 *   An array which contains the ancestors and placeholders. Placeholders
325
 *   simply contain as many '%s' as the ancestors.
326
 */
327
function menu_get_ancestors($parts) {
328
  $number_parts = count($parts);
329
  $ancestors = array();
330
  $length =  $number_parts - 1;
331
  $end = (1 << $number_parts) - 1;
332
  $masks = variable_get('menu_masks');
333
  // If the optimized menu_masks array is not available use brute force to get
334
  // the correct $ancestors and $placeholders returned. Do not use this as the
335
  // default value of the menu_masks variable to avoid building such a big
336
  // array.
337
  if (!$masks) {
338
    $masks = range(511, 1);
339
  }
340
  // Only examine patterns that actually exist as router items (the masks).
341
  foreach ($masks as $i) {
342
    if ($i > $end) {
343
      // Only look at masks that are not longer than the path of interest.
344
      continue;
345
    }
346
    elseif ($i < (1 << $length)) {
347
      // We have exhausted the masks of a given length, so decrease the length.
348
      --$length;
349
    }
350
    $current = '';
351
    for ($j = $length; $j >= 0; $j--) {
352
      // Check the bit on the $j offset.
353
      if ($i & (1 << $j)) {
354
        // Bit one means the original value.
355
        $current .= $parts[$length - $j];
356
      }
357
      else {
358
        // Bit zero means means wildcard.
359
        $current .= '%';
360
      }
361
      // Unless we are at offset 0, add a slash.
362
      if ($j) {
363
        $current .= '/';
364
      }
365
    }
366
    $ancestors[] = $current;
367
  }
368
  return $ancestors;
369
}
370

    
371
/**
372
 * Unserializes menu data, using a map to replace path elements.
373
 *
374
 * The menu system stores various path-related information (such as the 'page
375
 * arguments' and 'access arguments' components of a menu item) in the database
376
 * using serialized arrays, where integer values in the arrays represent
377
 * arguments to be replaced by values from the path. This function first
378
 * unserializes such menu information arrays, and then does the path
379
 * replacement.
380
 *
381
 * The path replacement acts on each integer-valued element of the unserialized
382
 * menu data array ($data) using a map array ($map, which is typically an array
383
 * of path arguments) as a list of replacements. For instance, if there is an
384
 * element of $data whose value is the number 2, then it is replaced in $data
385
 * with $map[2]; non-integer values in $data are left alone.
386
 *
387
 * As an example, an unserialized $data array with elements ('node_load', 1)
388
 * represents instructions for calling the node_load() function. Specifically,
389
 * this instruction says to use the path component at index 1 as the input
390
 * parameter to node_load(). If the path is 'node/123', then $map will be the
391
 * array ('node', 123), and the returned array from this function will have
392
 * elements ('node_load', 123), since $map[1] is 123. This return value will
393
 * indicate specifically that node_load(123) is to be called to load the node
394
 * whose ID is 123 for this menu item.
395
 *
396
 * @param $data
397
 *   A serialized array of menu data, as read from the database.
398
 * @param $map
399
 *   A path argument array, used to replace integer values in $data; an integer
400
 *   value N in $data will be replaced by value $map[N]. Typically, the $map
401
 *   array is generated from a call to the arg() function.
402
 *
403
 * @return
404
 *   The unserialized $data array, with path arguments replaced.
405
 */
406
function menu_unserialize($data, $map) {
407
  if ($data = unserialize($data)) {
408
    foreach ($data as $k => $v) {
409
      if (is_int($v)) {
410
        $data[$k] = isset($map[$v]) ? $map[$v] : '';
411
      }
412
    }
413
    return $data;
414
  }
415
  else {
416
    return array();
417
  }
418
}
419

    
420

    
421

    
422
/**
423
 * Replaces the statically cached item for a given path.
424
 *
425
 * @param $path
426
 *   The path.
427
 * @param $router_item
428
 *   The router item. Usually a router entry from menu_get_item() is either
429
 *   modified or set to a different path. This allows the navigation block,
430
 *   the page title, the breadcrumb, and the page help to be modified in one
431
 *   call.
432
 */
433
function menu_set_item($path, $router_item) {
434
  menu_get_item($path, $router_item);
435
}
436

    
437
/**
438
 * Gets a router item.
439
 *
440
 * @param $path
441
 *   The path; for example, 'node/5'. The function will find the corresponding
442
 *   node/% item and return that. Defaults to the current path.
443
 * @param $router_item
444
 *   Internal use only.
445
 *
446
 * @return
447
 *   The router item or, if an error occurs in _menu_translate(), FALSE. A
448
 *   router item is an associative array corresponding to one row in the
449
 *   menu_router table. The value corresponding to the key 'map' holds the
450
 *   loaded objects. The value corresponding to the key 'access' is TRUE if the
451
 *   current user can access this page. The values corresponding to the keys
452
 *   'title', 'page_arguments', 'access_arguments', and 'theme_arguments' will
453
 *   be filled in based on the database values and the objects loaded.
454
 */
455
function menu_get_item($path = NULL, $router_item = NULL) {
456
  $router_items = &drupal_static(__FUNCTION__);
457
  if (!isset($path)) {
458
    $path = $_GET['q'];
459
  }
460
  if (isset($router_item)) {
461
    $router_items[$path] = $router_item;
462
  }
463
  if (!isset($router_items[$path])) {
464
    // Rebuild if we know it's needed, or if the menu masks are missing which
465
    // occurs rarely, likely due to a race condition of multiple rebuilds.
466
    if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
467
      if (_menu_check_rebuild()) {
468
        menu_rebuild();
469
      }
470
    }
471
    $original_map = arg(NULL, $path);
472

    
473
    $parts = array_slice($original_map, 0, MENU_MAX_PARTS);
474
    $ancestors = menu_get_ancestors($parts);
475
    $router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();
476

    
477
    if ($router_item) {
478
      // Allow modules to alter the router item before it is translated and
479
      // checked for access.
480
      drupal_alter('menu_get_item', $router_item, $path, $original_map);
481

    
482
      $map = _menu_translate($router_item, $original_map);
483
      $router_item['original_map'] = $original_map;
484
      if ($map === FALSE) {
485
        $router_items[$path] = FALSE;
486
        return FALSE;
487
      }
488
      if ($router_item['access']) {
489
        $router_item['map'] = $map;
490
        $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
491
        $router_item['theme_arguments'] = array_merge(menu_unserialize($router_item['theme_arguments'], $map), array_slice($map, $router_item['number_parts']));
492
      }
493
    }
494
    $router_items[$path] = $router_item;
495
  }
496
  return $router_items[$path];
497
}
498

    
499
/**
500
 * Execute the page callback associated with the current path.
501
 *
502
 * @param $path
503
 *   The drupal path whose handler is to be be executed. If set to NULL, then
504
 *   the current path is used.
505
 * @param $deliver
506
 *   (optional) A boolean to indicate whether the content should be sent to the
507
 *   browser using the appropriate delivery callback (TRUE) or whether to return
508
 *   the result to the caller (FALSE).
509
 */
510
function menu_execute_active_handler($path = NULL, $deliver = TRUE) {
511
  // Check if site is offline.
512
  $page_callback_result = _menu_site_is_offline() ? MENU_SITE_OFFLINE : MENU_SITE_ONLINE;
513

    
514
  // Allow other modules to change the site status but not the path because that
515
  // would not change the global variable. hook_url_inbound_alter() can be used
516
  // to change the path. Code later will not use the $read_only_path variable.
517
  $read_only_path = !empty($path) ? $path : $_GET['q'];
518
  drupal_alter('menu_site_status', $page_callback_result, $read_only_path);
519

    
520
  // Only continue if the site status is not set.
521
  if ($page_callback_result == MENU_SITE_ONLINE) {
522
    if ($router_item = menu_get_item($path)) {
523
      if ($router_item['access']) {
524
        if ($router_item['include_file']) {
525
          require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
526
        }
527
        $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
528
      }
529
      else {
530
        $page_callback_result = MENU_ACCESS_DENIED;
531
      }
532
    }
533
    else {
534
      $page_callback_result = MENU_NOT_FOUND;
535
    }
536
  }
537

    
538
  // Deliver the result of the page callback to the browser, or if requested,
539
  // return it raw, so calling code can do more processing.
540
  if ($deliver) {
541
    $default_delivery_callback = (isset($router_item) && $router_item) ? $router_item['delivery_callback'] : NULL;
542
    drupal_deliver_page($page_callback_result, $default_delivery_callback);
543
  }
544
  else {
545
    return $page_callback_result;
546
  }
547
}
548

    
549
/**
550
 * Loads objects into the map as defined in the $item['load_functions'].
551
 *
552
 * @param $item
553
 *   A menu router or menu link item
554
 * @param $map
555
 *   An array of path arguments; for example, array('node', '5').
556
 *
557
 * @return
558
 *   Returns TRUE for success, FALSE if an object cannot be loaded.
559
 *   Names of object loading functions are placed in $item['load_functions'].
560
 *   Loaded objects are placed in $map[]; keys are the same as keys in the
561
 *   $item['load_functions'] array.
562
 *   $item['access'] is set to FALSE if an object cannot be loaded.
563
 */
564
function _menu_load_objects(&$item, &$map) {
565
  if ($load_functions = $item['load_functions']) {
566
    // If someone calls this function twice, then unserialize will fail.
567
    if (!is_array($load_functions)) {
568
      $load_functions = unserialize($load_functions);
569
    }
570
    $path_map = $map;
571
    foreach ($load_functions as $index => $function) {
572
      if ($function) {
573
        $value = isset($path_map[$index]) ? $path_map[$index] : '';
574
        if (is_array($function)) {
575
          // Set up arguments for the load function. These were pulled from
576
          // 'load arguments' in the hook_menu() entry, but they need
577
          // some processing. In this case the $function is the key to the
578
          // load_function array, and the value is the list of arguments.
579
          $args = current($function);
580
          $function = key($function);
581
          $load_functions[$index] = $function;
582

    
583
          // Some arguments are placeholders for dynamic items to process.
584
          foreach ($args as $i => $arg) {
585
            if ($arg === '%index') {
586
              // Pass on argument index to the load function, so multiple
587
              // occurrences of the same placeholder can be identified.
588
              $args[$i] = $index;
589
            }
590
            if ($arg === '%map') {
591
              // Pass on menu map by reference. The accepting function must
592
              // also declare this as a reference if it wants to modify
593
              // the map.
594
              $args[$i] = &$map;
595
            }
596
            if (is_int($arg)) {
597
              $args[$i] = isset($path_map[$arg]) ? $path_map[$arg] : '';
598
            }
599
          }
600
          array_unshift($args, $value);
601
          $return = call_user_func_array($function, $args);
602
        }
603
        else {
604
          $return = $function($value);
605
        }
606
        // If callback returned an error or there is no callback, trigger 404.
607
        if ($return === FALSE) {
608
          $item['access'] = FALSE;
609
          $map = FALSE;
610
          return FALSE;
611
        }
612
        $map[$index] = $return;
613
      }
614
    }
615
    $item['load_functions'] = $load_functions;
616
  }
617
  return TRUE;
618
}
619

    
620
/**
621
 * Checks access to a menu item using the access callback.
622
 *
623
 * @param $item
624
 *   A menu router or menu link item
625
 * @param $map
626
 *   An array of path arguments; for example, array('node', '5').
627
 *
628
 * @return
629
 *   $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
630
 */
631
function _menu_check_access(&$item, $map) {
632
  $item['access'] = FALSE;
633
  // Determine access callback, which will decide whether or not the current
634
  // user has access to this path.
635
  $callback = empty($item['access_callback']) ? 0 : trim($item['access_callback']);
636
  // Check for a TRUE or FALSE value.
637
  if (is_numeric($callback)) {
638
    $item['access'] = (bool) $callback;
639
  }
640
  else {
641
    $arguments = menu_unserialize($item['access_arguments'], $map);
642
    // As call_user_func_array is quite slow and user_access is a very common
643
    // callback, it is worth making a special case for it.
644
    if ($callback == 'user_access') {
645
      $item['access'] = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
646
    }
647
    elseif (function_exists($callback)) {
648
      $item['access'] = call_user_func_array($callback, $arguments);
649
    }
650
  }
651
}
652

    
653
/**
654
 * Localizes the router item title using t() or another callback.
655
 *
656
 * Translate the title and description to allow storage of English title
657
 * strings in the database, yet display of them in the language required
658
 * by the current user.
659
 *
660
 * @param $item
661
 *   A menu router item or a menu link item.
662
 * @param $map
663
 *   The path as an array with objects already replaced. E.g., for path
664
 *   node/123 $map would be array('node', $node) where $node is the node
665
 *   object for node 123.
666
 * @param $link_translate
667
 *   TRUE if we are translating a menu link item; FALSE if we are
668
 *   translating a menu router item.
669
 *
670
 * @return
671
 *   No return value.
672
 *   $item['title'] is localized according to $item['title_callback'].
673
 *   If an item's callback is check_plain(), $item['options']['html'] becomes
674
 *   TRUE.
675
 *   $item['description'] is translated using t().
676
 *   When doing link translation and the $item['options']['attributes']['title']
677
 *   (link title attribute) matches the description, it is translated as well.
678
 */
679
function _menu_item_localize(&$item, $map, $link_translate = FALSE) {
680
  $callback = $item['title_callback'];
681
  $item['localized_options'] = $item['options'];
682
  // All 'class' attributes are assumed to be an array during rendering, but
683
  // links stored in the database may use an old string value.
684
  // @todo In order to remove this code we need to implement a database update
685
  //   including unserializing all existing link options and running this code
686
  //   on them, as well as adding validation to menu_link_save().
687
  if (isset($item['options']['attributes']['class']) && is_string($item['options']['attributes']['class'])) {
688
    $item['localized_options']['attributes']['class'] = explode(' ', $item['options']['attributes']['class']);
689
  }
690
  // If we are translating the title of a menu link, and its title is the same
691
  // as the corresponding router item, then we can use the title information
692
  // from the router. If it's customized, then we need to use the link title
693
  // itself; can't localize.
694
  // If we are translating a router item (tabs, page, breadcrumb), then we
695
  // can always use the information from the router item.
696
  if (!$link_translate || ($item['title'] == $item['link_title'])) {
697
    // t() is a special case. Since it is used very close to all the time,
698
    // we handle it directly instead of using indirect, slower methods.
699
    if ($callback == 't') {
700
      if (empty($item['title_arguments'])) {
701
        $item['title'] = t($item['title']);
702
      }
703
      else {
704
        $item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));
705
      }
706
    }
707
    elseif ($callback && function_exists($callback)) {
708
      if (empty($item['title_arguments'])) {
709
        $item['title'] = $callback($item['title']);
710
      }
711
      else {
712
        $item['title'] = call_user_func_array($callback, menu_unserialize($item['title_arguments'], $map));
713
      }
714
      // Avoid calling check_plain again on l() function.
715
      if ($callback == 'check_plain') {
716
        $item['localized_options']['html'] = TRUE;
717
      }
718
    }
719
  }
720
  elseif ($link_translate) {
721
    $item['title'] = $item['link_title'];
722
  }
723

    
724
  // Translate description, see the motivation above.
725
  if (!empty($item['description'])) {
726
    $original_description = $item['description'];
727
    $item['description'] = t($item['description']);
728
    if ($link_translate && isset($item['options']['attributes']['title']) && $item['options']['attributes']['title'] == $original_description) {
729
      $item['localized_options']['attributes']['title'] = $item['description'];
730
    }
731
  }
732
}
733

    
734
/**
735
 * Handles dynamic path translation and menu access control.
736
 *
737
 * When a user arrives on a page such as node/5, this function determines
738
 * what "5" corresponds to, by inspecting the page's menu path definition,
739
 * node/%node. This will call node_load(5) to load the corresponding node
740
 * object.
741
 *
742
 * It also works in reverse, to allow the display of tabs and menu items which
743
 * contain these dynamic arguments, translating node/%node to node/5.
744
 *
745
 * Translation of menu item titles and descriptions are done here to
746
 * allow for storage of English strings in the database, and translation
747
 * to the language required to generate the current page.
748
 *
749
 * @param $router_item
750
 *   A menu router item
751
 * @param $map
752
 *   An array of path arguments; for example, array('node', '5').
753
 * @param $to_arg
754
 *   Execute $item['to_arg_functions'] or not. Use only if you want to render a
755
 *   path from the menu table, for example tabs.
756
 *
757
 * @return
758
 *   Returns the map with objects loaded as defined in the
759
 *   $item['load_functions']. $item['access'] becomes TRUE if the item is
760
 *   accessible, FALSE otherwise. $item['href'] is set according to the map.
761
 *   If an error occurs during calling the load_functions (like trying to load
762
 *   a non-existent node) then this function returns FALSE.
763
 */
764
function _menu_translate(&$router_item, $map, $to_arg = FALSE) {
765
  if ($to_arg && !empty($router_item['to_arg_functions'])) {
766
    // Fill in missing path elements, such as the current uid.
767
    _menu_link_map_translate($map, $router_item['to_arg_functions']);
768
  }
769
  // The $path_map saves the pieces of the path as strings, while elements in
770
  // $map may be replaced with loaded objects.
771
  $path_map = $map;
772
  if (!empty($router_item['load_functions']) && !_menu_load_objects($router_item, $map)) {
773
    // An error occurred loading an object.
774
    $router_item['access'] = FALSE;
775
    return FALSE;
776
  }
777

    
778
  // Generate the link path for the page request or local tasks.
779
  $link_map = explode('/', $router_item['path']);
780
  if (isset($router_item['tab_root'])) {
781
    $tab_root_map = explode('/', $router_item['tab_root']);
782
  }
783
  if (isset($router_item['tab_parent'])) {
784
    $tab_parent_map = explode('/', $router_item['tab_parent']);
785
  }
786
  for ($i = 0; $i < $router_item['number_parts']; $i++) {
787
    if ($link_map[$i] == '%') {
788
      $link_map[$i] = $path_map[$i];
789
    }
790
    if (isset($tab_root_map[$i]) && $tab_root_map[$i] == '%') {
791
      $tab_root_map[$i] = $path_map[$i];
792
    }
793
    if (isset($tab_parent_map[$i]) && $tab_parent_map[$i] == '%') {
794
      $tab_parent_map[$i] = $path_map[$i];
795
    }
796
  }
797
  $router_item['href'] = implode('/', $link_map);
798
  $router_item['tab_root_href'] = implode('/', $tab_root_map);
799
  $router_item['tab_parent_href'] = implode('/', $tab_parent_map);
800
  $router_item['options'] = array();
801
  _menu_check_access($router_item, $map);
802

    
803
  // For performance, don't localize an item the user can't access.
804
  if ($router_item['access']) {
805
    _menu_item_localize($router_item, $map);
806
  }
807

    
808
  return $map;
809
}
810

    
811
/**
812
 * Translates the path elements in the map using any to_arg helper function.
813
 *
814
 * @param $map
815
 *   An array of path arguments; for example, array('node', '5').
816
 * @param $to_arg_functions
817
 *   An array of helper functions; for example, array(2 => 'menu_tail_to_arg').
818
 *
819
 * @see hook_menu()
820
 */
821
function _menu_link_map_translate(&$map, $to_arg_functions) {
822
  $to_arg_functions = unserialize($to_arg_functions);
823
  foreach ($to_arg_functions as $index => $function) {
824
    // Translate place-holders into real values.
825
    $arg = $function(!empty($map[$index]) ? $map[$index] : '', $map, $index);
826
    if (!empty($map[$index]) || isset($arg)) {
827
      $map[$index] = $arg;
828
    }
829
    else {
830
      unset($map[$index]);
831
    }
832
  }
833
}
834

    
835
/**
836
 * Returns a string containing the path relative to the current index.
837
 */
838
function menu_tail_to_arg($arg, $map, $index) {
839
  return implode('/', array_slice($map, $index));
840
}
841

    
842
/**
843
 * Loads the path as one string relative to the current index.
844
 *
845
 * To use this load function, you must specify the load arguments
846
 * in the router item as:
847
 * @code
848
 * $item['load arguments'] = array('%map', '%index');
849
 * @endcode
850
 *
851
 * @see search_menu().
852
 */
853
function menu_tail_load($arg, &$map, $index) {
854
  $arg = implode('/', array_slice($map, $index));
855
  $map = array_slice($map, 0, $index);
856
  return $arg;
857
}
858

    
859
/**
860
 * Provides menu link access control, translation, and argument handling.
861
 *
862
 * This function is similar to _menu_translate(), but it also does
863
 * link-specific preparation (such as always calling to_arg() functions).
864
 *
865
 * @param $item
866
 *   A menu link.
867
 * @param $translate
868
 *   (optional) Whether to try to translate a link containing dynamic path
869
 *   argument placeholders (%) based on the menu router item of the current
870
 *   path. Defaults to FALSE. Internally used for breadcrumbs.
871
 *
872
 * @return
873
 *   Returns the map of path arguments with objects loaded as defined in the
874
 *   $item['load_functions'].
875
 *   $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
876
 *   $item['href'] is generated from link_path, possibly by to_arg functions.
877
 *   $item['title'] is generated from link_title, and may be localized.
878
 *   $item['options'] is unserialized; it is also changed within the call here
879
 *   to $item['localized_options'] by _menu_item_localize().
880
 */
881
function _menu_link_translate(&$item, $translate = FALSE) {
882
  if (!is_array($item['options'])) {
883
    $item['options'] = unserialize($item['options']);
884
  }
885
  if ($item['external']) {
886
    $item['access'] = 1;
887
    $map = array();
888
    $item['href'] = $item['link_path'];
889
    $item['title'] = $item['link_title'];
890
    $item['localized_options'] = $item['options'];
891
  }
892
  else {
893
    // Complete the path of the menu link with elements from the current path,
894
    // if it contains dynamic placeholders (%).
895
    $map = explode('/', $item['link_path']);
896
    if (strpos($item['link_path'], '%') !== FALSE) {
897
      // Invoke registered to_arg callbacks.
898
      if (!empty($item['to_arg_functions'])) {
899
        _menu_link_map_translate($map, $item['to_arg_functions']);
900
      }
901
      // Or try to derive the path argument map from the current router item,
902
      // if this $item's path is within the router item's path. This means
903
      // that if we are on the current path 'foo/%/bar/%/baz', then
904
      // menu_get_item() will have translated the menu router item for the
905
      // current path, and we can take over the argument map for a link like
906
      // 'foo/%/bar'. This inheritance is only valid for breadcrumb links.
907
      // @see _menu_tree_check_access()
908
      // @see menu_get_active_breadcrumb()
909
      elseif ($translate && ($current_router_item = menu_get_item())) {
910
        // If $translate is TRUE, then this link is in the active trail.
911
        // Only translate paths within the current path.
912
        if (strpos($current_router_item['path'], $item['link_path']) === 0) {
913
          $count = count($map);
914
          $map = array_slice($current_router_item['original_map'], 0, $count);
915
          $item['original_map'] = $map;
916
          if (isset($current_router_item['map'])) {
917
            $item['map'] = array_slice($current_router_item['map'], 0, $count);
918
          }
919
          // Reset access to check it (for the first time).
920
          unset($item['access']);
921
        }
922
      }
923
    }
924
    $item['href'] = implode('/', $map);
925

    
926
    // Skip links containing untranslated arguments.
927
    if (strpos($item['href'], '%') !== FALSE) {
928
      $item['access'] = FALSE;
929
      return FALSE;
930
    }
931
    // menu_tree_check_access() may set this ahead of time for links to nodes.
932
    if (!isset($item['access'])) {
933
      if (!empty($item['load_functions']) && !_menu_load_objects($item, $map)) {
934
        // An error occurred loading an object.
935
        $item['access'] = FALSE;
936
        return FALSE;
937
      }
938
      _menu_check_access($item, $map);
939
    }
940
    // For performance, don't localize a link the user can't access.
941
    if ($item['access']) {
942
      _menu_item_localize($item, $map, TRUE);
943
    }
944
  }
945

    
946
  // Allow other customizations - e.g. adding a page-specific query string to the
947
  // options array. For performance reasons we only invoke this hook if the link
948
  // has the 'alter' flag set in the options array.
949
  if (!empty($item['options']['alter'])) {
950
    drupal_alter('translated_menu_link', $item, $map);
951
  }
952

    
953
  return $map;
954
}
955

    
956
/**
957
 * Gets a loaded object from a router item.
958
 *
959
 * menu_get_object() provides access to objects loaded by the current router
960
 * item. For example, on the page node/%node, the router loads the %node object,
961
 * and calling menu_get_object() will return that. Normally, it is necessary to
962
 * specify the type of object referenced, however node is the default.
963
 * The following example tests to see whether the node being displayed is of the
964
 * "story" content type:
965
 * @code
966
 * $node = menu_get_object();
967
 * $story = $node->type == 'story';
968
 * @endcode
969
 *
970
 * @param $type
971
 *   Type of the object. These appear in hook_menu definitions as %type. Core
972
 *   provides aggregator_feed, aggregator_category, contact, filter_format,
973
 *   forum_term, menu, menu_link, node, taxonomy_vocabulary, user. See the
974
 *   relevant {$type}_load function for more on each. Defaults to node.
975
 * @param $position
976
 *   The position of the object in the path, where the first path segment is 0.
977
 *   For node/%node, the position of %node is 1, but for comment/reply/%node,
978
 *   it's 2. Defaults to 1.
979
 * @param $path
980
 *   See menu_get_item() for more on this. Defaults to the current path.
981
 */
982
function menu_get_object($type = 'node', $position = 1, $path = NULL) {
983
  $router_item = menu_get_item($path);
984
  if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type . '_load') {
985
    return $router_item['map'][$position];
986
  }
987
}
988

    
989
/**
990
 * Renders a menu tree based on the current path.
991
 *
992
 * The tree is expanded based on the current path and dynamic paths are also
993
 * changed according to the defined to_arg functions (for example the 'My
994
 * account' link is changed from user/% to a link with the current user's uid).
995
 *
996
 * @param $menu_name
997
 *   The name of the menu.
998
 *
999
 * @return
1000
 *   A structured array representing the specified menu on the current page, to
1001
 *   be rendered by drupal_render().
1002
 */
1003
function menu_tree($menu_name) {
1004
  $menu_output = &drupal_static(__FUNCTION__, array());
1005

    
1006
  if (!isset($menu_output[$menu_name])) {
1007
    $tree = menu_tree_page_data($menu_name);
1008
    $menu_output[$menu_name] = menu_tree_output($tree);
1009
  }
1010
  return $menu_output[$menu_name];
1011
}
1012

    
1013
/**
1014
 * Returns an output structure for rendering a menu tree.
1015
 *
1016
 * The menu item's LI element is given one of the following classes:
1017
 * - expanded: The menu item is showing its submenu.
1018
 * - collapsed: The menu item has a submenu which is not shown.
1019
 * - leaf: The menu item has no submenu.
1020
 *
1021
 * @param $tree
1022
 *   A data structure representing the tree as returned from menu_tree_data.
1023
 *
1024
 * @return
1025
 *   A structured array to be rendered by drupal_render().
1026
 */
1027
function menu_tree_output($tree) {
1028
  $build = array();
1029
  $items = array();
1030

    
1031
  // Pull out just the menu links we are going to render so that we
1032
  // get an accurate count for the first/last classes.
1033
  foreach ($tree as $data) {
1034
    if ($data['link']['access'] && !$data['link']['hidden']) {
1035
      $items[] = $data;
1036
    }
1037
  }
1038

    
1039
  $router_item = menu_get_item();
1040
  $num_items = count($items);
1041
  foreach ($items as $i => $data) {
1042
    $class = array();
1043
    if ($i == 0) {
1044
      $class[] = 'first';
1045
    }
1046
    if ($i == $num_items - 1) {
1047
      $class[] = 'last';
1048
    }
1049
    // Set a class for the <li>-tag. Since $data['below'] may contain local
1050
    // tasks, only set 'expanded' class if the link also has children within
1051
    // the current menu.
1052
    if ($data['link']['has_children'] && $data['below']) {
1053
      $class[] = 'expanded';
1054
    }
1055
    elseif ($data['link']['has_children']) {
1056
      $class[] = 'collapsed';
1057
    }
1058
    else {
1059
      $class[] = 'leaf';
1060
    }
1061
    // Set a class if the link is in the active trail.
1062
    if ($data['link']['in_active_trail']) {
1063
      $class[] = 'active-trail';
1064
      $data['link']['localized_options']['attributes']['class'][] = 'active-trail';
1065
    }
1066
    // Normally, l() compares the href of every link with $_GET['q'] and sets
1067
    // the active class accordingly. But local tasks do not appear in menu
1068
    // trees, so if the current path is a local task, and this link is its
1069
    // tab root, then we have to set the class manually.
1070
    if ($router_item && $data['link']['href'] == $router_item['tab_root_href'] && $data['link']['href'] != $_GET['q']) {
1071
      $data['link']['localized_options']['attributes']['class'][] = 'active';
1072
    }
1073

    
1074
    // Allow menu-specific theme overrides.
1075
    $element['#theme'] = 'menu_link__' . strtr($data['link']['menu_name'], '-', '_');
1076
    $element['#attributes']['class'] = $class;
1077
    $element['#title'] = $data['link']['title'];
1078
    $element['#href'] = $data['link']['href'];
1079
    $element['#localized_options'] = !empty($data['link']['localized_options']) ? $data['link']['localized_options'] : array();
1080
    $element['#below'] = $data['below'] ? menu_tree_output($data['below']) : $data['below'];
1081
    $element['#original_link'] = $data['link'];
1082
    // Index using the link's unique mlid.
1083
    $build[$data['link']['mlid']] = $element;
1084
  }
1085
  if ($build) {
1086
    // Make sure drupal_render() does not re-order the links.
1087
    $build['#sorted'] = TRUE;
1088
    // Add the theme wrapper for outer markup.
1089
    // Allow menu-specific theme overrides.
1090
    $build['#theme_wrappers'][] = 'menu_tree__' . strtr($data['link']['menu_name'], '-', '_');
1091
  }
1092

    
1093
  return $build;
1094
}
1095

    
1096
/**
1097
 * Gets the data structure representing a named menu tree.
1098
 *
1099
 * Since this can be the full tree including hidden items, the data returned
1100
 * may be used for generating an an admin interface or a select.
1101
 *
1102
 * @param $menu_name
1103
 *   The named menu links to return
1104
 * @param $link
1105
 *   A fully loaded menu link, or NULL. If a link is supplied, only the
1106
 *   path to root will be included in the returned tree - as if this link
1107
 *   represented the current page in a visible menu.
1108
 * @param $max_depth
1109
 *   Optional maximum depth of links to retrieve. Typically useful if only one
1110
 *   or two levels of a sub tree are needed in conjunction with a non-NULL
1111
 *   $link, in which case $max_depth should be greater than $link['depth'].
1112
 *
1113
 * @return
1114
 *   An tree of menu links in an array, in the order they should be rendered.
1115
 */
1116
function menu_tree_all_data($menu_name, $link = NULL, $max_depth = NULL) {
1117
  $tree = &drupal_static(__FUNCTION__, array());
1118

    
1119
  // Use $mlid as a flag for whether the data being loaded is for the whole tree.
1120
  $mlid = isset($link['mlid']) ? $link['mlid'] : 0;
1121
  // Generate a cache ID (cid) specific for this $menu_name, $link, $language, and depth.
1122
  $cid = 'links:' . $menu_name . ':all:' . $mlid . ':' . $GLOBALS['language']->language . ':' . (int) $max_depth;
1123

    
1124
  if (!isset($tree[$cid])) {
1125
    // If the static variable doesn't have the data, check {cache_menu}.
1126
    $cache = cache_get($cid, 'cache_menu');
1127
    if ($cache && isset($cache->data)) {
1128
      // If the cache entry exists, it contains the parameters for
1129
      // menu_build_tree().
1130
      $tree_parameters = $cache->data;
1131
    }
1132
    // If the tree data was not in the cache, build $tree_parameters.
1133
    if (!isset($tree_parameters)) {
1134
      $tree_parameters = array(
1135
        'min_depth' => 1,
1136
        'max_depth' => $max_depth,
1137
      );
1138
      if ($mlid) {
1139
        // The tree is for a single item, so we need to match the values in its
1140
        // p columns and 0 (the top level) with the plid values of other links.
1141
        $parents = array(0);
1142
        for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
1143
          if (!empty($link["p$i"])) {
1144
            $parents[] = $link["p$i"];
1145
          }
1146
        }
1147
        $tree_parameters['expanded'] = $parents;
1148
        $tree_parameters['active_trail'] = $parents;
1149
        $tree_parameters['active_trail'][] = $mlid;
1150
      }
1151

    
1152
      // Cache the tree building parameters using the page-specific cid.
1153
      cache_set($cid, $tree_parameters, 'cache_menu');
1154
    }
1155

    
1156
    // Build the tree using the parameters; the resulting tree will be cached
1157
    // by _menu_build_tree()).
1158
    $tree[$cid] = menu_build_tree($menu_name, $tree_parameters);
1159
  }
1160

    
1161
  return $tree[$cid];
1162
}
1163

    
1164
/**
1165
 * Sets the path for determining the active trail of the specified menu tree.
1166
 *
1167
 * This path will also affect the breadcrumbs under some circumstances.
1168
 * Breadcrumbs are built using the preferred link returned by
1169
 * menu_link_get_preferred(). If the preferred link is inside one of the menus
1170
 * specified in calls to menu_tree_set_path(), the preferred link will be
1171
 * overridden by the corresponding path returned by menu_tree_get_path().
1172
 *
1173
 * Setting this path does not affect the main content; for that use
1174
 * menu_set_active_item() instead.
1175
 *
1176
 * @param $menu_name
1177
 *   The name of the affected menu tree.
1178
 * @param $path
1179
 *   The path to use when finding the active trail.
1180
 */
1181
function menu_tree_set_path($menu_name, $path = NULL) {
1182
  $paths = &drupal_static(__FUNCTION__);
1183
  if (isset($path)) {
1184
    $paths[$menu_name] = $path;
1185
  }
1186
  return isset($paths[$menu_name]) ? $paths[$menu_name] : NULL;
1187
}
1188

    
1189
/**
1190
 * Gets the path for determining the active trail of the specified menu tree.
1191
 *
1192
 * @param $menu_name
1193
 *   The menu name of the requested tree.
1194
 *
1195
 * @return
1196
 *   A string containing the path. If no path has been specified with
1197
 *   menu_tree_set_path(), NULL is returned.
1198
 */
1199
function menu_tree_get_path($menu_name) {
1200
  return menu_tree_set_path($menu_name);
1201
}
1202

    
1203
/**
1204
 * Gets the data structure for a named menu tree, based on the current page.
1205
 *
1206
 * The tree order is maintained by storing each parent in an individual
1207
 * field, see http://drupal.org/node/141866 for more.
1208
 *
1209
 * @param $menu_name
1210
 *   The named menu links to return.
1211
 * @param $max_depth
1212
 *   (optional) The maximum depth of links to retrieve.
1213
 * @param $only_active_trail
1214
 *   (optional) Whether to only return the links in the active trail (TRUE)
1215
 *   instead of all links on every level of the menu link tree (FALSE). Defaults
1216
 *   to FALSE. Internally used for breadcrumbs only.
1217
 *
1218
 * @return
1219
 *   An array of menu links, in the order they should be rendered. The array
1220
 *   is a list of associative arrays -- these have two keys, link and below.
1221
 *   link is a menu item, ready for theming as a link. Below represents the
1222
 *   submenu below the link if there is one, and it is a subtree that has the
1223
 *   same structure described for the top-level array.
1224
 */
1225
function menu_tree_page_data($menu_name, $max_depth = NULL, $only_active_trail = FALSE) {
1226
  $tree = &drupal_static(__FUNCTION__, array());
1227

    
1228
  // Check if the active trail has been overridden for this menu tree.
1229
  $active_path = menu_tree_get_path($menu_name);
1230
  // Load the menu item corresponding to the current page.
1231
  if ($item = menu_get_item($active_path)) {
1232
    if (isset($max_depth)) {
1233
      $max_depth = min($max_depth, MENU_MAX_DEPTH);
1234
    }
1235
    // Generate a cache ID (cid) specific for this page.
1236
    $cid = 'links:' . $menu_name . ':page:' . $item['href'] . ':' . $GLOBALS['language']->language . ':' . (int) $item['access'] . ':' . (int) $max_depth;
1237
    // If we are asked for the active trail only, and $menu_name has not been
1238
    // built and cached for this page yet, then this likely means that it
1239
    // won't be built anymore, as this function is invoked from
1240
    // template_process_page(). So in order to not build a giant menu tree
1241
    // that needs to be checked for access on all levels, we simply check
1242
    // whether we have the menu already in cache, or otherwise, build a minimum
1243
    // tree containing the breadcrumb/active trail only.
1244
    // @see menu_set_active_trail()
1245
    if (!isset($tree[$cid]) && $only_active_trail) {
1246
      $cid .= ':trail';
1247
    }
1248

    
1249
    if (!isset($tree[$cid])) {
1250
      // If the static variable doesn't have the data, check {cache_menu}.
1251
      $cache = cache_get($cid, 'cache_menu');
1252
      if ($cache && isset($cache->data)) {
1253
        // If the cache entry exists, it contains the parameters for
1254
        // menu_build_tree().
1255
        $tree_parameters = $cache->data;
1256
      }
1257
      // If the tree data was not in the cache, build $tree_parameters.
1258
      if (!isset($tree_parameters)) {
1259
        $tree_parameters = array(
1260
          'min_depth' => 1,
1261
          'max_depth' => $max_depth,
1262
        );
1263
        // Parent mlids; used both as key and value to ensure uniqueness.
1264
        // We always want all the top-level links with plid == 0.
1265
        $active_trail = array(0 => 0);
1266

    
1267
        // If the item for the current page is accessible, build the tree
1268
        // parameters accordingly.
1269
        if ($item['access']) {
1270
          // Find a menu link corresponding to the current path. If $active_path
1271
          // is NULL, let menu_link_get_preferred() determine the path.
1272
          if ($active_link = menu_link_get_preferred($active_path, $menu_name)) {
1273
            // The active link may only be taken into account to build the
1274
            // active trail, if it resides in the requested menu. Otherwise,
1275
            // we'd needlessly re-run _menu_build_tree() queries for every menu
1276
            // on every page.
1277
            if ($active_link['menu_name'] == $menu_name) {
1278
              // Use all the coordinates, except the last one because there
1279
              // can be no child beyond the last column.
1280
              for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
1281
                if ($active_link['p' . $i]) {
1282
                  $active_trail[$active_link['p' . $i]] = $active_link['p' . $i];
1283
                }
1284
              }
1285
              // If we are asked to build links for the active trail only, skip
1286
              // the entire 'expanded' handling.
1287
              if ($only_active_trail) {
1288
                $tree_parameters['only_active_trail'] = TRUE;
1289
              }
1290
            }
1291
          }
1292
          $parents = $active_trail;
1293

    
1294
          $expanded = variable_get('menu_expanded', array());
1295
          // Check whether the current menu has any links set to be expanded.
1296
          if (!$only_active_trail && in_array($menu_name, $expanded)) {
1297
            // Collect all the links set to be expanded, and then add all of
1298
            // their children to the list as well.
1299
            do {
1300
              $result = db_select('menu_links', NULL, array('fetch' => PDO::FETCH_ASSOC))
1301
                ->fields('menu_links', array('mlid'))
1302
                ->condition('menu_name', $menu_name)
1303
                ->condition('expanded', 1)
1304
                ->condition('has_children', 1)
1305
                ->condition('plid', $parents, 'IN')
1306
                ->condition('mlid', $parents, 'NOT IN')
1307
                ->execute();
1308
              $num_rows = FALSE;
1309
              foreach ($result as $item) {
1310
                $parents[$item['mlid']] = $item['mlid'];
1311
                $num_rows = TRUE;
1312
              }
1313
            } while ($num_rows);
1314
          }
1315
          $tree_parameters['expanded'] = $parents;
1316
          $tree_parameters['active_trail'] = $active_trail;
1317
        }
1318
        // If access is denied, we only show top-level links in menus.
1319
        else {
1320
          $tree_parameters['expanded'] = $active_trail;
1321
          $tree_parameters['active_trail'] = $active_trail;
1322
        }
1323
        // Cache the tree building parameters using the page-specific cid.
1324
        cache_set($cid, $tree_parameters, 'cache_menu');
1325
      }
1326

    
1327
      // Build the tree using the parameters; the resulting tree will be cached
1328
      // by _menu_build_tree().
1329
      $tree[$cid] = menu_build_tree($menu_name, $tree_parameters);
1330
    }
1331
    return $tree[$cid];
1332
  }
1333

    
1334
  return array();
1335
}
1336

    
1337
/**
1338
 * Builds a menu tree, translates links, and checks access.
1339
 *
1340
 * @param $menu_name
1341
 *   The name of the menu.
1342
 * @param $parameters
1343
 *   (optional) An associative array of build parameters. Possible keys:
1344
 *   - expanded: An array of parent link ids to return only menu links that are
1345
 *     children of one of the plids in this list. If empty, the whole menu tree
1346
 *     is built, unless 'only_active_trail' is TRUE.
1347
 *   - active_trail: An array of mlids, representing the coordinates of the
1348
 *     currently active menu link.
1349
 *   - only_active_trail: Whether to only return links that are in the active
1350
 *     trail. This option is ignored, if 'expanded' is non-empty. Internally
1351
 *     used for breadcrumbs.
1352
 *   - min_depth: The minimum depth of menu links in the resulting tree.
1353
 *     Defaults to 1, which is the default to build a whole tree for a menu
1354
 *     (excluding menu container itself).
1355
 *   - max_depth: The maximum depth of menu links in the resulting tree.
1356
 *   - conditions: An associative array of custom database select query
1357
 *     condition key/value pairs; see _menu_build_tree() for the actual query.
1358
 *
1359
 * @return
1360
 *   A fully built menu tree.
1361
 */
1362
function menu_build_tree($menu_name, array $parameters = array()) {
1363
  // Build the menu tree.
1364
  $data = _menu_build_tree($menu_name, $parameters);
1365
  // Check access for the current user to each item in the tree.
1366
  menu_tree_check_access($data['tree'], $data['node_links']);
1367
  return $data['tree'];
1368
}
1369

    
1370
/**
1371
 * Builds a menu tree.
1372
 *
1373
 * This function may be used build the data for a menu tree only, for example
1374
 * to further massage the data manually before further processing happens.
1375
 * menu_tree_check_access() needs to be invoked afterwards.
1376
 *
1377
 * @see menu_build_tree()
1378
 */
1379
function _menu_build_tree($menu_name, array $parameters = array()) {
1380
  // Static cache of already built menu trees.
1381
  $trees = &drupal_static(__FUNCTION__, array());
1382

    
1383
  // Build the cache id; sort parents to prevent duplicate storage and remove
1384
  // default parameter values.
1385
  if (isset($parameters['expanded'])) {
1386
    sort($parameters['expanded']);
1387
  }
1388
  $tree_cid = 'links:' . $menu_name . ':tree-data:' . $GLOBALS['language']->language . ':' . hash('sha256', serialize($parameters));
1389

    
1390
  // If we do not have this tree in the static cache, check {cache_menu}.
1391
  if (!isset($trees[$tree_cid])) {
1392
    $cache = cache_get($tree_cid, 'cache_menu');
1393
    if ($cache && isset($cache->data)) {
1394
      $trees[$tree_cid] = $cache->data;
1395
    }
1396
  }
1397

    
1398
  if (!isset($trees[$tree_cid])) {
1399
    // Select the links from the table, and recursively build the tree. We
1400
    // LEFT JOIN since there is no match in {menu_router} for an external
1401
    // link.
1402
    $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
1403
    $query->addTag('translatable');
1404
    $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
1405
    $query->fields('ml');
1406
    $query->fields('m', array(
1407
      'load_functions',
1408
      'to_arg_functions',
1409
      'access_callback',
1410
      'access_arguments',
1411
      'page_callback',
1412
      'page_arguments',
1413
      'delivery_callback',
1414
      'tab_parent',
1415
      'tab_root',
1416
      'title',
1417
      'title_callback',
1418
      'title_arguments',
1419
      'theme_callback',
1420
      'theme_arguments',
1421
      'type',
1422
      'description',
1423
    ));
1424
    for ($i = 1; $i <= MENU_MAX_DEPTH; $i++) {
1425
      $query->orderBy('p' . $i, 'ASC');
1426
    }
1427
    $query->condition('ml.menu_name', $menu_name);
1428
    if (!empty($parameters['expanded'])) {
1429
      $query->condition('ml.plid', $parameters['expanded'], 'IN');
1430
    }
1431
    elseif (!empty($parameters['only_active_trail'])) {
1432
      $query->condition('ml.mlid', $parameters['active_trail'], 'IN');
1433
    }
1434
    $min_depth = (isset($parameters['min_depth']) ? $parameters['min_depth'] : 1);
1435
    if ($min_depth != 1) {
1436
      $query->condition('ml.depth', $min_depth, '>=');
1437
    }
1438
    if (isset($parameters['max_depth'])) {
1439
      $query->condition('ml.depth', $parameters['max_depth'], '<=');
1440
    }
1441
    // Add custom query conditions, if any were passed.
1442
    if (isset($parameters['conditions'])) {
1443
      foreach ($parameters['conditions'] as $column => $value) {
1444
        $query->condition($column, $value);
1445
      }
1446
    }
1447

    
1448
    // Build an ordered array of links using the query result object.
1449
    $links = array();
1450
    foreach ($query->execute() as $item) {
1451
      $links[] = $item;
1452
    }
1453
    $active_trail = (isset($parameters['active_trail']) ? $parameters['active_trail'] : array());
1454
    $data['tree'] = menu_tree_data($links, $active_trail, $min_depth);
1455
    $data['node_links'] = array();
1456
    menu_tree_collect_node_links($data['tree'], $data['node_links']);
1457

    
1458
    // Cache the data, if it is not already in the cache.
1459
    cache_set($tree_cid, $data, 'cache_menu');
1460
    $trees[$tree_cid] = $data;
1461
  }
1462

    
1463
  return $trees[$tree_cid];
1464
}
1465

    
1466
/**
1467
 * Collects node links from a given menu tree recursively.
1468
 *
1469
 * @param $tree
1470
 *   The menu tree you wish to collect node links from.
1471
 * @param $node_links
1472
 *   An array in which to store the collected node links.
1473
 */
1474
function menu_tree_collect_node_links(&$tree, &$node_links) {
1475
  foreach ($tree as $key => $v) {
1476
    if ($tree[$key]['link']['router_path'] == 'node/%') {
1477
      $nid = substr($tree[$key]['link']['link_path'], 5);
1478
      if (is_numeric($nid)) {
1479
        $node_links[$nid][$tree[$key]['link']['mlid']] = &$tree[$key]['link'];
1480
        $tree[$key]['link']['access'] = FALSE;
1481
      }
1482
    }
1483
    if ($tree[$key]['below']) {
1484
      menu_tree_collect_node_links($tree[$key]['below'], $node_links);
1485
    }
1486
  }
1487
}
1488

    
1489
/**
1490
 * Checks access and performs dynamic operations for each link in the tree.
1491
 *
1492
 * @param $tree
1493
 *   The menu tree you wish to operate on.
1494
 * @param $node_links
1495
 *   A collection of node link references generated from $tree by
1496
 *   menu_tree_collect_node_links().
1497
 */
1498
function menu_tree_check_access(&$tree, $node_links = array()) {
1499
  if ($node_links && (user_access('access content') || user_access('bypass node access'))) {
1500
    $nids = array_keys($node_links);
1501
    $select = db_select('node', 'n');
1502
    $select->addField('n', 'nid');
1503
    $select->condition('n.status', 1);
1504
    $select->condition('n.nid', $nids, 'IN');
1505
    $select->addTag('node_access');
1506
    $nids = $select->execute()->fetchCol();
1507
    foreach ($nids as $nid) {
1508
      foreach ($node_links[$nid] as $mlid => $link) {
1509
        $node_links[$nid][$mlid]['access'] = TRUE;
1510
      }
1511
    }
1512
  }
1513
  _menu_tree_check_access($tree);
1514
}
1515

    
1516
/**
1517
 * Sorts the menu tree and recursively checks access for each item.
1518
 */
1519
function _menu_tree_check_access(&$tree) {
1520
  $new_tree = array();
1521
  foreach ($tree as $key => $v) {
1522
    $item = &$tree[$key]['link'];
1523
    _menu_link_translate($item);
1524
    if ($item['access'] || ($item['in_active_trail'] && strpos($item['href'], '%') !== FALSE)) {
1525
      if ($tree[$key]['below']) {
1526
        _menu_tree_check_access($tree[$key]['below']);
1527
      }
1528
      // The weights are made a uniform 5 digits by adding 50000 as an offset.
1529
      // After _menu_link_translate(), $item['title'] has the localized link title.
1530
      // Adding the mlid to the end of the index insures that it is unique.
1531
      $new_tree[(50000 + $item['weight']) . ' ' . $item['title'] . ' ' . $item['mlid']] = $tree[$key];
1532
    }
1533
  }
1534
  // Sort siblings in the tree based on the weights and localized titles.
1535
  ksort($new_tree);
1536
  $tree = $new_tree;
1537
}
1538

    
1539
/**
1540
 * Sorts and returns the built data representing a menu tree.
1541
 *
1542
 * @param $links
1543
 *   A flat array of menu links that are part of the menu. Each array element
1544
 *   is an associative array of information about the menu link, containing the
1545
 *   fields from the {menu_links} table, and optionally additional information
1546
 *   from the {menu_router} table, if the menu item appears in both tables.
1547
 *   This array must be ordered depth-first. See _menu_build_tree() for a sample
1548
 *   query.
1549
 * @param $parents
1550
 *   An array of the menu link ID values that are in the path from the current
1551
 *   page to the root of the menu tree.
1552
 * @param $depth
1553
 *   The minimum depth to include in the returned menu tree.
1554
 *
1555
 * @return
1556
 *   An array of menu links in the form of a tree. Each item in the tree is an
1557
 *   associative array containing:
1558
 *   - link: The menu link item from $links, with additional element
1559
 *     'in_active_trail' (TRUE if the link ID was in $parents).
1560
 *   - below: An array containing the sub-tree of this item, where each element
1561
 *     is a tree item array with 'link' and 'below' elements. This array will be
1562
 *     empty if the menu item has no items in its sub-tree having a depth
1563
 *     greater than or equal to $depth.
1564
 */
1565
function menu_tree_data(array $links, array $parents = array(), $depth = 1) {
1566
  // Reverse the array so we can use the more efficient array_pop() function.
1567
  $links = array_reverse($links);
1568
  return _menu_tree_data($links, $parents, $depth);
1569
}
1570

    
1571
/**
1572
 * Builds the data representing a menu tree.
1573
 *
1574
 * The function is a bit complex because the rendering of a link depends on
1575
 * the next menu link.
1576
 */
1577
function _menu_tree_data(&$links, $parents, $depth) {
1578
  $tree = array();
1579
  while ($item = array_pop($links)) {
1580
    // We need to determine if we're on the path to root so we can later build
1581
    // the correct active trail and breadcrumb.
1582
    $item['in_active_trail'] = in_array($item['mlid'], $parents);
1583
    // Add the current link to the tree.
1584
    $tree[$item['mlid']] = array(
1585
      'link' => $item,
1586
      'below' => array(),
1587
    );
1588
    // Look ahead to the next link, but leave it on the array so it's available
1589
    // to other recursive function calls if we return or build a sub-tree.
1590
    $next = end($links);
1591
    // Check whether the next link is the first in a new sub-tree.
1592
    if ($next && $next['depth'] > $depth) {
1593
      // Recursively call _menu_tree_data to build the sub-tree.
1594
      $tree[$item['mlid']]['below'] = _menu_tree_data($links, $parents, $next['depth']);
1595
      // Fetch next link after filling the sub-tree.
1596
      $next = end($links);
1597
    }
1598
    // Determine if we should exit the loop and return.
1599
    if (!$next || $next['depth'] < $depth) {
1600
      break;
1601
    }
1602
  }
1603
  return $tree;
1604
}
1605

    
1606
/**
1607
 * Implements template_preprocess_HOOK() for theme_menu_tree().
1608
 */
1609
function template_preprocess_menu_tree(&$variables) {
1610
  $variables['#tree'] = $variables['tree'];
1611
  $variables['tree'] = $variables['tree']['#children'];
1612
}
1613

    
1614
/**
1615
 * Returns HTML for a wrapper for a menu sub-tree.
1616
 *
1617
 * @param $variables
1618
 *   An associative array containing:
1619
 *   - tree: An HTML string containing the tree's items.
1620
 *
1621
 * @see template_preprocess_menu_tree()
1622
 * @ingroup themeable
1623
 */
1624
function theme_menu_tree($variables) {
1625
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
1626
}
1627

    
1628
/**
1629
 * Returns HTML for a menu link and submenu.
1630
 *
1631
 * @param $variables
1632
 *   An associative array containing:
1633
 *   - element: Structured array data for a menu link.
1634
 *
1635
 * @ingroup themeable
1636
 */
1637
function theme_menu_link(array $variables) {
1638
  $element = $variables['element'];
1639
  $sub_menu = '';
1640

    
1641
  if ($element['#below']) {
1642
    $sub_menu = drupal_render($element['#below']);
1643
  }
1644
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
1645
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
1646
}
1647

    
1648
/**
1649
 * Returns HTML for a single local task link.
1650
 *
1651
 * @param $variables
1652
 *   An associative array containing:
1653
 *   - element: A render element containing:
1654
 *     - #link: A menu link array with 'title', 'href', and 'localized_options'
1655
 *       keys.
1656
 *     - #active: A boolean indicating whether the local task is active.
1657
 *
1658
 * @ingroup themeable
1659
 */
1660
function theme_menu_local_task($variables) {
1661
  $link = $variables['element']['#link'];
1662
  $link_text = $link['title'];
1663

    
1664
  if (!empty($variables['element']['#active'])) {
1665
    // Add text to indicate active tab for non-visual users.
1666
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';
1667

    
1668
    // If the link does not contain HTML already, check_plain() it now.
1669
    // After we set 'html'=TRUE the link will not be sanitized by l().
1670
    if (empty($link['localized_options']['html'])) {
1671
      $link['title'] = check_plain($link['title']);
1672
    }
1673
    $link['localized_options']['html'] = TRUE;
1674
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
1675
  }
1676

    
1677
  return '<li' . (!empty($variables['element']['#active']) ? ' class="active"' : '') . '>' . l($link_text, $link['href'], $link['localized_options']) . "</li>\n";
1678
}
1679

    
1680
/**
1681
 * Returns HTML for a single local action link.
1682
 *
1683
 * @param $variables
1684
 *   An associative array containing:
1685
 *   - element: A render element containing:
1686
 *     - #link: A menu link array with 'title', 'href', and 'localized_options'
1687
 *       keys.
1688
 *
1689
 * @ingroup themeable
1690
 */
1691
function theme_menu_local_action($variables) {
1692
  $link = $variables['element']['#link'];
1693

    
1694
  $output = '<li>';
1695
  if (isset($link['href'])) {
1696
    $output .= l($link['title'], $link['href'], isset($link['localized_options']) ? $link['localized_options'] : array());
1697
  }
1698
  elseif (!empty($link['localized_options']['html'])) {
1699
    $output .= $link['title'];
1700
  }
1701
  else {
1702
    $output .= check_plain($link['title']);
1703
  }
1704
  $output .= "</li>\n";
1705

    
1706
  return $output;
1707
}
1708

    
1709
/**
1710
 * Generates elements for the $arg array in the help hook.
1711
 */
1712
function drupal_help_arg($arg = array()) {
1713
  // Note - the number of empty elements should be > MENU_MAX_PARTS.
1714
  return $arg + array('', '', '', '', '', '', '', '', '', '', '', '');
1715
}
1716

    
1717
/**
1718
 * Returns the help associated with the active menu item.
1719
 */
1720
function menu_get_active_help() {
1721
  $output = '';
1722
  $router_path = menu_tab_root_path();
1723
  // We will always have a path unless we are on a 403 or 404.
1724
  if (!$router_path) {
1725
    return '';
1726
  }
1727

    
1728
  $arg = drupal_help_arg(arg(NULL));
1729

    
1730
  foreach (module_implements('help') as $module) {
1731
    $function = $module . '_help';
1732
    // Lookup help for this path.
1733
    if ($help = $function($router_path, $arg)) {
1734
      $output .= $help . "\n";
1735
    }
1736
  }
1737
  return $output;
1738
}
1739

    
1740
/**
1741
 * Gets the custom theme for the current page, if there is one.
1742
 *
1743
 * @param $initialize
1744
 *   This parameter should only be used internally; it is set to TRUE in order
1745
 *   to force the custom theme to be initialized for the current page request.
1746
 *
1747
 * @return
1748
 *   The machine-readable name of the custom theme, if there is one.
1749
 *
1750
 * @see menu_set_custom_theme()
1751
 */
1752
function menu_get_custom_theme($initialize = FALSE) {
1753
  $custom_theme = &drupal_static(__FUNCTION__);
1754
  // Skip this if the site is offline or being installed or updated, since the
1755
  // menu system may not be correctly initialized then.
1756
  if ($initialize && !_menu_site_is_offline(TRUE) && (!defined('MAINTENANCE_MODE') || (MAINTENANCE_MODE != 'update' && MAINTENANCE_MODE != 'install'))) {
1757
    // First allow modules to dynamically set a custom theme for the current
1758
    // page. Since we can only have one, the last module to return a valid
1759
    // theme takes precedence.
1760
    $custom_themes = array_filter(module_invoke_all('custom_theme'), 'drupal_theme_access');
1761
    if (!empty($custom_themes)) {
1762
      $custom_theme = array_pop($custom_themes);
1763
    }
1764
    // If there is a theme callback function for the current page, execute it.
1765
    // If this returns a valid theme, it will override any theme that was set
1766
    // by a hook_custom_theme() implementation above.
1767
    $router_item = menu_get_item();
1768
    if (!empty($router_item['access']) && !empty($router_item['theme_callback']) && function_exists($router_item['theme_callback'])) {
1769
      $theme_name = call_user_func_array($router_item['theme_callback'], $router_item['theme_arguments']);
1770
      if (drupal_theme_access($theme_name)) {
1771
        $custom_theme = $theme_name;
1772
      }
1773
    }
1774
  }
1775
  return $custom_theme;
1776
}
1777

    
1778
/**
1779
 * Sets a custom theme for the current page, if there is one.
1780
 */
1781
function menu_set_custom_theme() {
1782
  menu_get_custom_theme(TRUE);
1783
}
1784

    
1785
/**
1786
 * Build a list of named menus.
1787
 */
1788
function menu_get_names() {
1789
  $names = &drupal_static(__FUNCTION__);
1790

    
1791
  if (empty($names)) {
1792
    $names = db_select('menu_links')
1793
      ->distinct()
1794
      ->fields('menu_links', array('menu_name'))
1795
      ->orderBy('menu_name')
1796
      ->execute()->fetchCol();
1797
  }
1798
  return $names;
1799
}
1800

    
1801
/**
1802
 * Returns an array containing the names of system-defined (default) menus.
1803
 */
1804
function menu_list_system_menus() {
1805
  return array(
1806
    'navigation' => 'Navigation',
1807
    'management' => 'Management',
1808
    'user-menu' => 'User menu',
1809
    'main-menu' => 'Main menu',
1810
  );
1811
}
1812

    
1813
/**
1814
 * Returns an array of links to be rendered as the Main menu.
1815
 */
1816
function menu_main_menu() {
1817
  return menu_navigation_links(variable_get('menu_main_links_source', 'main-menu'));
1818
}
1819

    
1820
/**
1821
 * Returns an array of links to be rendered as the Secondary links.
1822
 */
1823
function menu_secondary_menu() {
1824

    
1825
  // If the secondary menu source is set as the primary menu, we display the
1826
  // second level of the primary menu.
1827
  if (variable_get('menu_secondary_links_source', 'user-menu') == variable_get('menu_main_links_source', 'main-menu')) {
1828
    return menu_navigation_links(variable_get('menu_main_links_source', 'main-menu'), 1);
1829
  }
1830
  else {
1831
    return menu_navigation_links(variable_get('menu_secondary_links_source', 'user-menu'), 0);
1832
  }
1833
}
1834

    
1835
/**
1836
 * Returns an array of links for a navigation menu.
1837
 *
1838
 * @param $menu_name
1839
 *   The name of the menu.
1840
 * @param $level
1841
 *   Optional, the depth of the menu to be returned.
1842
 *
1843
 * @return
1844
 *   An array of links of the specified menu and level.
1845
 */
1846
function menu_navigation_links($menu_name, $level = 0) {
1847
  // Don't even bother querying the menu table if no menu is specified.
1848
  if (empty($menu_name)) {
1849
    return array();
1850
  }
1851

    
1852
  // Get the menu hierarchy for the current page.
1853
  $tree = menu_tree_page_data($menu_name, $level + 1);
1854

    
1855
  // Go down the active trail until the right level is reached.
1856
  while ($level-- > 0 && $tree) {
1857
    // Loop through the current level's items until we find one that is in trail.
1858
    while ($item = array_shift($tree)) {
1859
      if ($item['link']['in_active_trail']) {
1860
        // If the item is in the active trail, we continue in the subtree.
1861
        $tree = empty($item['below']) ? array() : $item['below'];
1862
        break;
1863
      }
1864
    }
1865
  }
1866

    
1867
  // Create a single level of links.
1868
  $router_item = menu_get_item();
1869
  $links = array();
1870
  foreach ($tree as $item) {
1871
    if (!$item['link']['hidden']) {
1872
      $class = '';
1873
      $l = $item['link']['localized_options'];
1874
      $l['href'] = $item['link']['href'];
1875
      $l['title'] = $item['link']['title'];
1876
      if ($item['link']['in_active_trail']) {
1877
        $class = ' active-trail';
1878
        $l['attributes']['class'][] = 'active-trail';
1879
      }
1880
      // Normally, l() compares the href of every link with $_GET['q'] and sets
1881
      // the active class accordingly. But local tasks do not appear in menu
1882
      // trees, so if the current path is a local task, and this link is its
1883
      // tab root, then we have to set the class manually.
1884
      if ($item['link']['href'] == $router_item['tab_root_href'] && $item['link']['href'] != $_GET['q']) {
1885
        $l['attributes']['class'][] = 'active';
1886
      }
1887
      // Keyed with the unique mlid to generate classes in theme_links().
1888
      $links['menu-' . $item['link']['mlid'] . $class] = $l;
1889
    }
1890
  }
1891
  return $links;
1892
}
1893

    
1894
/**
1895
 * Collects the local tasks (tabs), action links, and the root path.
1896
 *
1897
 * @param $level
1898
 *   The level of tasks you ask for. Primary tasks are 0, secondary are 1.
1899
 *
1900
 * @return
1901
 *   An array containing
1902
 *   - tabs: Local tasks for the requested level:
1903
 *     - count: The number of local tasks.
1904
 *     - output: The themed output of local tasks.
1905
 *   - actions: Action links for the requested level:
1906
 *     - count: The number of action links.
1907
 *     - output: The themed output of action links.
1908
 *   - root_path: The router path for the current page. If the current page is
1909
 *     a default local task, then this corresponds to the parent tab.
1910
 */
1911
function menu_local_tasks($level = 0) {
1912
  $data = &drupal_static(__FUNCTION__);
1913
  $root_path = &drupal_static(__FUNCTION__ . ':root_path', '');
1914
  $empty = array(
1915
    'tabs' => array('count' => 0, 'output' => array()),
1916
    'actions' => array('count' => 0, 'output' => array()),
1917
    'root_path' => &$root_path,
1918
  );
1919

    
1920
  if (!isset($data)) {
1921
    $data = array();
1922
    // Set defaults in case there are no actions or tabs.
1923
    $actions = $empty['actions'];
1924
    $tabs = array();
1925

    
1926
    $router_item = menu_get_item();
1927

    
1928
    // If this router item points to its parent, start from the parents to
1929
    // compute tabs and actions.
1930
    if ($router_item && ($router_item['type'] & MENU_LINKS_TO_PARENT)) {
1931
      $router_item = menu_get_item($router_item['tab_parent_href']);
1932
    }
1933

    
1934
    // If we failed to fetch a router item or the current user doesn't have
1935
    // access to it, don't bother computing the tabs.
1936
    if (!$router_item || !$router_item['access']) {
1937
      return $empty;
1938
    }
1939

    
1940
    // Get all tabs (also known as local tasks) and the root page.
1941
    $cid = 'local_tasks:' . $router_item['tab_root'];
1942
    if ($cache = cache_get($cid, 'cache_menu')) {
1943
      $result = $cache->data;
1944
    }
1945
    else {
1946
      $result = db_select('menu_router', NULL, array('fetch' => PDO::FETCH_ASSOC))
1947
        ->fields('menu_router')
1948
        ->condition('tab_root', $router_item['tab_root'])
1949
        ->condition('context', MENU_CONTEXT_INLINE, '<>')
1950
        ->orderBy('weight')
1951
        ->orderBy('title')
1952
        ->execute()
1953
        ->fetchAll();
1954
      cache_set($cid, $result, 'cache_menu');
1955
    }
1956
    $map = $router_item['original_map'];
1957
    $children = array();
1958
    $tasks = array();
1959
    $root_path = $router_item['path'];
1960

    
1961
    foreach ($result as $item) {
1962
      _menu_translate($item, $map, TRUE);
1963
      if ($item['tab_parent']) {
1964
        // All tabs, but not the root page.
1965
        $children[$item['tab_parent']][$item['path']] = $item;
1966
      }
1967
      // Store the translated item for later use.
1968
      $tasks[$item['path']] = $item;
1969
    }
1970

    
1971
    // Find all tabs below the current path.
1972
    $path = $router_item['path'];
1973
    // Tab parenting may skip levels, so the number of parts in the path may not
1974
    // equal the depth. Thus we use the $depth counter (offset by 1000 for ksort).
1975
    $depth = 1001;
1976
    $actions['count'] = 0;
1977
    $actions['output'] = array();
1978
    while (isset($children[$path])) {
1979
      $tabs_current = array();
1980
      $actions_current = array();
1981
      $next_path = '';
1982
      $tab_count = 0;
1983
      $action_count = 0;
1984
      foreach ($children[$path] as $item) {
1985
        // Local tasks can be normal items too, so bitmask with
1986
        // MENU_IS_LOCAL_TASK before checking.
1987
        if (!($item['type'] & MENU_IS_LOCAL_TASK)) {
1988
          // This item is not a tab, skip it.
1989
          continue;
1990
        }
1991
        if ($item['access']) {
1992
          $link = $item;
1993
          // The default task is always active. As tabs can be normal items
1994
          // too, so bitmask with MENU_LINKS_TO_PARENT before checking.
1995
          if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
1996
            // Find the first parent which is not a default local task or action.
1997
            for ($p = $item['tab_parent']; ($tasks[$p]['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT; $p = $tasks[$p]['tab_parent']);
1998
            // Use the path of the parent instead.
1999
            $link['href'] = $tasks[$p]['href'];
2000
            // Mark the link as active, if the current path happens to be the
2001
            // path of the default local task itself (i.e., instead of its
2002
            // tab_parent_href or tab_root_href). Normally, links for default
2003
            // local tasks link to their parent, but the path of default local
2004
            // tasks can still be accessed directly, in which case this link
2005
            // would not be marked as active, since l() only compares the href
2006
            // with $_GET['q'].
2007
            if ($link['href'] != $_GET['q']) {
2008
              $link['localized_options']['attributes']['class'][] = 'active';
2009
            }
2010
            $tabs_current[] = array(
2011
              '#theme' => 'menu_local_task',
2012
              '#link' => $link,
2013
              '#active' => TRUE,
2014
            );
2015
            $next_path = $item['path'];
2016
            $tab_count++;
2017
          }
2018
          else {
2019
            // Actions can be normal items too, so bitmask with
2020
            // MENU_IS_LOCAL_ACTION before checking.
2021
            if (($item['type'] & MENU_IS_LOCAL_ACTION) == MENU_IS_LOCAL_ACTION) {
2022
              // The item is an action, display it as such.
2023
              $actions_current[] = array(
2024
                '#theme' => 'menu_local_action',
2025
                '#link' => $link,
2026
              );
2027
              $action_count++;
2028
            }
2029
            else {
2030
              // Otherwise, it's a normal tab.
2031
              $tabs_current[] = array(
2032
                '#theme' => 'menu_local_task',
2033
                '#link' => $link,
2034
              );
2035
              $tab_count++;
2036
            }
2037
          }
2038
        }
2039
      }
2040
      $path = $next_path;
2041
      $tabs[$depth]['count'] = $tab_count;
2042
      $tabs[$depth]['output'] = $tabs_current;
2043
      $actions['count'] += $action_count;
2044
      $actions['output'] = array_merge($actions['output'], $actions_current);
2045
      $depth++;
2046
    }
2047
    $data['actions'] = $actions;
2048
    // Find all tabs at the same level or above the current one.
2049
    $parent = $router_item['tab_parent'];
2050
    $path = $router_item['path'];
2051
    $current = $router_item;
2052
    $depth = 1000;
2053
    while (isset($children[$parent])) {
2054
      $tabs_current = array();
2055
      $next_path = '';
2056
      $next_parent = '';
2057
      $count = 0;
2058
      foreach ($children[$parent] as $item) {
2059
        // Skip local actions.
2060
        if ($item['type'] & MENU_IS_LOCAL_ACTION) {
2061
          continue;
2062
        }
2063
        if ($item['access']) {
2064
          $count++;
2065
          $link = $item;
2066
          // Local tasks can be normal items too, so bitmask with
2067
          // MENU_LINKS_TO_PARENT before checking.
2068
          if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
2069
            // Find the first parent which is not a default local task.
2070
            for ($p = $item['tab_parent']; ($tasks[$p]['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT; $p = $tasks[$p]['tab_parent']);
2071
            // Use the path of the parent instead.
2072
            $link['href'] = $tasks[$p]['href'];
2073
            if ($item['path'] == $router_item['path']) {
2074
              $root_path = $tasks[$p]['path'];
2075
            }
2076
          }
2077
          // We check for the active tab.
2078
          if ($item['path'] == $path) {
2079
            // Mark the link as active, if the current path is a (second-level)
2080
            // local task of a default local task. Since this default local task
2081
            // links to its parent, l() will not mark it as active, as it only
2082
            // compares the link's href to $_GET['q'].
2083
            if ($link['href'] != $_GET['q']) {
2084
              $link['localized_options']['attributes']['class'][] = 'active';
2085
            }
2086
            $tabs_current[] = array(
2087
              '#theme' => 'menu_local_task',
2088
              '#link' => $link,
2089
              '#active' => TRUE,
2090
            );
2091
            $next_path = $item['tab_parent'];
2092
            if (isset($tasks[$next_path])) {
2093
              $next_parent = $tasks[$next_path]['tab_parent'];
2094
            }
2095
          }
2096
          else {
2097
            $tabs_current[] = array(
2098
              '#theme' => 'menu_local_task',
2099
              '#link' => $link,
2100
            );
2101
          }
2102
        }
2103
      }
2104
      $path = $next_path;
2105
      $parent = $next_parent;
2106
      $tabs[$depth]['count'] = $count;
2107
      $tabs[$depth]['output'] = $tabs_current;
2108
      $depth--;
2109
    }
2110
    // Sort by depth.
2111
    ksort($tabs);
2112
    // Remove the depth, we are interested only in their relative placement.
2113
    $tabs = array_values($tabs);
2114
    $data['tabs'] = $tabs;
2115

    
2116
    // Allow modules to alter local tasks or dynamically append further tasks.
2117
    drupal_alter('menu_local_tasks', $data, $router_item, $root_path);
2118
  }
2119

    
2120
  if (isset($data['tabs'][$level])) {
2121
    return array(
2122
      'tabs' => $data['tabs'][$level],
2123
      'actions' => $data['actions'],
2124
      'root_path' => $root_path,
2125
    );
2126
  }
2127
  // @todo If there are no tabs, then there still can be actions; for example,
2128
  //   when added via hook_menu_local_tasks_alter().
2129
  elseif (!empty($data['actions']['output'])) {
2130
    return array('actions' => $data['actions']) + $empty;
2131
  }
2132
  return $empty;
2133
}
2134

    
2135
/**
2136
 * Retrieves contextual links for a path based on registered local tasks.
2137
 *
2138
 * This leverages the menu system to retrieve the first layer of registered
2139
 * local tasks for a given system path. All local tasks of the tab type
2140
 * MENU_CONTEXT_INLINE are taken into account.
2141
 *
2142
 * For example, when considering the following registered local tasks:
2143
 * - node/%node/view (default local task) with no 'context' defined
2144
 * - node/%node/edit with context: MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE
2145
 * - node/%node/revisions with context: MENU_CONTEXT_PAGE
2146
 * - node/%node/report-as-spam with context: MENU_CONTEXT_INLINE
2147
 *
2148
 * If the path "node/123" is passed to this function, then it will return the
2149
 * links for 'edit' and 'report-as-spam'.
2150
 *
2151
 * @param $module
2152
 *   The name of the implementing module. This is used to prefix the key for
2153
 *   each contextual link, which is transformed into a CSS class during
2154
 *   rendering by theme_links(). For example, if $module is 'block' and the
2155
 *   retrieved local task path argument is 'edit', then the resulting CSS class
2156
 *   will be 'block-edit'.
2157
 * @param $parent_path
2158
 *   The static menu router path of the object to retrieve local tasks for, for
2159
 *   example 'node' or 'admin/structure/block/manage'.
2160
 * @param $args
2161
 *   A list of dynamic path arguments to append to $parent_path to form the
2162
 *   fully-qualified menu router path; for example, array(123) for a certain
2163
 *   node or array('system', 'navigation') for a certain block.
2164
 *
2165
 * @return
2166
 *   A list of menu router items that are local tasks for the passed-in path.
2167
 *
2168
 * @see contextual_links_preprocess()
2169
 * @see hook_menu()
2170
 */
2171
function menu_contextual_links($module, $parent_path, $args) {
2172
  static $path_empty = array();
2173

    
2174
  $links = array();
2175
  // Performance: In case a previous invocation for the same parent path did not
2176
  // return any links, we immediately return here.
2177
  if (isset($path_empty[$parent_path]) && strpos($parent_path, '%') !== FALSE) {
2178
    return $links;
2179
  }
2180
  // Construct the item-specific parent path.
2181
  $path = $parent_path . '/' . implode('/', $args);
2182

    
2183
  // Get the router item for the given parent link path.
2184
  $router_item = menu_get_item($path);
2185
  if (!$router_item || !$router_item['access']) {
2186
    $path_empty[$parent_path] = TRUE;
2187
    return $links;
2188
  }
2189
  $data = &drupal_static(__FUNCTION__, array());
2190
  $root_path = $router_item['path'];
2191

    
2192
  // Performance: For a single, normalized path (such as 'node/%') we only query
2193
  // available tasks once per request.
2194
  if (!isset($data[$root_path])) {
2195
    // Get all contextual links that are direct children of the router item and
2196
    // not of the tab type 'view'.
2197
    $data[$root_path] = db_select('menu_router', 'm')
2198
      ->fields('m')
2199
      ->condition('tab_parent', $router_item['tab_root'])
2200
      ->condition('context', MENU_CONTEXT_NONE, '<>')
2201
      ->condition('context', MENU_CONTEXT_PAGE, '<>')
2202
      ->orderBy('weight')
2203
      ->orderBy('title')
2204
      ->execute()
2205
      ->fetchAllAssoc('path', PDO::FETCH_ASSOC);
2206
  }
2207
  $parent_length = drupal_strlen($root_path) + 1;
2208
  $map = $router_item['original_map'];
2209
  foreach ($data[$root_path] as $item) {
2210
    // Extract the actual "task" string from the path argument.
2211
    $key = drupal_substr($item['path'], $parent_length);
2212

    
2213
    // Denormalize and translate the contextual link.
2214
    _menu_translate($item, $map, TRUE);
2215
    if (!$item['access']) {
2216
      continue;
2217
    }
2218
    // All contextual links are keyed by the actual "task" path argument,
2219
    // prefixed with the name of the implementing module.
2220
    $links[$module . '-' . $key] = $item;
2221
  }
2222

    
2223
  // Allow modules to alter contextual links.
2224
  drupal_alter('menu_contextual_links', $links, $router_item, $root_path);
2225

    
2226
  // Performance: If the current user does not have access to any links for this
2227
  // router path and no other module added further links, we assign FALSE here
2228
  // to skip the entire process the next time the same router path is requested.
2229
  if (empty($links)) {
2230
    $path_empty[$parent_path] = TRUE;
2231
  }
2232

    
2233
  return $links;
2234
}
2235

    
2236
/**
2237
 * Returns the rendered local tasks at the top level.
2238
 */
2239
function menu_primary_local_tasks() {
2240
  $links = menu_local_tasks(0);
2241
  // Do not display single tabs.
2242
  return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
2243
}
2244

    
2245
/**
2246
 * Returns the rendered local tasks at the second level.
2247
 */
2248
function menu_secondary_local_tasks() {
2249
  $links = menu_local_tasks(1);
2250
  // Do not display single tabs.
2251
  return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
2252
}
2253

    
2254
/**
2255
 * Returns the rendered local actions at the current level.
2256
 */
2257
function menu_local_actions() {
2258
  $links = menu_local_tasks();
2259
  return $links['actions']['output'];
2260
}
2261

    
2262
/**
2263
 * Returns the router path, or the path for a default local task's parent.
2264
 */
2265
function menu_tab_root_path() {
2266
  $links = menu_local_tasks();
2267
  return $links['root_path'];
2268
}
2269

    
2270
/**
2271
 * Returns a renderable element for the primary and secondary tabs.
2272
 */
2273
function menu_local_tabs() {
2274
  return array(
2275
    '#theme' => 'menu_local_tasks',
2276
    '#primary' => menu_primary_local_tasks(),
2277
    '#secondary' => menu_secondary_local_tasks(),
2278
  );
2279
}
2280

    
2281
/**
2282
 * Returns HTML for primary and secondary local tasks.
2283
 *
2284
 * @param $variables
2285
 *   An associative array containing:
2286
 *     - primary: (optional) An array of local tasks (tabs).
2287
 *     - secondary: (optional) An array of local tasks (tabs).
2288
 *
2289
 * @ingroup themeable
2290
 * @see menu_local_tasks()
2291
 */
2292
function theme_menu_local_tasks(&$variables) {
2293
  $output = '';
2294

    
2295
  if (!empty($variables['primary'])) {
2296
    $variables['primary']['#prefix'] = '<h2 class="element-invisible">' . t('Primary tabs') . '</h2>';
2297
    $variables['primary']['#prefix'] .= '<ul class="tabs primary">';
2298
    $variables['primary']['#suffix'] = '</ul>';
2299
    $output .= drupal_render($variables['primary']);
2300
  }
2301
  if (!empty($variables['secondary'])) {
2302
    $variables['secondary']['#prefix'] = '<h2 class="element-invisible">' . t('Secondary tabs') . '</h2>';
2303
    $variables['secondary']['#prefix'] .= '<ul class="tabs secondary">';
2304
    $variables['secondary']['#suffix'] = '</ul>';
2305
    $output .= drupal_render($variables['secondary']);
2306
  }
2307

    
2308
  return $output;
2309
}
2310

    
2311
/**
2312
 * Sets (or gets) the active menu for the current page.
2313
 *
2314
 * The active menu for the page determines the active trail.
2315
 *
2316
 * @return
2317
 *   An array of menu machine names, in order of preference. The
2318
 *   'menu_default_active_menus' variable may be used to assert a menu order
2319
 *   different from the order of creation, or to prevent a particular menu from
2320
 *   being used at all in the active trail.
2321
 *   E.g., $conf['menu_default_active_menus'] = array('navigation', 'main-menu')
2322
 */
2323
function menu_set_active_menu_names($menu_names = NULL) {
2324
  $active = &drupal_static(__FUNCTION__);
2325

    
2326
  if (isset($menu_names) && is_array($menu_names)) {
2327
    $active = $menu_names;
2328
  }
2329
  elseif (!isset($active)) {
2330
    $active = variable_get('menu_default_active_menus', array_keys(menu_list_system_menus()));
2331
  }
2332
  return $active;
2333
}
2334

    
2335
/**
2336
 * Gets the active menu for the current page.
2337
 */
2338
function menu_get_active_menu_names() {
2339
  return menu_set_active_menu_names();
2340
}
2341

    
2342
/**
2343
 * Sets the active path, which determines which page is loaded.
2344
 *
2345
 * Note that this may not have the desired effect unless invoked very early
2346
 * in the page load, such as during hook_boot(), or unless you call
2347
 * menu_execute_active_handler() to generate your page output.
2348
 *
2349
 * @param $path
2350
 *   A Drupal path - not a path alias.
2351
 */
2352
function menu_set_active_item($path) {
2353
  $_GET['q'] = $path;
2354
  // Since the active item has changed, the active menu trail may also be out
2355
  // of date.
2356
  drupal_static_reset('menu_set_active_trail');
2357
}
2358

    
2359
/**
2360
 * Sets the active trail (path to the menu tree root) of the current page.
2361
 *
2362
 * Any trail set by this function will only be used for functionality that calls
2363
 * menu_get_active_trail(). Drupal core only uses trails set here for
2364
 * breadcrumbs and the page title and not for menu trees or page content.
2365
 * Additionally, breadcrumbs set by drupal_set_breadcrumb() will override any
2366
 * trail set here.
2367
 *
2368
 * To affect the trail used by menu trees, use menu_tree_set_path(). To affect
2369
 * the page content, use menu_set_active_item() instead.
2370
 *
2371
 * @param $new_trail
2372
 *   Menu trail to set; the value is saved in a static variable and can be
2373
 *   retrieved by menu_get_active_trail(). The format of this array should be
2374
 *   the same as the return value of menu_get_active_trail().
2375
 *
2376
 * @return
2377
 *   The active trail. See menu_get_active_trail() for details.
2378
 */
2379
function menu_set_active_trail($new_trail = NULL) {
2380
  $trail = &drupal_static(__FUNCTION__);
2381

    
2382
  if (isset($new_trail)) {
2383
    $trail = $new_trail;
2384
  }
2385
  elseif (!isset($trail)) {
2386
    $trail = array();
2387
    $trail[] = array(
2388
      'title' => t('Home'),
2389
      'href' => '<front>',
2390
      'link_path' => '',
2391
      'localized_options' => array(),
2392
      'type' => 0,
2393
    );
2394

    
2395
    // Try to retrieve a menu link corresponding to the current path. If more
2396
    // than one exists, the link from the most preferred menu is returned.
2397
    $preferred_link = menu_link_get_preferred();
2398
    $current_item = menu_get_item();
2399

    
2400
    // There is a link for the current path.
2401
    if ($preferred_link) {
2402
      // Pass TRUE for $only_active_trail to make menu_tree_page_data() build
2403
      // a stripped down menu tree containing the active trail only, in case
2404
      // the given menu has not been built in this request yet.
2405
      $tree = menu_tree_page_data($preferred_link['menu_name'], NULL, TRUE);
2406
      $curr = current($tree);
2407
      next($tree);
2408
    }
2409
    // There is no link for the current path.
2410
    else {
2411
      $preferred_link = $current_item;
2412
      $curr = FALSE;
2413
    }
2414

    
2415
    while ($curr) {
2416
      $link = $curr['link'];
2417
      if ($link['in_active_trail']) {
2418
        // Add the link to the trail, unless it links to its parent.
2419
        if (!($link['type'] & MENU_LINKS_TO_PARENT)) {
2420
          // The menu tree for the active trail may contain additional links
2421
          // that have not been translated yet, since they contain dynamic
2422
          // argument placeholders (%). Such links are not contained in regular
2423
          // menu trees, and have only been loaded for the additional
2424
          // translation that happens here, so as to be able to display them in
2425
          // the breadcrumb for the current page.
2426
          // @see _menu_tree_check_access()
2427
          // @see _menu_link_translate()
2428
          if (strpos($link['href'], '%') !== FALSE) {
2429
            _menu_link_translate($link, TRUE);
2430
          }
2431
          if ($link['access']) {
2432
            $trail[] = $link;
2433
          }
2434
        }
2435
        $tree = $curr['below'] ? $curr['below'] : array();
2436
      }
2437
      $curr = current($tree);
2438
      next($tree);
2439
    }
2440
    // Make sure the current page is in the trail to build the page title, by
2441
    // appending either the preferred link or the menu router item for the
2442
    // current page. Exclude it if we are on the front page.
2443
    $last = end($trail);
2444
    if ($preferred_link && $last['href'] != $preferred_link['href'] && !drupal_is_front_page()) {
2445
      $trail[] = $preferred_link;
2446
    }
2447
  }
2448
  return $trail;
2449
}
2450

    
2451
/**
2452
 * Looks up the preferred menu link for a given system path.
2453
 *
2454
 * @param $path
2455
 *   The path; for example, 'node/5'. The function will find the corresponding
2456
 *   menu link ('node/5' if it exists, or fallback to 'node/%').
2457
 * @param $selected_menu
2458
 *   The name of a menu used to restrict the search for a preferred menu link.
2459
 *   If not specified, all the menus returned by menu_get_active_menu_names()
2460
 *   will be used.
2461
 *
2462
 * @return
2463
 *   A fully translated menu link, or FALSE if no matching menu link was
2464
 *   found. The most specific menu link ('node/5' preferred over 'node/%') in
2465
 *   the most preferred menu (as defined by menu_get_active_menu_names()) is
2466
 *   returned.
2467
 */
2468
function menu_link_get_preferred($path = NULL, $selected_menu = NULL) {
2469
  $preferred_links = &drupal_static(__FUNCTION__);
2470

    
2471
  if (!isset($path)) {
2472
    $path = $_GET['q'];
2473
  }
2474

    
2475
  if (empty($selected_menu)) {
2476
    // Use an illegal menu name as the key for the preferred menu link.
2477
    $selected_menu = MENU_PREFERRED_LINK;
2478
  }
2479

    
2480
  if (!isset($preferred_links[$path])) {
2481
    // Look for the correct menu link by building a list of candidate paths,
2482
    // which are ordered by priority (translated hrefs are preferred over
2483
    // untranslated paths). Afterwards, the most relevant path is picked from
2484
    // the menus, ordered by menu preference.
2485
    $item = menu_get_item($path);
2486
    if ($item === FALSE) {
2487
      return FALSE;
2488
    }
2489
    $path_candidates = array();
2490
    // 1. The current item href.
2491
    $path_candidates[$item['href']] = $item['href'];
2492
    // 2. The tab root href of the current item (if any).
2493
    if ($item['tab_parent'] && ($tab_root = menu_get_item($item['tab_root_href']))) {
2494
      $path_candidates[$tab_root['href']] = $tab_root['href'];
2495
    }
2496
    // 3. The current item path (with wildcards).
2497
    $path_candidates[$item['path']] = $item['path'];
2498
    // 4. The tab root path of the current item (if any).
2499
    if (!empty($tab_root)) {
2500
      $path_candidates[$tab_root['path']] = $tab_root['path'];
2501
    }
2502

    
2503
    // Retrieve a list of menu names, ordered by preference.
2504
    $menu_names = menu_get_active_menu_names();
2505
    // Put the selected menu at the front of the list.
2506
    array_unshift($menu_names, $selected_menu);
2507

    
2508
    $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
2509
    $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
2510
    $query->fields('ml');
2511
    // Weight must be taken from {menu_links}, not {menu_router}.
2512
    $query->addField('ml', 'weight', 'link_weight');
2513
    $query->fields('m');
2514
    $query->condition('ml.link_path', $path_candidates, 'IN');
2515
    $query->addTag('preferred_menu_links');
2516

    
2517
    // Sort candidates by link path and menu name.
2518
    $candidates = array();
2519
    foreach ($query->execute() as $candidate) {
2520
      $candidate['weight'] = $candidate['link_weight'];
2521
      $candidates[$candidate['link_path']][$candidate['menu_name']] = $candidate;
2522
      // Add any menus not already in the menu name search list.
2523
      if (!in_array($candidate['menu_name'], $menu_names)) {
2524
        $menu_names[] = $candidate['menu_name'];
2525
      }
2526
    }
2527

    
2528
    // Store the most specific link for each menu. Also save the most specific
2529
    // link of the most preferred menu in $preferred_link.
2530
    foreach ($path_candidates as $link_path) {
2531
      if (isset($candidates[$link_path])) {
2532
        foreach ($menu_names as $menu_name) {
2533
          if (empty($preferred_links[$path][$menu_name]) && isset($candidates[$link_path][$menu_name])) {
2534
            $candidate_item = $candidates[$link_path][$menu_name];
2535
            $map = explode('/', $path);
2536
            _menu_translate($candidate_item, $map);
2537
            if ($candidate_item['access']) {
2538
              $preferred_links[$path][$menu_name] = $candidate_item;
2539
              if (empty($preferred_links[$path][MENU_PREFERRED_LINK])) {
2540
                // Store the most specific link.
2541
                $preferred_links[$path][MENU_PREFERRED_LINK] = $candidate_item;
2542
              }
2543
            }
2544
          }
2545
        }
2546
      }
2547
    }
2548
  }
2549

    
2550
  return isset($preferred_links[$path][$selected_menu]) ? $preferred_links[$path][$selected_menu] : FALSE;
2551
}
2552

    
2553
/**
2554
 * Gets the active trail (path to root menu root) of the current page.
2555
 *
2556
 * If a trail is supplied to menu_set_active_trail(), that value is returned. If
2557
 * a trail is not supplied to menu_set_active_trail(), the path to the current
2558
 * page is calculated and returned. The calculated trail is also saved as a
2559
 * static value for use by subsequent calls to menu_get_active_trail().
2560
 *
2561
 * @return
2562
 *   Path to menu root of the current page, as an array of menu link items,
2563
 *   starting with the site's home page. Each link item is an associative array
2564
 *   with the following components:
2565
 *   - title: Title of the item.
2566
 *   - href: Drupal path of the item.
2567
 *   - localized_options: Options for passing into the l() function.
2568
 *   - type: A menu type constant, such as MENU_DEFAULT_LOCAL_TASK, or 0 to
2569
 *     indicate it's not really in the menu (used for the home page item).
2570
 */
2571
function menu_get_active_trail() {
2572
  return menu_set_active_trail();
2573
}
2574

    
2575
/**
2576
 * Gets the breadcrumb for the current page, as determined by the active trail.
2577
 *
2578
 * @see menu_set_active_trail()
2579
 */
2580
function menu_get_active_breadcrumb() {
2581
  $breadcrumb = array();
2582

    
2583
  // No breadcrumb for the front page.
2584
  if (drupal_is_front_page()) {
2585
    return $breadcrumb;
2586
  }
2587

    
2588
  $item = menu_get_item();
2589
  if (!empty($item['access'])) {
2590
    $active_trail = menu_get_active_trail();
2591

    
2592
    // Allow modules to alter the breadcrumb, if possible, as that is much
2593
    // faster than rebuilding an entirely new active trail.
2594
    drupal_alter('menu_breadcrumb', $active_trail, $item);
2595

    
2596
    // Don't show a link to the current page in the breadcrumb trail.
2597
    $end = end($active_trail);
2598
    if ($item['href'] == $end['href']) {
2599
      array_pop($active_trail);
2600
    }
2601

    
2602
    // Remove the tab root (parent) if the current path links to its parent.
2603
    // Normally, the tab root link is included in the breadcrumb, as soon as we
2604
    // are on a local task or any other child link. However, if we are on a
2605
    // default local task (e.g., node/%/view), then we do not want the tab root
2606
    // link (e.g., node/%) to appear, as it would be identical to the current
2607
    // page. Since this behavior also needs to work recursively (i.e., on
2608
    // default local tasks of default local tasks), and since the last non-task
2609
    // link in the trail is used as page title (see menu_get_active_title()),
2610
    // this condition cannot be cleanly integrated into menu_get_active_trail().
2611
    // menu_get_active_trail() already skips all links that link to their parent
2612
    // (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
2613
    // itself, we always remove the last link in the trail, if the current
2614
    // router item links to its parent.
2615
    if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
2616
      array_pop($active_trail);
2617
    }
2618

    
2619
    foreach ($active_trail as $parent) {
2620
      $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
2621
    }
2622
  }
2623
  return $breadcrumb;
2624
}
2625

    
2626
/**
2627
 * Gets the title of the current page, as determined by the active trail.
2628
 */
2629
function menu_get_active_title() {
2630
  $active_trail = menu_get_active_trail();
2631
  $local_task_title = NULL;
2632

    
2633
  foreach (array_reverse($active_trail) as $item) {
2634
    // Local task titles are displayed as tabs and therefore should not be
2635
    // repeated as the page title. However, if the local task appears in a
2636
    // top-level menu, it is no longer a "local task" anymore (the front page
2637
    // of the site does not have tabs) so it is better to use the local task
2638
    // title in that case than to fall back on the front page link in the
2639
    // active trail (which is usually "Home" and would not make sense in this
2640
    // context).
2641
    if ((bool) ($item['type'] & MENU_IS_LOCAL_TASK)) {
2642
      // A local task title is being skipped; track it in case it needs to be
2643
      // used later.
2644
      $local_task_title = $item['title'];
2645
    }
2646
    else {
2647
      // This is not a local task, so use it for the page title (unless the
2648
      // conditions described above are met).
2649
      if (isset($local_task_title) && isset($item['href']) && $item['href'] == '<front>') {
2650
        return $local_task_title;
2651
      }
2652
      else {
2653
        return $item['title'];
2654
      }
2655
    }
2656
  }
2657
}
2658

    
2659
/**
2660
 * Gets a translated, access-checked menu link that is ready for rendering.
2661
 *
2662
 * This function should never be called from within node_load() or any other
2663
 * function used as a menu object load function since an infinite recursion may
2664
 * occur.
2665
 *
2666
 * @param $mlid
2667
 *   The mlid of the menu item.
2668
 *
2669
 * @return
2670
 *   A menu link, with $item['access'] filled and link translated for
2671
 *   rendering.
2672
 */
2673
function menu_link_load($mlid) {
2674
  if (is_numeric($mlid)) {
2675
    $query = db_select('menu_links', 'ml');
2676
    $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
2677
    $query->fields('ml');
2678
    // Weight should be taken from {menu_links}, not {menu_router}.
2679
    $query->addField('ml', 'weight', 'link_weight');
2680
    $query->fields('m');
2681
    $query->condition('ml.mlid', $mlid);
2682
    if ($item = $query->execute()->fetchAssoc()) {
2683
      $item['weight'] = $item['link_weight'];
2684
      _menu_link_translate($item);
2685
      return $item;
2686
    }
2687
  }
2688
  return FALSE;
2689
}
2690

    
2691
/**
2692
 * Clears the cached data for a single named menu.
2693
 */
2694
function menu_cache_clear($menu_name = 'navigation') {
2695
  $cache_cleared = &drupal_static(__FUNCTION__, array());
2696

    
2697
  if (empty($cache_cleared[$menu_name])) {
2698
    cache_clear_all('links:' . $menu_name . ':', 'cache_menu', TRUE);
2699
    $cache_cleared[$menu_name] = 1;
2700
  }
2701
  elseif ($cache_cleared[$menu_name] == 1) {
2702
    drupal_register_shutdown_function('cache_clear_all', 'links:' . $menu_name . ':', 'cache_menu', TRUE);
2703
    $cache_cleared[$menu_name] = 2;
2704
  }
2705

    
2706
  // Also clear the menu system static caches.
2707
  menu_reset_static_cache();
2708
}
2709

    
2710
/**
2711
 * Clears all cached menu data.
2712
 *
2713
 * This should be called any time broad changes
2714
 * might have been made to the router items or menu links.
2715
 */
2716
function menu_cache_clear_all() {
2717
  cache_clear_all('*', 'cache_menu', TRUE);
2718
  menu_reset_static_cache();
2719
}
2720

    
2721
/**
2722
 * Resets the menu system static cache.
2723
 */
2724
function menu_reset_static_cache() {
2725
  drupal_static_reset('_menu_build_tree');
2726
  drupal_static_reset('menu_tree');
2727
  drupal_static_reset('menu_tree_all_data');
2728
  drupal_static_reset('menu_tree_page_data');
2729
  drupal_static_reset('menu_load_all');
2730
  drupal_static_reset('menu_link_get_preferred');
2731
}
2732

    
2733
/**
2734
 * Checks whether a menu_rebuild() is necessary.
2735
 */
2736
function _menu_check_rebuild() {
2737
  // To absolutely ensure that the menu rebuild is required, re-load the
2738
  // variables in case they were set by another process.
2739
  $variables = variable_initialize();
2740
  if (empty($variables['menu_rebuild_needed']) && !empty($variables['menu_masks'])) {
2741
    unset($GLOBALS['conf']['menu_rebuild_needed']);
2742
    $GLOBALS['conf']['menu_masks'] = $variables['menu_masks'];
2743
    return FALSE;
2744
  }
2745
  return TRUE;
2746
}
2747

    
2748
/**
2749
 * Populates the database tables used by various menu functions.
2750
 *
2751
 * This function will clear and populate the {menu_router} table, add entries
2752
 * to {menu_links} for new router items, and then remove stale items from
2753
 * {menu_links}. If called from update.php or install.php, it will also
2754
 * schedule a call to itself on the first real page load from
2755
 * menu_execute_active_handler(), because the maintenance page environment
2756
 * is different and leaves stale data in the menu tables.
2757
 *
2758
 * @return
2759
 *   TRUE if the menu was rebuilt, FALSE if another thread was rebuilding
2760
 *   in parallel and the current thread just waited for completion.
2761
 */
2762
function menu_rebuild() {
2763
  if (!lock_acquire('menu_rebuild')) {
2764
    // Wait for another request that is already doing this work.
2765
    // We choose to block here since otherwise the router item may not
2766
    // be available in menu_execute_active_handler() resulting in a 404.
2767
    lock_wait('menu_rebuild');
2768

    
2769
    if (_menu_check_rebuild()) {
2770
      // If we get here and menu_masks was not set, then it is possible a menu
2771
      // is being reloaded, or that the process rebuilding the menu was unable
2772
      // to complete successfully. A missing menu_masks variable could result
2773
      // in a 404, so re-run the function.
2774
      return menu_rebuild();
2775
    }
2776
    return FALSE;
2777
  }
2778

    
2779
  $transaction = db_transaction();
2780

    
2781
  try {
2782
    list($menu, $masks) = menu_router_build();
2783
    _menu_router_save($menu, $masks);
2784
    _menu_navigation_links_rebuild($menu);
2785
    // Clear the menu, page and block caches.
2786
    menu_cache_clear_all();
2787
    _menu_clear_page_cache();
2788

    
2789
    if (defined('MAINTENANCE_MODE')) {
2790
      variable_set('menu_rebuild_needed', TRUE);
2791
    }
2792
    else {
2793
      variable_del('menu_rebuild_needed');
2794
    }
2795
  }
2796
  catch (Exception $e) {
2797
    $transaction->rollback();
2798
    watchdog_exception('menu', $e);
2799
  }
2800
  // Explicitly commit the transaction now; this ensures that the database
2801
  // operations during the menu rebuild are committed before the lock is made
2802
  // available again, since locks may not always reside in the same database
2803
  // connection. The lock is acquired outside of the transaction so should also
2804
  // be released outside of it.
2805
  unset($transaction);
2806

    
2807
  lock_release('menu_rebuild');
2808
  return TRUE;
2809
}
2810

    
2811
/**
2812
 * Collects and alters the menu definitions.
2813
 */
2814
function menu_router_build() {
2815
  // We need to manually call each module so that we can know which module
2816
  // a given item came from.
2817
  $callbacks = array();
2818
  foreach (module_implements('menu') as $module) {
2819
    $router_items = call_user_func($module . '_menu');
2820
    if (isset($router_items) && is_array($router_items)) {
2821
      foreach (array_keys($router_items) as $path) {
2822
        $router_items[$path]['module'] = $module;
2823
      }
2824
      $callbacks = array_merge($callbacks, $router_items);
2825
    }
2826
  }
2827
  // Alter the menu as defined in modules, keys are like user/%user.
2828
  drupal_alter('menu', $callbacks);
2829
  list($menu, $masks) = _menu_router_build($callbacks);
2830
  _menu_router_cache($menu);
2831

    
2832
  return array($menu, $masks);
2833
}
2834

    
2835
/**
2836
 * Stores the menu router if we have it in memory.
2837
 */
2838
function _menu_router_cache($new_menu = NULL) {
2839
  $menu = &drupal_static(__FUNCTION__);
2840

    
2841
  if (isset($new_menu)) {
2842
    $menu = $new_menu;
2843
  }
2844
  return $menu;
2845
}
2846

    
2847
/**
2848
 * Gets the menu router.
2849
 */
2850
function menu_get_router() {
2851
  // Check first if we have it in memory already.
2852
  $menu = _menu_router_cache();
2853
  if (empty($menu)) {
2854
    list($menu, $masks) = menu_router_build();
2855
  }
2856
  return $menu;
2857
}
2858

    
2859
/**
2860
 * Builds a link from a router item.
2861
 */
2862
function _menu_link_build($item) {
2863
  // Suggested items are disabled by default.
2864
  if ($item['type'] == MENU_SUGGESTED_ITEM) {
2865
    $item['hidden'] = 1;
2866
  }
2867
  // Hide all items that are not visible in the tree.
2868
  elseif (!($item['type'] & MENU_VISIBLE_IN_TREE)) {
2869
    $item['hidden'] = -1;
2870
  }
2871
  // Note, we set this as 'system', so that we can be sure to distinguish all
2872
  // the menu links generated automatically from entries in {menu_router}.
2873
  $item['module'] = 'system';
2874
  $item += array(
2875
    'menu_name' => 'navigation',
2876
    'link_title' => $item['title'],
2877
    'link_path' => $item['path'],
2878
    'hidden' => 0,
2879
    'options' => empty($item['description']) ? array() : array('attributes' => array('title' => $item['description'])),
2880
  );
2881
  return $item;
2882
}
2883

    
2884
/**
2885
 * Builds menu links for the items in the menu router.
2886
 */
2887
function _menu_navigation_links_rebuild($menu) {
2888
  // Add normal and suggested items as links.
2889
  $menu_links = array();
2890
  foreach ($menu as $path => $item) {
2891
    if ($item['_visible']) {
2892
      $menu_links[$path] = $item;
2893
      $sort[$path] = $item['_number_parts'];
2894
    }
2895
  }
2896
  if ($menu_links) {
2897
    // Keep an array of processed menu links, to allow menu_link_save() to
2898
    // check this for parents instead of querying the database.
2899
    $parent_candidates = array();
2900
    // Make sure no child comes before its parent.
2901
    array_multisort($sort, SORT_NUMERIC, $menu_links);
2902

    
2903
    foreach ($menu_links as $key => $item) {
2904
      $existing_item = db_select('menu_links')
2905
        ->fields('menu_links')
2906
        ->condition('link_path', $item['path'])
2907
        ->condition('module', 'system')
2908
        ->execute()->fetchAssoc();
2909
      if ($existing_item) {
2910
        $item['mlid'] = $existing_item['mlid'];
2911
        // A change in hook_menu may move the link to a different menu
2912
        if (empty($item['menu_name']) || ($item['menu_name'] == $existing_item['menu_name'])) {
2913
          $item['menu_name'] = $existing_item['menu_name'];
2914
          $item['plid'] = $existing_item['plid'];
2915
        }
2916
        else {
2917
          // It moved to a new menu. Let menu_link_save() try to find a new
2918
          // parent based on the path.
2919
          unset($item['plid']);
2920
        }
2921
        $item['has_children'] = $existing_item['has_children'];
2922
        $item['updated'] = $existing_item['updated'];
2923
      }
2924
      if ($existing_item && $existing_item['customized']) {
2925
        $parent_candidates[$existing_item['mlid']] = $existing_item;
2926
      }
2927
      else {
2928
        $item = _menu_link_build($item);
2929
        menu_link_save($item, $existing_item, $parent_candidates);
2930
        $parent_candidates[$item['mlid']] = $item;
2931
        unset($menu_links[$key]);
2932
      }
2933
    }
2934
  }
2935
  $paths = array_keys($menu);
2936
  // Updated and customized items whose router paths are gone need new ones.
2937
  $result = db_select('menu_links', NULL, array('fetch' => PDO::FETCH_ASSOC))
2938
    ->fields('menu_links', array(
2939
      'link_path',
2940
      'mlid',
2941
      'router_path',
2942
      'updated',
2943
    ))
2944
    ->condition(db_or()
2945
      ->condition('updated', 1)
2946
      ->condition(db_and()
2947
        ->condition('router_path', $paths, 'NOT IN')
2948
        ->condition('external', 0)
2949
        ->condition('customized', 1)
2950
      )
2951
    )
2952
    ->execute();
2953
  foreach ($result as $item) {
2954
    $router_path = _menu_find_router_path($item['link_path']);
2955
    if (!empty($router_path) && ($router_path != $item['router_path'] || $item['updated'])) {
2956
      // If the router path and the link path matches, it's surely a working
2957
      // item, so we clear the updated flag.
2958
      $updated = $item['updated'] && $router_path != $item['link_path'];
2959
      db_update('menu_links')
2960
        ->fields(array(
2961
          'router_path' => $router_path,
2962
          'updated' => (int) $updated,
2963
        ))
2964
        ->condition('mlid', $item['mlid'])
2965
        ->execute();
2966
    }
2967
  }
2968
  // Find any item whose router path does not exist any more.
2969
  $result = db_select('menu_links')
2970
    ->fields('menu_links')
2971
    ->condition('router_path', $paths, 'NOT IN')
2972
    ->condition('external', 0)
2973
    ->condition('updated', 0)
2974
    ->condition('customized', 0)
2975
    ->orderBy('depth', 'DESC')
2976
    ->execute();
2977
  // Remove all such items. Starting from those with the greatest depth will
2978
  // minimize the amount of re-parenting done by menu_link_delete().
2979
  foreach ($result as $item) {
2980
    _menu_delete_item($item, TRUE);
2981
  }
2982
}
2983

    
2984
/**
2985
 * Clones an array of menu links.
2986
 *
2987
 * @param $links
2988
 *   An array of menu links to clone.
2989
 * @param $menu_name
2990
 *   (optional) The name of a menu that the links will be cloned for. If not
2991
 *   set, the cloned links will be in the same menu as the original set of
2992
 *   links that were passed in.
2993
 *
2994
 * @return
2995
 *   An array of menu links with the same properties as the passed-in array,
2996
 *   but with the link identifiers removed so that a new link will be created
2997
 *   when any of them is passed in to menu_link_save().
2998
 *
2999
 * @see menu_link_save()
3000
 */
3001
function menu_links_clone($links, $menu_name = NULL) {
3002
  foreach ($links as &$link) {
3003
    unset($link['mlid']);
3004
    unset($link['plid']);
3005
    if (isset($menu_name)) {
3006
      $link['menu_name'] = $menu_name;
3007
    }
3008
  }
3009
  return $links;
3010
}
3011

    
3012
/**
3013
 * Returns an array containing all links for a menu.
3014
 *
3015
 * @param $menu_name
3016
 *   The name of the menu whose links should be returned.
3017
 *
3018
 * @return
3019
 *   An array of menu links.
3020
 */
3021
function menu_load_links($menu_name) {
3022
  $links = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC))
3023
    ->fields('ml')
3024
    ->condition('ml.menu_name', $menu_name)
3025
    // Order by weight so as to be helpful for menus that are only one level
3026
    // deep.
3027
    ->orderBy('weight')
3028
    ->execute()
3029
    ->fetchAll();
3030

    
3031
  foreach ($links as &$link) {
3032
    $link['options'] = unserialize($link['options']);
3033
  }
3034
  return $links;
3035
}
3036

    
3037
/**
3038
 * Deletes all links for a menu.
3039
 *
3040
 * @param $menu_name
3041
 *   The name of the menu whose links will be deleted.
3042
 */
3043
function menu_delete_links($menu_name) {
3044
  $links = menu_load_links($menu_name);
3045
  foreach ($links as $link) {
3046
    // To speed up the deletion process, we reset some link properties that
3047
    // would trigger re-parenting logic in _menu_delete_item() and
3048
    // _menu_update_parental_status().
3049
    $link['has_children'] = FALSE;
3050
    $link['plid'] = 0;
3051
    _menu_delete_item($link);
3052
  }
3053
}
3054

    
3055
/**
3056
 * Delete one or several menu links.
3057
 *
3058
 * @param $mlid
3059
 *   A valid menu link mlid or NULL. If NULL, $path is used.
3060
 * @param $path
3061
 *   The path to the menu items to be deleted. $mlid must be NULL.
3062
 */
3063
function menu_link_delete($mlid, $path = NULL) {
3064
  if (isset($mlid)) {
3065
    _menu_delete_item(db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc());
3066
  }
3067
  else {
3068
    $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $path));
3069
    foreach ($result as $link) {
3070
      _menu_delete_item($link);
3071
    }
3072
  }
3073
}
3074

    
3075
/**
3076
 * Deletes a single menu link.
3077
 *
3078
 * @param $item
3079
 *   Item to be deleted.
3080
 * @param $force
3081
 *   Forces deletion. Internal use only, setting to TRUE is discouraged.
3082
 *
3083
 * @see menu_link_delete()
3084
 */
3085
function _menu_delete_item($item, $force = FALSE) {
3086
  $item = is_object($item) ? get_object_vars($item) : $item;
3087
  if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) {
3088
    // Children get re-attached to the item's parent.
3089
    if ($item['has_children']) {
3090
      $result = db_query("SELECT mlid FROM {menu_links} WHERE plid = :plid", array(':plid' => $item['mlid']));
3091
      foreach ($result as $m) {
3092
        $child = menu_link_load($m->mlid);
3093
        $child['plid'] = $item['plid'];
3094
        menu_link_save($child);
3095
      }
3096
    }
3097

    
3098
    // Notify modules we are deleting the item.
3099
    module_invoke_all('menu_link_delete', $item);
3100

    
3101
    db_delete('menu_links')->condition('mlid', $item['mlid'])->execute();
3102

    
3103
    // Update the has_children status of the parent.
3104
    _menu_update_parental_status($item);
3105
    menu_cache_clear($item['menu_name']);
3106
    _menu_clear_page_cache();
3107
  }
3108
}
3109

    
3110
/**
3111
 * Saves a menu link.
3112
 *
3113
 * After calling this function, rebuild the menu cache using
3114
 * menu_cache_clear_all().
3115
 *
3116
 * @param $item
3117
 *   An associative array representing a menu link item, with elements:
3118
 *   - link_path: (required) The path of the menu item, which should be
3119
 *     normalized first by calling drupal_get_normal_path() on it.
3120
 *   - link_title: (required) Title to appear in menu for the link.
3121
 *   - menu_name: (optional) The machine name of the menu for the link.
3122
 *     Defaults to 'navigation'.
3123
 *   - weight: (optional) Integer to determine position in menu. Default is 0.
3124
 *   - expanded: (optional) Boolean that determines if the item is expanded.
3125
 *   - options: (optional) An array of options, see l() for more.
3126
 *   - mlid: (optional) Menu link identifier, the primary integer key for each
3127
 *     menu link. Can be set to an existing value, or to 0 or NULL
3128
 *     to insert a new link.
3129
 *   - plid: (optional) The mlid of the parent.
3130
 *   - router_path: (optional) The path of the relevant router item.
3131
 * @param $existing_item
3132
 *   Optional, the current record from the {menu_links} table as an array.
3133
 * @param $parent_candidates
3134
 *   Optional array of menu links keyed by mlid. Used by
3135
 *   _menu_navigation_links_rebuild() only.
3136
 *
3137
 * @return
3138
 *   The mlid of the saved menu link, or FALSE if the menu link could not be
3139
 *   saved.
3140
 */
3141
function menu_link_save(&$item, $existing_item = array(), $parent_candidates = array()) {
3142
  drupal_alter('menu_link', $item);
3143

    
3144
  // This is the easiest way to handle the unique internal path '<front>',
3145
  // since a path marked as external does not need to match a router path.
3146
  $item['external'] = (url_is_external($item['link_path'])  || $item['link_path'] == '<front>') ? 1 : 0;
3147
  // Load defaults.
3148
  $item += array(
3149
    'menu_name' => 'navigation',
3150
    'weight' => 0,
3151
    'link_title' => '',
3152
    'hidden' => 0,
3153
    'has_children' => 0,
3154
    'expanded' => 0,
3155
    'options' => array(),
3156
    'module' => 'menu',
3157
    'customized' => 0,
3158
    'updated' => 0,
3159
  );
3160
  if (isset($item['mlid'])) {
3161
    if (!$existing_item) {
3162
      $existing_item = db_query('SELECT * FROM {menu_links} WHERE mlid = :mlid', array('mlid' => $item['mlid']))->fetchAssoc();
3163
    }
3164
    if ($existing_item) {
3165
      $existing_item['options'] = unserialize($existing_item['options']);
3166
    }
3167
  }
3168
  else {
3169
    $existing_item = FALSE;
3170
  }
3171

    
3172
  // Try to find a parent link. If found, assign it and derive its menu.
3173
  $parent = _menu_link_find_parent($item, $parent_candidates);
3174
  if (!empty($parent['mlid'])) {
3175
    $item['plid'] = $parent['mlid'];
3176
    $item['menu_name'] = $parent['menu_name'];
3177
  }
3178
  // If no corresponding parent link was found, move the link to the top-level.
3179
  else {
3180
    $item['plid'] = 0;
3181
  }
3182
  $menu_name = $item['menu_name'];
3183

    
3184
  if (!$existing_item) {
3185
    $item['mlid'] = db_insert('menu_links')
3186
      ->fields(array(
3187
        'menu_name' => $item['menu_name'],
3188
        'plid' => $item['plid'],
3189
        'link_path' => $item['link_path'],
3190
        'hidden' => $item['hidden'],
3191
        'external' => $item['external'],
3192
        'has_children' => $item['has_children'],
3193
        'expanded' => $item['expanded'],
3194
        'weight' => $item['weight'],
3195
        'module' => $item['module'],
3196
        'link_title' => $item['link_title'],
3197
        'options' => serialize($item['options']),
3198
        'customized' => $item['customized'],
3199
        'updated' => $item['updated'],
3200
      ))
3201
      ->execute();
3202
  }
3203

    
3204
  // Directly fill parents for top-level links.
3205
  if ($item['plid'] == 0) {
3206
    $item['p1'] = $item['mlid'];
3207
    for ($i = 2; $i <= MENU_MAX_DEPTH; $i++) {
3208
      $item["p$i"] = 0;
3209
    }
3210
    $item['depth'] = 1;
3211
  }
3212
  // Otherwise, ensure that this link's depth is not beyond the maximum depth
3213
  // and fill parents based on the parent link.
3214
  else {
3215
    if ($item['has_children'] && $existing_item) {
3216
      $limit = MENU_MAX_DEPTH - menu_link_children_relative_depth($existing_item) - 1;
3217
    }
3218
    else {
3219
      $limit = MENU_MAX_DEPTH - 1;
3220
    }
3221
    if ($parent['depth'] > $limit) {
3222
      return FALSE;
3223
    }
3224
    $item['depth'] = $parent['depth'] + 1;
3225
    _menu_link_parents_set($item, $parent);
3226
  }
3227
  // Need to check both plid and menu_name, since plid can be 0 in any menu.
3228
  if ($existing_item && ($item['plid'] != $existing_item['plid'] || $menu_name != $existing_item['menu_name'])) {
3229
    _menu_link_move_children($item, $existing_item);
3230
  }
3231
  // Find the router_path.
3232
  if (empty($item['router_path'])  || !$existing_item || ($existing_item['link_path'] != $item['link_path'])) {
3233
    if ($item['external']) {
3234
      $item['router_path'] = '';
3235
    }
3236
    else {
3237
      // Find the router path which will serve this path.
3238
      $item['parts'] = explode('/', $item['link_path'], MENU_MAX_PARTS);
3239
      $item['router_path'] = _menu_find_router_path($item['link_path']);
3240
    }
3241
  }
3242
  // If every value in $existing_item is the same in the $item, there is no
3243
  // reason to run the update queries or clear the caches. We use
3244
  // array_intersect_key() with the $item as the first parameter because
3245
  // $item may have additional keys left over from building a router entry.
3246
  // The intersect removes the extra keys, allowing a meaningful comparison.
3247
  if (!$existing_item || (array_intersect_key($item, $existing_item) != $existing_item)) {
3248
    db_update('menu_links')
3249
      ->fields(array(
3250
        'menu_name' => $item['menu_name'],
3251
        'plid' => $item['plid'],
3252
        'link_path' => $item['link_path'],
3253
        'router_path' => $item['router_path'],
3254
        'hidden' => $item['hidden'],
3255
        'external' => $item['external'],
3256
        'has_children' => $item['has_children'],
3257
        'expanded' => $item['expanded'],
3258
        'weight' => $item['weight'],
3259
        'depth' => $item['depth'],
3260
        'p1' => $item['p1'],
3261
        'p2' => $item['p2'],
3262
        'p3' => $item['p3'],
3263
        'p4' => $item['p4'],
3264
        'p5' => $item['p5'],
3265
        'p6' => $item['p6'],
3266
        'p7' => $item['p7'],
3267
        'p8' => $item['p8'],
3268
        'p9' => $item['p9'],
3269
        'module' => $item['module'],
3270
        'link_title' => $item['link_title'],
3271
        'options' => serialize($item['options']),
3272
        'customized' => $item['customized'],
3273
      ))
3274
      ->condition('mlid', $item['mlid'])
3275
      ->execute();
3276
    // Check the has_children status of the parent.
3277
    _menu_update_parental_status($item);
3278
    menu_cache_clear($menu_name);
3279
    if ($existing_item && $menu_name != $existing_item['menu_name']) {
3280
      menu_cache_clear($existing_item['menu_name']);
3281
    }
3282
    // Notify modules we have acted on a menu item.
3283
    $hook = 'menu_link_insert';
3284
    if ($existing_item) {
3285
      $hook = 'menu_link_update';
3286
    }
3287
    module_invoke_all($hook, $item);
3288
    // Now clear the cache.
3289
    _menu_clear_page_cache();
3290
  }
3291
  return $item['mlid'];
3292
}
3293

    
3294
/**
3295
 * Finds a possible parent for a given menu link.
3296
 *
3297
 * Because the parent of a given link might not exist anymore in the database,
3298
 * we apply a set of heuristics to determine a proper parent:
3299
 *
3300
 *  - use the passed parent link if specified and existing.
3301
 *  - else, use the first existing link down the previous link hierarchy
3302
 *  - else, for system menu links (derived from hook_menu()), reparent
3303
 *    based on the path hierarchy.
3304
 *
3305
 * @param $menu_link
3306
 *   A menu link.
3307
 * @param $parent_candidates
3308
 *   An array of menu links keyed by mlid.
3309
 *
3310
 * @return
3311
 *   A menu link structure of the possible parent or FALSE if no valid parent
3312
 *   has been found.
3313
 */
3314
function _menu_link_find_parent($menu_link, $parent_candidates = array()) {
3315
  $parent = FALSE;
3316

    
3317
  // This item is explicitely top-level, skip the rest of the parenting.
3318
  if (isset($menu_link['plid']) && empty($menu_link['plid'])) {
3319
    return $parent;
3320
  }
3321

    
3322
  // If we have a parent link ID, try to use that.
3323
  $candidates = array();
3324
  if (isset($menu_link['plid'])) {
3325
    $candidates[] = $menu_link['plid'];
3326
  }
3327

    
3328
  // Else, if we have a link hierarchy try to find a valid parent in there.
3329
  if (!empty($menu_link['depth']) && $menu_link['depth'] > 1) {
3330
    for ($depth = $menu_link['depth'] - 1; $depth >= 1; $depth--) {
3331
      $candidates[] = $menu_link['p' . $depth];
3332
    }
3333
  }
3334

    
3335
  foreach ($candidates as $mlid) {
3336
    if (isset($parent_candidates[$mlid])) {
3337
      $parent = $parent_candidates[$mlid];
3338
    }
3339
    else {
3340
      $parent = db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc();
3341
    }
3342
    if ($parent) {
3343
      return $parent;
3344
    }
3345
  }
3346

    
3347
  // If everything else failed, try to derive the parent from the path
3348
  // hierarchy. This only makes sense for links derived from menu router
3349
  // items (ie. from hook_menu()).
3350
  if ($menu_link['module'] == 'system') {
3351
    $query = db_select('menu_links');
3352
    $query->condition('module', 'system');
3353
    // We always respect the link's 'menu_name'; inheritance for router items is
3354
    // ensured in _menu_router_build().
3355
    $query->condition('menu_name', $menu_link['menu_name']);
3356

    
3357
    // Find the parent - it must be unique.
3358
    $parent_path = $menu_link['link_path'];
3359
    do {
3360
      $parent = FALSE;
3361
      $parent_path = substr($parent_path, 0, strrpos($parent_path, '/'));
3362
      $new_query = clone $query;
3363
      $new_query->condition('link_path', $parent_path);
3364
      // Only valid if we get a unique result.
3365
      if ($new_query->countQuery()->execute()->fetchField() == 1) {
3366
        $parent = $new_query->fields('menu_links')->execute()->fetchAssoc();
3367
      }
3368
    } while ($parent === FALSE && $parent_path);
3369
  }
3370

    
3371
  return $parent;
3372
}
3373

    
3374
/**
3375
 * Clears the page and block caches at most twice per page load.
3376
 */
3377
function _menu_clear_page_cache() {
3378
  $cache_cleared = &drupal_static(__FUNCTION__, 0);
3379

    
3380
  // Clear the page and block caches, but at most twice, including at
3381
  //  the end of the page load when there are multiple links saved or deleted.
3382
  if ($cache_cleared == 0) {
3383
    cache_clear_all();
3384
    // Keep track of which menus have expanded items.
3385
    _menu_set_expanded_menus();
3386
    $cache_cleared = 1;
3387
  }
3388
  elseif ($cache_cleared == 1) {
3389
    drupal_register_shutdown_function('cache_clear_all');
3390
    // Keep track of which menus have expanded items.
3391
    drupal_register_shutdown_function('_menu_set_expanded_menus');
3392
    $cache_cleared = 2;
3393
  }
3394
}
3395

    
3396
/**
3397
 * Updates a list of menus with expanded items.
3398
 */
3399
function _menu_set_expanded_menus() {
3400
  $names = db_query("SELECT menu_name FROM {menu_links} WHERE expanded <> 0 GROUP BY menu_name")->fetchCol();
3401
  variable_set('menu_expanded', $names);
3402
}
3403

    
3404
/**
3405
 * Finds the router path which will serve this path.
3406
 *
3407
 * @param $link_path
3408
 *  The path for we are looking up its router path.
3409
 *
3410
 * @return
3411
 *  A path from $menu keys or empty if $link_path points to a nonexisting
3412
 *  place.
3413
 */
3414
function _menu_find_router_path($link_path) {
3415
  // $menu will only have data during a menu rebuild.
3416
  $menu = _menu_router_cache();
3417

    
3418
  $router_path = $link_path;
3419
  $parts = explode('/', $link_path, MENU_MAX_PARTS);
3420
  $ancestors = menu_get_ancestors($parts);
3421

    
3422
  if (empty($menu)) {
3423
    // Not during a menu rebuild, so look up in the database.
3424
    $router_path = (string) db_select('menu_router')
3425
      ->fields('menu_router', array('path'))
3426
      ->condition('path', $ancestors, 'IN')
3427
      ->orderBy('fit', 'DESC')
3428
      ->range(0, 1)
3429
      ->execute()->fetchField();
3430
  }
3431
  elseif (!isset($menu[$router_path])) {
3432
    // Add an empty router path as a fallback.
3433
    $ancestors[] = '';
3434
    foreach ($ancestors as $key => $router_path) {
3435
      if (isset($menu[$router_path])) {
3436
        // Exit the loop leaving $router_path as the first match.
3437
        break;
3438
      }
3439
    }
3440
    // If we did not find the path, $router_path will be the empty string
3441
    // at the end of $ancestors.
3442
  }
3443
  return $router_path;
3444
}
3445

    
3446
/**
3447
 * Inserts, updates, or deletes an uncustomized menu link related to a module.
3448
 *
3449
 * @param $module
3450
 *   The name of the module.
3451
 * @param $op
3452
 *   Operation to perform: insert, update or delete.
3453
 * @param $link_path
3454
 *   The path this link points to.
3455
 * @param $link_title
3456
 *   Title of the link to insert or new title to update the link to.
3457
 *   Unused for delete.
3458
 *
3459
 * @return
3460
 *   The insert op returns the mlid of the new item. Others op return NULL.
3461
 */
3462
function menu_link_maintain($module, $op, $link_path, $link_title) {
3463
  switch ($op) {
3464
    case 'insert':
3465
      $menu_link = array(
3466
        'link_title' => $link_title,
3467
        'link_path' => $link_path,
3468
        'module' => $module,
3469
      );
3470
      return menu_link_save($menu_link);
3471
      break;
3472
    case 'update':
3473
      $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path AND module = :module AND customized = 0", array(':link_path' => $link_path, ':module' => $module))->fetchAll(PDO::FETCH_ASSOC);
3474
      foreach ($result as $link) {
3475
        $link['link_title'] = $link_title;
3476
        $link['options'] = unserialize($link['options']);
3477
        menu_link_save($link);
3478
      }
3479
      break;
3480
    case 'delete':
3481
      menu_link_delete(NULL, $link_path);
3482
      break;
3483
  }
3484
}
3485

    
3486
/**
3487
 * Finds the depth of an item's children relative to its depth.
3488
 *
3489
 * For example, if the item has a depth of 2, and the maximum of any child in
3490
 * the menu link tree is 5, the relative depth is 3.
3491
 *
3492
 * @param $item
3493
 *   An array representing a menu link item.
3494
 *
3495
 * @return
3496
 *   The relative depth, or zero.
3497
 *
3498
 */
3499
function menu_link_children_relative_depth($item) {
3500
  $query = db_select('menu_links');
3501
  $query->addField('menu_links', 'depth');
3502
  $query->condition('menu_name', $item['menu_name']);
3503
  $query->orderBy('depth', 'DESC');
3504
  $query->range(0, 1);
3505

    
3506
  $i = 1;
3507
  $p = 'p1';
3508
  while ($i <= MENU_MAX_DEPTH && $item[$p]) {
3509
    $query->condition($p, $item[$p]);
3510
    $p = 'p' . ++$i;
3511
  }
3512

    
3513
  $max_depth = $query->execute()->fetchField();
3514

    
3515
  return ($max_depth > $item['depth']) ? $max_depth - $item['depth'] : 0;
3516
}
3517

    
3518
/**
3519
 * Updates the children of a menu link that is being moved.
3520
 *
3521
 * The menu name, parents (p1 - p6), and depth are updated for all children of
3522
 * the link, and the has_children status of the previous parent is updated.
3523
 */
3524
function _menu_link_move_children($item, $existing_item) {
3525
  $query = db_update('menu_links');
3526

    
3527
  $query->fields(array('menu_name' => $item['menu_name']));
3528

    
3529
  $p = 'p1';
3530
  $expressions = array();
3531
  for ($i = 1; $i <= $item['depth']; $p = 'p' . ++$i) {
3532
    $expressions[] = array($p, ":p_$i", array(":p_$i" => $item[$p]));
3533
  }
3534
  $j = $existing_item['depth'] + 1;
3535
  while ($i <= MENU_MAX_DEPTH && $j <= MENU_MAX_DEPTH) {
3536
    $expressions[] = array('p' . $i++, 'p' . $j++, array());
3537
  }
3538
  while ($i <= MENU_MAX_DEPTH) {
3539
    $expressions[] = array('p' . $i++, 0, array());
3540
  }
3541

    
3542
  $shift = $item['depth'] - $existing_item['depth'];
3543
  if ($shift > 0) {
3544
    // The order of expressions must be reversed so the new values don't
3545
    // overwrite the old ones before they can be used because "Single-table
3546
    // UPDATE assignments are generally evaluated from left to right"
3547
    // see: http://dev.mysql.com/doc/refman/5.0/en/update.html
3548
    $expressions = array_reverse($expressions);
3549
  }
3550
  foreach ($expressions as $expression) {
3551
    $query->expression($expression[0], $expression[1], $expression[2]);
3552
  }
3553

    
3554
  $query->expression('depth', 'depth + :depth', array(':depth' => $shift));
3555
  $query->condition('menu_name', $existing_item['menu_name']);
3556
  $p = 'p1';
3557
  for ($i = 1; $i <= MENU_MAX_DEPTH && $existing_item[$p]; $p = 'p' . ++$i) {
3558
    $query->condition($p, $existing_item[$p]);
3559
  }
3560

    
3561
  $query->execute();
3562

    
3563
  // Check the has_children status of the parent, while excluding this item.
3564
  _menu_update_parental_status($existing_item, TRUE);
3565
}
3566

    
3567
/**
3568
 * Checks and updates the 'has_children' status for the parent of a link.
3569
 */
3570
function _menu_update_parental_status($item, $exclude = FALSE) {
3571
  // If plid == 0, there is nothing to update.
3572
  if ($item['plid']) {
3573
    // Check if at least one visible child exists in the table.
3574
    $query = db_select('menu_links');
3575
    $query->addField('menu_links', 'mlid');
3576
    $query->condition('menu_name', $item['menu_name']);
3577
    $query->condition('hidden', 0);
3578
    $query->condition('plid', $item['plid']);
3579
    $query->range(0, 1);
3580
    if ($exclude) {
3581
      $query->condition('mlid', $item['mlid'], '<>');
3582
    }
3583
    $parent_has_children = ((bool) $query->execute()->fetchField()) ? 1 : 0;
3584
    db_update('menu_links')
3585
      ->fields(array('has_children' => $parent_has_children))
3586
      ->condition('mlid', $item['plid'])
3587
      ->execute();
3588
  }
3589
}
3590

    
3591
/**
3592
 * Sets the p1 through p9 values for a menu link being saved.
3593
 */
3594
function _menu_link_parents_set(&$item, $parent) {
3595
  $i = 1;
3596
  while ($i < $item['depth']) {
3597
    $p = 'p' . $i++;
3598
    $item[$p] = $parent[$p];
3599
  }
3600
  $p = 'p' . $i++;
3601
  // The parent (p1 - p9) corresponding to the depth always equals the mlid.
3602
  $item[$p] = $item['mlid'];
3603
  while ($i <= MENU_MAX_DEPTH) {
3604
    $p = 'p' . $i++;
3605
    $item[$p] = 0;
3606
  }
3607
}
3608

    
3609
/**
3610
 * Builds the router table based on the data from hook_menu().
3611
 */
3612
function _menu_router_build($callbacks) {
3613
  // First pass: separate callbacks from paths, making paths ready for
3614
  // matching. Calculate fitness, and fill some default values.
3615
  $menu = array();
3616
  $masks = array();
3617
  foreach ($callbacks as $path => $item) {
3618
    $load_functions = array();
3619
    $to_arg_functions = array();
3620
    $fit = 0;
3621
    $move = FALSE;
3622

    
3623
    $parts = explode('/', $path, MENU_MAX_PARTS);
3624
    $number_parts = count($parts);
3625
    // We store the highest index of parts here to save some work in the fit
3626
    // calculation loop.
3627
    $slashes = $number_parts - 1;
3628
    // Extract load and to_arg functions.
3629
    foreach ($parts as $k => $part) {
3630
      $match = FALSE;
3631
      // Look for wildcards in the form allowed to be used in PHP functions,
3632
      // because we are using these to construct the load function names.
3633
      if (preg_match('/^%(|' . DRUPAL_PHP_FUNCTION_PATTERN . ')$/', $part, $matches)) {
3634
        if (empty($matches[1])) {
3635
          $match = TRUE;
3636
          $load_functions[$k] = NULL;
3637
        }
3638
        else {
3639
          if (function_exists($matches[1] . '_to_arg')) {
3640
            $to_arg_functions[$k] = $matches[1] . '_to_arg';
3641
            $load_functions[$k] = NULL;
3642
            $match = TRUE;
3643
          }
3644
          if (function_exists($matches[1] . '_load')) {
3645
            $function = $matches[1] . '_load';
3646
            // Create an array of arguments that will be passed to the _load
3647
            // function when this menu path is checked, if 'load arguments'
3648
            // exists.
3649
            $load_functions[$k] = isset($item['load arguments']) ? array($function => $item['load arguments']) : $function;
3650
            $match = TRUE;
3651
          }
3652
        }
3653
      }
3654
      if ($match) {
3655
        $parts[$k] = '%';
3656
      }
3657
      else {
3658
        $fit |=  1 << ($slashes - $k);
3659
      }
3660
    }
3661
    if ($fit) {
3662
      $move = TRUE;
3663
    }
3664
    else {
3665
      // If there is no %, it fits maximally.
3666
      $fit = (1 << $number_parts) - 1;
3667
    }
3668
    $masks[$fit] = 1;
3669
    $item['_load_functions'] = $load_functions;
3670
    $item['to_arg_functions'] = empty($to_arg_functions) ? '' : serialize($to_arg_functions);
3671
    $item += array(
3672
      'title' => '',
3673
      'weight' => 0,
3674
      'type' => MENU_NORMAL_ITEM,
3675
      'module' => '',
3676
      '_number_parts' => $number_parts,
3677
      '_parts' => $parts,
3678
      '_fit' => $fit,
3679
    );
3680
    $item += array(
3681
      '_visible' => (bool) ($item['type'] & MENU_VISIBLE_IN_BREADCRUMB),
3682
      '_tab' => (bool) ($item['type'] & MENU_IS_LOCAL_TASK),
3683
    );
3684
    if ($move) {
3685
      $new_path = implode('/', $item['_parts']);
3686
      $menu[$new_path] = $item;
3687
      $sort[$new_path] = $number_parts;
3688
    }
3689
    else {
3690
      $menu[$path] = $item;
3691
      $sort[$path] = $number_parts;
3692
    }
3693
  }
3694
  array_multisort($sort, SORT_NUMERIC, $menu);
3695
  // Apply inheritance rules.
3696
  foreach ($menu as $path => $v) {
3697
    $item = &$menu[$path];
3698
    if (!$item['_tab']) {
3699
      // Non-tab items.
3700
      $item['tab_parent'] = '';
3701
      $item['tab_root'] = $path;
3702
    }
3703
    // If not specified, assign the default tab type for local tasks.
3704
    elseif (!isset($item['context'])) {
3705
      $item['context'] = MENU_CONTEXT_PAGE;
3706
    }
3707
    for ($i = $item['_number_parts'] - 1; $i; $i--) {
3708
      $parent_path = implode('/', array_slice($item['_parts'], 0, $i));
3709
      if (isset($menu[$parent_path])) {
3710

    
3711
        $parent = &$menu[$parent_path];
3712

    
3713
        // If we have no menu name, try to inherit it from parent items.
3714
        if (!isset($item['menu_name'])) {
3715
          // If the parent item of this item does not define a menu name (and no
3716
          // previous iteration assigned one already), try to find the menu name
3717
          // of the parent item in the currently stored menu links.
3718
          if (!isset($parent['menu_name'])) {
3719
            $menu_name = db_query("SELECT menu_name FROM {menu_links} WHERE router_path = :router_path AND module = 'system'", array(':router_path' => $parent_path))->fetchField();
3720
            if ($menu_name) {
3721
              $parent['menu_name'] = $menu_name;
3722
            }
3723
          }
3724
          // If the parent item defines a menu name, inherit it.
3725
          if (!empty($parent['menu_name'])) {
3726
            $item['menu_name'] = $parent['menu_name'];
3727
          }
3728
        }
3729
        if (!isset($item['tab_parent'])) {
3730
          // Parent stores the parent of the path.
3731
          $item['tab_parent'] = $parent_path;
3732
        }
3733
        if (!isset($item['tab_root']) && !$parent['_tab']) {
3734
          $item['tab_root'] = $parent_path;
3735
        }
3736
        // If an access callback is not found for a default local task we use
3737
        // the callback from the parent, since we expect them to be identical.
3738
        // In all other cases, the access parameters must be specified.
3739
        if (($item['type'] == MENU_DEFAULT_LOCAL_TASK) && !isset($item['access callback']) && isset($parent['access callback'])) {
3740
          $item['access callback'] = $parent['access callback'];
3741
          if (!isset($item['access arguments']) && isset($parent['access arguments'])) {
3742
            $item['access arguments'] = $parent['access arguments'];
3743
          }
3744
        }
3745
        // Same for page callbacks.
3746
        if (!isset($item['page callback']) && isset($parent['page callback'])) {
3747
          $item['page callback'] = $parent['page callback'];
3748
          if (!isset($item['page arguments']) && isset($parent['page arguments'])) {
3749
            $item['page arguments'] = $parent['page arguments'];
3750
          }
3751
          if (!isset($item['file path']) && isset($parent['file path'])) {
3752
            $item['file path'] = $parent['file path'];
3753
          }
3754
          if (!isset($item['file']) && isset($parent['file'])) {
3755
            $item['file'] = $parent['file'];
3756
            if (empty($item['file path']) && isset($item['module']) && isset($parent['module']) && $item['module'] != $parent['module']) {
3757
              $item['file path'] = drupal_get_path('module', $parent['module']);
3758
            }
3759
          }
3760
        }
3761
        // Same for delivery callbacks.
3762
        if (!isset($item['delivery callback']) && isset($parent['delivery callback'])) {
3763
          $item['delivery callback'] = $parent['delivery callback'];
3764
        }
3765
        // Same for theme callbacks.
3766
        if (!isset($item['theme callback']) && isset($parent['theme callback'])) {
3767
          $item['theme callback'] = $parent['theme callback'];
3768
          if (!isset($item['theme arguments']) && isset($parent['theme arguments'])) {
3769
            $item['theme arguments'] = $parent['theme arguments'];
3770
          }
3771
        }
3772
        // Same for load arguments: if a loader doesn't have any explict
3773
        // arguments, try to find arguments in the parent.
3774
        if (!isset($item['load arguments'])) {
3775
          foreach ($item['_load_functions'] as $k => $function) {
3776
            // This loader doesn't have any explict arguments...
3777
            if (!is_array($function)) {
3778
              // ... check the parent for a loader at the same position
3779
              // using the same function name and defining arguments...
3780
              if (isset($parent['_load_functions'][$k]) && is_array($parent['_load_functions'][$k]) && key($parent['_load_functions'][$k]) === $function) {
3781
                // ... and inherit the arguments on the child.
3782
                $item['_load_functions'][$k] = $parent['_load_functions'][$k];
3783
              }
3784
            }
3785
          }
3786
        }
3787
      }
3788
    }
3789
    if (!isset($item['access callback']) && isset($item['access arguments'])) {
3790
      // Default callback.
3791
      $item['access callback'] = 'user_access';
3792
    }
3793
    if (!isset($item['access callback']) || empty($item['page callback'])) {
3794
      $item['access callback'] = 0;
3795
    }
3796
    if (is_bool($item['access callback'])) {
3797
      $item['access callback'] = intval($item['access callback']);
3798
    }
3799

    
3800
    $item['load_functions'] = empty($item['_load_functions']) ? '' : serialize($item['_load_functions']);
3801
    $item += array(
3802
      'access arguments' => array(),
3803
      'access callback' => '',
3804
      'page arguments' => array(),
3805
      'page callback' => '',
3806
      'delivery callback' => '',
3807
      'title arguments' => array(),
3808
      'title callback' => 't',
3809
      'theme arguments' => array(),
3810
      'theme callback' => '',
3811
      'description' => '',
3812
      'position' => '',
3813
      'context' => 0,
3814
      'tab_parent' => '',
3815
      'tab_root' => $path,
3816
      'path' => $path,
3817
      'file' => '',
3818
      'file path' => '',
3819
      'include file' => '',
3820
    );
3821

    
3822
    // Calculate out the file to be included for each callback, if any.
3823
    if ($item['file']) {
3824
      $file_path = $item['file path'] ? $item['file path'] : drupal_get_path('module', $item['module']);
3825
      $item['include file'] = $file_path . '/' . $item['file'];
3826
    }
3827
  }
3828

    
3829
  // Sort the masks so they are in order of descending fit.
3830
  $masks = array_keys($masks);
3831
  rsort($masks);
3832

    
3833
  return array($menu, $masks);
3834
}
3835

    
3836
/**
3837
 * Saves data from menu_router_build() to the router table.
3838
 */
3839
function _menu_router_save($menu, $masks) {
3840
  // Delete the existing router since we have some data to replace it.
3841
  db_truncate('menu_router')->execute();
3842

    
3843
  // Prepare insert object.
3844
  $insert = db_insert('menu_router')
3845
    ->fields(array(
3846
      'path',
3847
      'load_functions',
3848
      'to_arg_functions',
3849
      'access_callback',
3850
      'access_arguments',
3851
      'page_callback',
3852
      'page_arguments',
3853
      'delivery_callback',
3854
      'fit',
3855
      'number_parts',
3856
      'context',
3857
      'tab_parent',
3858
      'tab_root',
3859
      'title',
3860
      'title_callback',
3861
      'title_arguments',
3862
      'theme_callback',
3863
      'theme_arguments',
3864
      'type',
3865
      'description',
3866
      'position',
3867
      'weight',
3868
      'include_file',
3869
    ));
3870

    
3871
  $num_records = 0;
3872

    
3873
  foreach ($menu as $path => $item) {
3874
    // Fill in insert object values.
3875
    $insert->values(array(
3876
      'path' => $item['path'],
3877
      'load_functions' => $item['load_functions'],
3878
      'to_arg_functions' => $item['to_arg_functions'],
3879
      'access_callback' => $item['access callback'],
3880
      'access_arguments' => serialize($item['access arguments']),
3881
      'page_callback' => $item['page callback'],
3882
      'page_arguments' => serialize($item['page arguments']),
3883
      'delivery_callback' => $item['delivery callback'],
3884
      'fit' => $item['_fit'],
3885
      'number_parts' => $item['_number_parts'],
3886
      'context' => $item['context'],
3887
      'tab_parent' => $item['tab_parent'],
3888
      'tab_root' => $item['tab_root'],
3889
      'title' => $item['title'],
3890
      'title_callback' => $item['title callback'],
3891
      'title_arguments' => ($item['title arguments'] ? serialize($item['title arguments']) : ''),
3892
      'theme_callback' => $item['theme callback'],
3893
      'theme_arguments' => serialize($item['theme arguments']),
3894
      'type' => $item['type'],
3895
      'description' => $item['description'],
3896
      'position' => $item['position'],
3897
      'weight' => $item['weight'],
3898
      'include_file' => $item['include file'],
3899
    ));
3900

    
3901
    // Execute in batches to avoid the memory overhead of all of those records
3902
    // in the query object.
3903
    if (++$num_records == 20) {
3904
      $insert->execute();
3905
      $num_records = 0;
3906
    }
3907
  }
3908
  // Insert any remaining records.
3909
  $insert->execute();
3910
  // Store the masks.
3911
  variable_set('menu_masks', $masks);
3912

    
3913
  return $menu;
3914
}
3915

    
3916
/**
3917
 * Checks whether the site is in maintenance mode.
3918
 *
3919
 * This function will log the current user out and redirect to front page
3920
 * if the current user has no 'access site in maintenance mode' permission.
3921
 *
3922
 * @param $check_only
3923
 *   If this is set to TRUE, the function will perform the access checks and
3924
 *   return the site offline status, but not log the user out or display any
3925
 *   messages.
3926
 *
3927
 * @return
3928
 *   FALSE if the site is not in maintenance mode, the user login page is
3929
 *   displayed, or the user has the 'access site in maintenance mode'
3930
 *   permission. TRUE for anonymous users not being on the login page when the
3931
 *   site is in maintenance mode.
3932
 */
3933
function _menu_site_is_offline($check_only = FALSE) {
3934
  // Check if site is in maintenance mode.
3935
  if (variable_get('maintenance_mode', 0)) {
3936
    if (user_access('access site in maintenance mode')) {
3937
      // Ensure that the maintenance mode message is displayed only once
3938
      // (allowing for page redirects) and specifically suppress its display on
3939
      // the maintenance mode settings page.
3940
      if (!$check_only && $_GET['q'] != 'admin/config/development/maintenance') {
3941
        if (user_access('administer site configuration')) {
3942
          drupal_set_message(t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance'))), 'status', FALSE);
3943
        }
3944
        else {
3945
          drupal_set_message(t('Operating in maintenance mode.'), 'status', FALSE);
3946
        }
3947
      }
3948
    }
3949
    else {
3950
      return TRUE;
3951
    }
3952
  }
3953
  return FALSE;
3954
}
3955

    
3956
/**
3957
 * @} End of "defgroup menu".
3958
 */