Projet

Général

Profil

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

root / drupal7 / includes / menu.inc @ db2d93dd

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
 * Internal menu status code -- Menu item was not found.
233
 */
234
define('MENU_NOT_FOUND', 2);
235

    
236
/**
237
 * Internal menu status code -- Menu item access is denied.
238
 */
239
define('MENU_ACCESS_DENIED', 3);
240

    
241
/**
242
 * Internal menu status code -- Menu item inaccessible because site is offline.
243
 */
244
define('MENU_SITE_OFFLINE', 4);
245

    
246
/**
247
 * Internal menu status code -- Everything is working fine.
248
 */
249
define('MENU_SITE_ONLINE', 5);
250

    
251
/**
252
 * @} End of "Menu status codes".
253
 */
254

    
255
/**
256
 * @defgroup menu_tree_parameters Menu tree parameters
257
 * @{
258
 * Parameters for a menu tree.
259
 */
260

    
261
 /**
262
 * The maximum number of path elements for a menu callback
263
 */
264
define('MENU_MAX_PARTS', 9);
265

    
266

    
267
/**
268
 * The maximum depth of a menu links tree - matches the number of p columns.
269
 */
270
define('MENU_MAX_DEPTH', 9);
271

    
272

    
273
/**
274
 * @} End of "Menu tree parameters".
275
 */
276

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

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

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

    
412

    
413

    
414
/**
415
 * Replaces the statically cached item for a given path.
416
 *
417
 * @param $path
418
 *   The path.
419
 * @param $router_item
420
 *   The router item. Usually a router entry from menu_get_item() is either
421
 *   modified or set to a different path. This allows the navigation block,
422
 *   the page title, the breadcrumb, and the page help to be modified in one
423
 *   call.
424
 */
425
function menu_set_item($path, $router_item) {
426
  menu_get_item($path, $router_item);
427
}
428

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

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

    
469
    if ($router_item) {
470
      // Allow modules to alter the router item before it is translated and
471
      // checked for access.
472
      drupal_alter('menu_get_item', $router_item, $path, $original_map);
473

    
474
      $map = _menu_translate($router_item, $original_map);
475
      $router_item['original_map'] = $original_map;
476
      if ($map === FALSE) {
477
        $router_items[$path] = FALSE;
478
        return FALSE;
479
      }
480
      if ($router_item['access']) {
481
        $router_item['map'] = $map;
482
        $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
483
        $router_item['theme_arguments'] = array_merge(menu_unserialize($router_item['theme_arguments'], $map), array_slice($map, $router_item['number_parts']));
484
      }
485
    }
486
    $router_items[$path] = $router_item;
487
  }
488
  return $router_items[$path];
489
}
490

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

    
506
  // Allow other modules to change the site status but not the path because that
507
  // would not change the global variable. hook_url_inbound_alter() can be used
508
  // to change the path. Code later will not use the $read_only_path variable.
509
  $read_only_path = !empty($path) ? $path : $_GET['q'];
510
  drupal_alter('menu_site_status', $page_callback_result, $read_only_path);
511

    
512
  // Only continue if the site status is not set.
513
  if ($page_callback_result == MENU_SITE_ONLINE) {
514
    if ($router_item = menu_get_item($path)) {
515
      if ($router_item['access']) {
516
        if ($router_item['include_file']) {
517
          require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
518
        }
519
        $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
520
      }
521
      else {
522
        $page_callback_result = MENU_ACCESS_DENIED;
523
      }
524
    }
525
    else {
526
      $page_callback_result = MENU_NOT_FOUND;
527
    }
528
  }
529

    
530
  // Deliver the result of the page callback to the browser, or if requested,
531
  // return it raw, so calling code can do more processing.
532
  if ($deliver) {
533
    $default_delivery_callback = (isset($router_item) && $router_item) ? $router_item['delivery_callback'] : NULL;
534
    drupal_deliver_page($page_callback_result, $default_delivery_callback);
535
  }
536
  else {
537
    return $page_callback_result;
538
  }
539
}
540

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

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

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

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

    
715
  // Translate description, see the motivation above.
716
  if (!empty($item['description'])) {
717
    $original_description = $item['description'];
718
    $item['description'] = t($item['description']);
719
    if ($link_translate && isset($item['options']['attributes']['title']) && $item['options']['attributes']['title'] == $original_description) {
720
      $item['localized_options']['attributes']['title'] = $item['description'];
721
    }
722
  }
723
}
724

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

    
769
  // Generate the link path for the page request or local tasks.
770
  $link_map = explode('/', $router_item['path']);
771
  if (isset($router_item['tab_root'])) {
772
    $tab_root_map = explode('/', $router_item['tab_root']);
773
  }
774
  if (isset($router_item['tab_parent'])) {
775
    $tab_parent_map = explode('/', $router_item['tab_parent']);
776
  }
777
  for ($i = 0; $i < $router_item['number_parts']; $i++) {
778
    if ($link_map[$i] == '%') {
779
      $link_map[$i] = $path_map[$i];
780
    }
781
    if (isset($tab_root_map[$i]) && $tab_root_map[$i] == '%') {
782
      $tab_root_map[$i] = $path_map[$i];
783
    }
784
    if (isset($tab_parent_map[$i]) && $tab_parent_map[$i] == '%') {
785
      $tab_parent_map[$i] = $path_map[$i];
786
    }
787
  }
788
  $router_item['href'] = implode('/', $link_map);
789
  $router_item['tab_root_href'] = implode('/', $tab_root_map);
790
  $router_item['tab_parent_href'] = implode('/', $tab_parent_map);
791
  $router_item['options'] = array();
792
  _menu_check_access($router_item, $map);
793

    
794
  // For performance, don't localize an item the user can't access.
795
  if ($router_item['access']) {
796
    _menu_item_localize($router_item, $map);
797
  }
798

    
799
  return $map;
800
}
801

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

    
826
/**
827
 * Returns a string containing the path relative to the current index.
828
 */
829
function menu_tail_to_arg($arg, $map, $index) {
830
  return implode('/', array_slice($map, $index));
831
}
832

    
833
/**
834
 * Loads the path as one string relative to the current index.
835
 *
836
 * To use this load function, you must specify the load arguments
837
 * in the router item as:
838
 * @code
839
 * $item['load arguments'] = array('%map', '%index');
840
 * @endcode
841
 *
842
 * @see search_menu().
843
 */
844
function menu_tail_load($arg, &$map, $index) {
845
  $arg = implode('/', array_slice($map, $index));
846
  $map = array_slice($map, 0, $index);
847
  return $arg;
848
}
849

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

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

    
937
  // Allow other customizations - e.g. adding a page-specific query string to the
938
  // options array. For performance reasons we only invoke this hook if the link
939
  // has the 'alter' flag set in the options array.
940
  if (!empty($item['options']['alter'])) {
941
    drupal_alter('translated_menu_link', $item, $map);
942
  }
943

    
944
  return $map;
945
}
946

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

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

    
997
  if (!isset($menu_output[$menu_name])) {
998
    $tree = menu_tree_page_data($menu_name);
999
    $menu_output[$menu_name] = menu_tree_output($tree);
1000
  }
1001
  return $menu_output[$menu_name];
1002
}
1003

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

    
1022
  // Pull out just the menu links we are going to render so that we
1023
  // get an accurate count for the first/last classes.
1024
  foreach ($tree as $data) {
1025
    if ($data['link']['access'] && !$data['link']['hidden']) {
1026
      $items[] = $data;
1027
    }
1028
  }
1029

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

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

    
1084
  return $build;
1085
}
1086

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

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

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

    
1143
      // Cache the tree building parameters using the page-specific cid.
1144
      cache_set($cid, $tree_parameters, 'cache_menu');
1145
    }
1146

    
1147
    // Build the tree using the parameters; the resulting tree will be cached
1148
    // by _menu_build_tree()).
1149
    $tree[$cid] = menu_build_tree($menu_name, $tree_parameters);
1150
  }
1151

    
1152
  return $tree[$cid];
1153
}
1154

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

    
1180
/**
1181
 * Gets the path for determining the active trail of the specified menu tree.
1182
 *
1183
 * @param $menu_name
1184
 *   The menu name of the requested tree.
1185
 *
1186
 * @return
1187
 *   A string containing the path. If no path has been specified with
1188
 *   menu_tree_set_path(), NULL is returned.
1189
 */
1190
function menu_tree_get_path($menu_name) {
1191
  return menu_tree_set_path($menu_name);
1192
}
1193

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

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

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

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

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

    
1318
      // Build the tree using the parameters; the resulting tree will be cached
1319
      // by _menu_build_tree().
1320
      $tree[$cid] = menu_build_tree($menu_name, $tree_parameters);
1321
    }
1322
    return $tree[$cid];
1323
  }
1324

    
1325
  return array();
1326
}
1327

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

    
1361
/**
1362
 * Builds a menu tree.
1363
 *
1364
 * This function may be used build the data for a menu tree only, for example
1365
 * to further massage the data manually before further processing happens.
1366
 * menu_tree_check_access() needs to be invoked afterwards.
1367
 *
1368
 * @see menu_build_tree()
1369
 */
1370
function _menu_build_tree($menu_name, array $parameters = array()) {
1371
  // Static cache of already built menu trees.
1372
  $trees = &drupal_static(__FUNCTION__, array());
1373

    
1374
  // Build the cache id; sort parents to prevent duplicate storage and remove
1375
  // default parameter values.
1376
  if (isset($parameters['expanded'])) {
1377
    sort($parameters['expanded']);
1378
  }
1379
  $tree_cid = 'links:' . $menu_name . ':tree-data:' . $GLOBALS['language']->language . ':' . hash('sha256', serialize($parameters));
1380

    
1381
  // If we do not have this tree in the static cache, check {cache_menu}.
1382
  if (!isset($trees[$tree_cid])) {
1383
    $cache = cache_get($tree_cid, 'cache_menu');
1384
    if ($cache && isset($cache->data)) {
1385
      $trees[$tree_cid] = $cache->data;
1386
    }
1387
  }
1388

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

    
1439
    // Build an ordered array of links using the query result object.
1440
    $links = array();
1441
    foreach ($query->execute() as $item) {
1442
      $links[] = $item;
1443
    }
1444
    $active_trail = (isset($parameters['active_trail']) ? $parameters['active_trail'] : array());
1445
    $data['tree'] = menu_tree_data($links, $active_trail, $min_depth);
1446
    $data['node_links'] = array();
1447
    menu_tree_collect_node_links($data['tree'], $data['node_links']);
1448

    
1449
    // Cache the data, if it is not already in the cache.
1450
    cache_set($tree_cid, $data, 'cache_menu');
1451
    $trees[$tree_cid] = $data;
1452
  }
1453

    
1454
  return $trees[$tree_cid];
1455
}
1456

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

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

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

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

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

    
1597
/**
1598
 * Implements template_preprocess_HOOK() for theme_menu_tree().
1599
 */
1600
function template_preprocess_menu_tree(&$variables) {
1601
  $variables['tree'] = $variables['tree']['#children'];
1602
}
1603

    
1604
/**
1605
 * Returns HTML for a wrapper for a menu sub-tree.
1606
 *
1607
 * @param $variables
1608
 *   An associative array containing:
1609
 *   - tree: An HTML string containing the tree's items.
1610
 *
1611
 * @see template_preprocess_menu_tree()
1612
 * @ingroup themeable
1613
 */
1614
function theme_menu_tree($variables) {
1615
  return '<ul class="menu">' . $variables['tree'] . '</ul>';
1616
}
1617

    
1618
/**
1619
 * Returns HTML for a menu link and submenu.
1620
 *
1621
 * @param $variables
1622
 *   An associative array containing:
1623
 *   - element: Structured array data for a menu link.
1624
 *
1625
 * @ingroup themeable
1626
 */
1627
function theme_menu_link(array $variables) {
1628
  $element = $variables['element'];
1629
  $sub_menu = '';
1630

    
1631
  if ($element['#below']) {
1632
    $sub_menu = drupal_render($element['#below']);
1633
  }
1634
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
1635
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
1636
}
1637

    
1638
/**
1639
 * Returns HTML for a single local task link.
1640
 *
1641
 * @param $variables
1642
 *   An associative array containing:
1643
 *   - element: A render element containing:
1644
 *     - #link: A menu link array with 'title', 'href', and 'localized_options'
1645
 *       keys.
1646
 *     - #active: A boolean indicating whether the local task is active.
1647
 *
1648
 * @ingroup themeable
1649
 */
1650
function theme_menu_local_task($variables) {
1651
  $link = $variables['element']['#link'];
1652
  $link_text = $link['title'];
1653

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

    
1658
    // If the link does not contain HTML already, check_plain() it now.
1659
    // After we set 'html'=TRUE the link will not be sanitized by l().
1660
    if (empty($link['localized_options']['html'])) {
1661
      $link['title'] = check_plain($link['title']);
1662
    }
1663
    $link['localized_options']['html'] = TRUE;
1664
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
1665
  }
1666

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

    
1670
/**
1671
 * Returns HTML for a single local action link.
1672
 *
1673
 * @param $variables
1674
 *   An associative array containing:
1675
 *   - element: A render element containing:
1676
 *     - #link: A menu link array with 'title', 'href', and 'localized_options'
1677
 *       keys.
1678
 *
1679
 * @ingroup themeable
1680
 */
1681
function theme_menu_local_action($variables) {
1682
  $link = $variables['element']['#link'];
1683

    
1684
  $output = '<li>';
1685
  if (isset($link['href'])) {
1686
    $output .= l($link['title'], $link['href'], isset($link['localized_options']) ? $link['localized_options'] : array());
1687
  }
1688
  elseif (!empty($link['localized_options']['html'])) {
1689
    $output .= $link['title'];
1690
  }
1691
  else {
1692
    $output .= check_plain($link['title']);
1693
  }
1694
  $output .= "</li>\n";
1695

    
1696
  return $output;
1697
}
1698

    
1699
/**
1700
 * Generates elements for the $arg array in the help hook.
1701
 */
1702
function drupal_help_arg($arg = array()) {
1703
  // Note - the number of empty elements should be > MENU_MAX_PARTS.
1704
  return $arg + array('', '', '', '', '', '', '', '', '', '', '', '');
1705
}
1706

    
1707
/**
1708
 * Returns the help associated with the active menu item.
1709
 */
1710
function menu_get_active_help() {
1711
  $output = '';
1712
  $router_path = menu_tab_root_path();
1713
  // We will always have a path unless we are on a 403 or 404.
1714
  if (!$router_path) {
1715
    return '';
1716
  }
1717

    
1718
  $arg = drupal_help_arg(arg(NULL));
1719

    
1720
  foreach (module_implements('help') as $module) {
1721
    $function = $module . '_help';
1722
    // Lookup help for this path.
1723
    if ($help = $function($router_path, $arg)) {
1724
      $output .= $help . "\n";
1725
    }
1726
  }
1727
  return $output;
1728
}
1729

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

    
1768
/**
1769
 * Sets a custom theme for the current page, if there is one.
1770
 */
1771
function menu_set_custom_theme() {
1772
  menu_get_custom_theme(TRUE);
1773
}
1774

    
1775
/**
1776
 * Build a list of named menus.
1777
 */
1778
function menu_get_names() {
1779
  $names = &drupal_static(__FUNCTION__);
1780

    
1781
  if (empty($names)) {
1782
    $names = db_select('menu_links')
1783
      ->distinct()
1784
      ->fields('menu_links', array('menu_name'))
1785
      ->orderBy('menu_name')
1786
      ->execute()->fetchCol();
1787
  }
1788
  return $names;
1789
}
1790

    
1791
/**
1792
 * Returns an array containing the names of system-defined (default) menus.
1793
 */
1794
function menu_list_system_menus() {
1795
  return array(
1796
    'navigation' => 'Navigation',
1797
    'management' => 'Management',
1798
    'user-menu' => 'User menu',
1799
    'main-menu' => 'Main menu',
1800
  );
1801
}
1802

    
1803
/**
1804
 * Returns an array of links to be rendered as the Main menu.
1805
 */
1806
function menu_main_menu() {
1807
  return menu_navigation_links(variable_get('menu_main_links_source', 'main-menu'));
1808
}
1809

    
1810
/**
1811
 * Returns an array of links to be rendered as the Secondary links.
1812
 */
1813
function menu_secondary_menu() {
1814

    
1815
  // If the secondary menu source is set as the primary menu, we display the
1816
  // second level of the primary menu.
1817
  if (variable_get('menu_secondary_links_source', 'user-menu') == variable_get('menu_main_links_source', 'main-menu')) {
1818
    return menu_navigation_links(variable_get('menu_main_links_source', 'main-menu'), 1);
1819
  }
1820
  else {
1821
    return menu_navigation_links(variable_get('menu_secondary_links_source', 'user-menu'), 0);
1822
  }
1823
}
1824

    
1825
/**
1826
 * Returns an array of links for a navigation menu.
1827
 *
1828
 * @param $menu_name
1829
 *   The name of the menu.
1830
 * @param $level
1831
 *   Optional, the depth of the menu to be returned.
1832
 *
1833
 * @return
1834
 *   An array of links of the specified menu and level.
1835
 */
1836
function menu_navigation_links($menu_name, $level = 0) {
1837
  // Don't even bother querying the menu table if no menu is specified.
1838
  if (empty($menu_name)) {
1839
    return array();
1840
  }
1841

    
1842
  // Get the menu hierarchy for the current page.
1843
  $tree = menu_tree_page_data($menu_name, $level + 1);
1844

    
1845
  // Go down the active trail until the right level is reached.
1846
  while ($level-- > 0 && $tree) {
1847
    // Loop through the current level's items until we find one that is in trail.
1848
    while ($item = array_shift($tree)) {
1849
      if ($item['link']['in_active_trail']) {
1850
        // If the item is in the active trail, we continue in the subtree.
1851
        $tree = empty($item['below']) ? array() : $item['below'];
1852
        break;
1853
      }
1854
    }
1855
  }
1856

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

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

    
1910
  if (!isset($data)) {
1911
    $data = array();
1912
    // Set defaults in case there are no actions or tabs.
1913
    $actions = $empty['actions'];
1914
    $tabs = array();
1915

    
1916
    $router_item = menu_get_item();
1917

    
1918
    // If this router item points to its parent, start from the parents to
1919
    // compute tabs and actions.
1920
    if ($router_item && ($router_item['type'] & MENU_LINKS_TO_PARENT)) {
1921
      $router_item = menu_get_item($router_item['tab_parent_href']);
1922
    }
1923

    
1924
    // If we failed to fetch a router item or the current user doesn't have
1925
    // access to it, don't bother computing the tabs.
1926
    if (!$router_item || !$router_item['access']) {
1927
      return $empty;
1928
    }
1929

    
1930
    // Get all tabs (also known as local tasks) and the root page.
1931
    $cid = 'local_tasks:' . $router_item['tab_root'];
1932
    if ($cache = cache_get($cid, 'cache_menu')) {
1933
      $result = $cache->data;
1934
    }
1935
    else {
1936
      $result = db_select('menu_router', NULL, array('fetch' => PDO::FETCH_ASSOC))
1937
        ->fields('menu_router')
1938
        ->condition('tab_root', $router_item['tab_root'])
1939
        ->condition('context', MENU_CONTEXT_INLINE, '<>')
1940
        ->orderBy('weight')
1941
        ->orderBy('title')
1942
        ->execute()
1943
        ->fetchAll();
1944
      cache_set($cid, $result, 'cache_menu');
1945
    }
1946
    $map = $router_item['original_map'];
1947
    $children = array();
1948
    $tasks = array();
1949
    $root_path = $router_item['path'];
1950

    
1951
    foreach ($result as $item) {
1952
      _menu_translate($item, $map, TRUE);
1953
      if ($item['tab_parent']) {
1954
        // All tabs, but not the root page.
1955
        $children[$item['tab_parent']][$item['path']] = $item;
1956
      }
1957
      // Store the translated item for later use.
1958
      $tasks[$item['path']] = $item;
1959
    }
1960

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

    
2106
    // Allow modules to alter local tasks or dynamically append further tasks.
2107
    drupal_alter('menu_local_tasks', $data, $router_item, $root_path);
2108
  }
2109

    
2110
  if (isset($data['tabs'][$level])) {
2111
    return array(
2112
      'tabs' => $data['tabs'][$level],
2113
      'actions' => $data['actions'],
2114
      'root_path' => $root_path,
2115
    );
2116
  }
2117
  // @todo If there are no tabs, then there still can be actions; for example,
2118
  //   when added via hook_menu_local_tasks_alter().
2119
  elseif (!empty($data['actions']['output'])) {
2120
    return array('actions' => $data['actions']) + $empty;
2121
  }
2122
  return $empty;
2123
}
2124

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

    
2164
  $links = array();
2165
  // Performance: In case a previous invocation for the same parent path did not
2166
  // return any links, we immediately return here.
2167
  if (isset($path_empty[$parent_path]) && strpos($parent_path, '%') !== FALSE) {
2168
    return $links;
2169
  }
2170
  // Construct the item-specific parent path.
2171
  $path = $parent_path . '/' . implode('/', $args);
2172

    
2173
  // Get the router item for the given parent link path.
2174
  $router_item = menu_get_item($path);
2175
  if (!$router_item || !$router_item['access']) {
2176
    $path_empty[$parent_path] = TRUE;
2177
    return $links;
2178
  }
2179
  $data = &drupal_static(__FUNCTION__, array());
2180
  $root_path = $router_item['path'];
2181

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

    
2203
    // Denormalize and translate the contextual link.
2204
    _menu_translate($item, $map, TRUE);
2205
    if (!$item['access']) {
2206
      continue;
2207
    }
2208
    // All contextual links are keyed by the actual "task" path argument,
2209
    // prefixed with the name of the implementing module.
2210
    $links[$module . '-' . $key] = $item;
2211
  }
2212

    
2213
  // Allow modules to alter contextual links.
2214
  drupal_alter('menu_contextual_links', $links, $router_item, $root_path);
2215

    
2216
  // Performance: If the current user does not have access to any links for this
2217
  // router path and no other module added further links, we assign FALSE here
2218
  // to skip the entire process the next time the same router path is requested.
2219
  if (empty($links)) {
2220
    $path_empty[$parent_path] = TRUE;
2221
  }
2222

    
2223
  return $links;
2224
}
2225

    
2226
/**
2227
 * Returns the rendered local tasks at the top level.
2228
 */
2229
function menu_primary_local_tasks() {
2230
  $links = menu_local_tasks(0);
2231
  // Do not display single tabs.
2232
  return ($links['tabs']['count'] > 1 ? $links['tabs']['output'] : '');
2233
}
2234

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

    
2244
/**
2245
 * Returns the rendered local actions at the current level.
2246
 */
2247
function menu_local_actions() {
2248
  $links = menu_local_tasks();
2249
  return $links['actions']['output'];
2250
}
2251

    
2252
/**
2253
 * Returns the router path, or the path for a default local task's parent.
2254
 */
2255
function menu_tab_root_path() {
2256
  $links = menu_local_tasks();
2257
  return $links['root_path'];
2258
}
2259

    
2260
/**
2261
 * Returns a renderable element for the primary and secondary tabs.
2262
 */
2263
function menu_local_tabs() {
2264
  return array(
2265
    '#theme' => 'menu_local_tasks',
2266
    '#primary' => menu_primary_local_tasks(),
2267
    '#secondary' => menu_secondary_local_tasks(),
2268
  );
2269
}
2270

    
2271
/**
2272
 * Returns HTML for primary and secondary local tasks.
2273
 *
2274
 * @param $variables
2275
 *   An associative array containing:
2276
 *     - primary: (optional) An array of local tasks (tabs).
2277
 *     - secondary: (optional) An array of local tasks (tabs).
2278
 *
2279
 * @ingroup themeable
2280
 * @see menu_local_tasks()
2281
 */
2282
function theme_menu_local_tasks(&$variables) {
2283
  $output = '';
2284

    
2285
  if (!empty($variables['primary'])) {
2286
    $variables['primary']['#prefix'] = '<h2 class="element-invisible">' . t('Primary tabs') . '</h2>';
2287
    $variables['primary']['#prefix'] .= '<ul class="tabs primary">';
2288
    $variables['primary']['#suffix'] = '</ul>';
2289
    $output .= drupal_render($variables['primary']);
2290
  }
2291
  if (!empty($variables['secondary'])) {
2292
    $variables['secondary']['#prefix'] = '<h2 class="element-invisible">' . t('Secondary tabs') . '</h2>';
2293
    $variables['secondary']['#prefix'] .= '<ul class="tabs secondary">';
2294
    $variables['secondary']['#suffix'] = '</ul>';
2295
    $output .= drupal_render($variables['secondary']);
2296
  }
2297

    
2298
  return $output;
2299
}
2300

    
2301
/**
2302
 * Sets (or gets) the active menu for the current page.
2303
 *
2304
 * The active menu for the page determines the active trail.
2305
 *
2306
 * @return
2307
 *   An array of menu machine names, in order of preference. The
2308
 *   'menu_default_active_menus' variable may be used to assert a menu order
2309
 *   different from the order of creation, or to prevent a particular menu from
2310
 *   being used at all in the active trail.
2311
 *   E.g., $conf['menu_default_active_menus'] = array('navigation', 'main-menu')
2312
 */
2313
function menu_set_active_menu_names($menu_names = NULL) {
2314
  $active = &drupal_static(__FUNCTION__);
2315

    
2316
  if (isset($menu_names) && is_array($menu_names)) {
2317
    $active = $menu_names;
2318
  }
2319
  elseif (!isset($active)) {
2320
    $active = variable_get('menu_default_active_menus', array_keys(menu_list_system_menus()));
2321
  }
2322
  return $active;
2323
}
2324

    
2325
/**
2326
 * Gets the active menu for the current page.
2327
 */
2328
function menu_get_active_menu_names() {
2329
  return menu_set_active_menu_names();
2330
}
2331

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

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

    
2372
  if (isset($new_trail)) {
2373
    $trail = $new_trail;
2374
  }
2375
  elseif (!isset($trail)) {
2376
    $trail = array();
2377
    $trail[] = array(
2378
      'title' => t('Home'),
2379
      'href' => '<front>',
2380
      'link_path' => '',
2381
      'localized_options' => array(),
2382
      'type' => 0,
2383
    );
2384

    
2385
    // Try to retrieve a menu link corresponding to the current path. If more
2386
    // than one exists, the link from the most preferred menu is returned.
2387
    $preferred_link = menu_link_get_preferred();
2388
    $current_item = menu_get_item();
2389

    
2390
    // There is a link for the current path.
2391
    if ($preferred_link) {
2392
      // Pass TRUE for $only_active_trail to make menu_tree_page_data() build
2393
      // a stripped down menu tree containing the active trail only, in case
2394
      // the given menu has not been built in this request yet.
2395
      $tree = menu_tree_page_data($preferred_link['menu_name'], NULL, TRUE);
2396
      list($key, $curr) = each($tree);
2397
    }
2398
    // There is no link for the current path.
2399
    else {
2400
      $preferred_link = $current_item;
2401
      $curr = FALSE;
2402
    }
2403

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

    
2439
/**
2440
 * Looks up the preferred menu link for a given system path.
2441
 *
2442
 * @param $path
2443
 *   The path; for example, 'node/5'. The function will find the corresponding
2444
 *   menu link ('node/5' if it exists, or fallback to 'node/%').
2445
 * @param $selected_menu
2446
 *   The name of a menu used to restrict the search for a preferred menu link.
2447
 *   If not specified, all the menus returned by menu_get_active_menu_names()
2448
 *   will be used.
2449
 *
2450
 * @return
2451
 *   A fully translated menu link, or FALSE if no matching menu link was
2452
 *   found. The most specific menu link ('node/5' preferred over 'node/%') in
2453
 *   the most preferred menu (as defined by menu_get_active_menu_names()) is
2454
 *   returned.
2455
 */
2456
function menu_link_get_preferred($path = NULL, $selected_menu = NULL) {
2457
  $preferred_links = &drupal_static(__FUNCTION__);
2458

    
2459
  if (!isset($path)) {
2460
    $path = $_GET['q'];
2461
  }
2462

    
2463
  if (empty($selected_menu)) {
2464
    // Use an illegal menu name as the key for the preferred menu link.
2465
    $selected_menu = MENU_PREFERRED_LINK;
2466
  }
2467

    
2468
  if (!isset($preferred_links[$path])) {
2469
    // Look for the correct menu link by building a list of candidate paths,
2470
    // which are ordered by priority (translated hrefs are preferred over
2471
    // untranslated paths). Afterwards, the most relevant path is picked from
2472
    // the menus, ordered by menu preference.
2473
    $item = menu_get_item($path);
2474
    $path_candidates = array();
2475
    // 1. The current item href.
2476
    $path_candidates[$item['href']] = $item['href'];
2477
    // 2. The tab root href of the current item (if any).
2478
    if ($item['tab_parent'] && ($tab_root = menu_get_item($item['tab_root_href']))) {
2479
      $path_candidates[$tab_root['href']] = $tab_root['href'];
2480
    }
2481
    // 3. The current item path (with wildcards).
2482
    $path_candidates[$item['path']] = $item['path'];
2483
    // 4. The tab root path of the current item (if any).
2484
    if (!empty($tab_root)) {
2485
      $path_candidates[$tab_root['path']] = $tab_root['path'];
2486
    }
2487

    
2488
    // Retrieve a list of menu names, ordered by preference.
2489
    $menu_names = menu_get_active_menu_names();
2490
    // Put the selected menu at the front of the list.
2491
    array_unshift($menu_names, $selected_menu);
2492

    
2493
    $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
2494
    $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
2495
    $query->fields('ml');
2496
    // Weight must be taken from {menu_links}, not {menu_router}.
2497
    $query->addField('ml', 'weight', 'link_weight');
2498
    $query->fields('m');
2499
    $query->condition('ml.link_path', $path_candidates, 'IN');
2500
    $query->addTag('preferred_menu_links');
2501

    
2502
    // Sort candidates by link path and menu name.
2503
    $candidates = array();
2504
    foreach ($query->execute() as $candidate) {
2505
      $candidate['weight'] = $candidate['link_weight'];
2506
      $candidates[$candidate['link_path']][$candidate['menu_name']] = $candidate;
2507
      // Add any menus not already in the menu name search list.
2508
      if (!in_array($candidate['menu_name'], $menu_names)) {
2509
        $menu_names[] = $candidate['menu_name'];
2510
      }
2511
    }
2512

    
2513
    // Store the most specific link for each menu. Also save the most specific
2514
    // link of the most preferred menu in $preferred_link.
2515
    foreach ($path_candidates as $link_path) {
2516
      if (isset($candidates[$link_path])) {
2517
        foreach ($menu_names as $menu_name) {
2518
          if (empty($preferred_links[$path][$menu_name]) && isset($candidates[$link_path][$menu_name])) {
2519
            $candidate_item = $candidates[$link_path][$menu_name];
2520
            $map = explode('/', $path);
2521
            _menu_translate($candidate_item, $map);
2522
            if ($candidate_item['access']) {
2523
              $preferred_links[$path][$menu_name] = $candidate_item;
2524
              if (empty($preferred_links[$path][MENU_PREFERRED_LINK])) {
2525
                // Store the most specific link.
2526
                $preferred_links[$path][MENU_PREFERRED_LINK] = $candidate_item;
2527
              }
2528
            }
2529
          }
2530
        }
2531
      }
2532
    }
2533
  }
2534

    
2535
  return isset($preferred_links[$path][$selected_menu]) ? $preferred_links[$path][$selected_menu] : FALSE;
2536
}
2537

    
2538
/**
2539
 * Gets the active trail (path to root menu root) of the current page.
2540
 *
2541
 * If a trail is supplied to menu_set_active_trail(), that value is returned. If
2542
 * a trail is not supplied to menu_set_active_trail(), the path to the current
2543
 * page is calculated and returned. The calculated trail is also saved as a
2544
 * static value for use by subsequent calls to menu_get_active_trail().
2545
 *
2546
 * @return
2547
 *   Path to menu root of the current page, as an array of menu link items,
2548
 *   starting with the site's home page. Each link item is an associative array
2549
 *   with the following components:
2550
 *   - title: Title of the item.
2551
 *   - href: Drupal path of the item.
2552
 *   - localized_options: Options for passing into the l() function.
2553
 *   - type: A menu type constant, such as MENU_DEFAULT_LOCAL_TASK, or 0 to
2554
 *     indicate it's not really in the menu (used for the home page item).
2555
 */
2556
function menu_get_active_trail() {
2557
  return menu_set_active_trail();
2558
}
2559

    
2560
/**
2561
 * Gets the breadcrumb for the current page, as determined by the active trail.
2562
 *
2563
 * @see menu_set_active_trail()
2564
 */
2565
function menu_get_active_breadcrumb() {
2566
  $breadcrumb = array();
2567

    
2568
  // No breadcrumb for the front page.
2569
  if (drupal_is_front_page()) {
2570
    return $breadcrumb;
2571
  }
2572

    
2573
  $item = menu_get_item();
2574
  if (!empty($item['access'])) {
2575
    $active_trail = menu_get_active_trail();
2576

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

    
2581
    // Don't show a link to the current page in the breadcrumb trail.
2582
    $end = end($active_trail);
2583
    if ($item['href'] == $end['href']) {
2584
      array_pop($active_trail);
2585
    }
2586

    
2587
    // Remove the tab root (parent) if the current path links to its parent.
2588
    // Normally, the tab root link is included in the breadcrumb, as soon as we
2589
    // are on a local task or any other child link. However, if we are on a
2590
    // default local task (e.g., node/%/view), then we do not want the tab root
2591
    // link (e.g., node/%) to appear, as it would be identical to the current
2592
    // page. Since this behavior also needs to work recursively (i.e., on
2593
    // default local tasks of default local tasks), and since the last non-task
2594
    // link in the trail is used as page title (see menu_get_active_title()),
2595
    // this condition cannot be cleanly integrated into menu_get_active_trail().
2596
    // menu_get_active_trail() already skips all links that link to their parent
2597
    // (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
2598
    // itself, we always remove the last link in the trail, if the current
2599
    // router item links to its parent.
2600
    if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
2601
      array_pop($active_trail);
2602
    }
2603

    
2604
    foreach ($active_trail as $parent) {
2605
      $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
2606
    }
2607
  }
2608
  return $breadcrumb;
2609
}
2610

    
2611
/**
2612
 * Gets the title of the current page, as determined by the active trail.
2613
 */
2614
function menu_get_active_title() {
2615
  $active_trail = menu_get_active_trail();
2616

    
2617
  foreach (array_reverse($active_trail) as $item) {
2618
    if (!(bool) ($item['type'] & MENU_IS_LOCAL_TASK)) {
2619
      return $item['title'];
2620
    }
2621
  }
2622
}
2623

    
2624
/**
2625
 * Gets a translated, access-checked menu link that is ready for rendering.
2626
 *
2627
 * This function should never be called from within node_load() or any other
2628
 * function used as a menu object load function since an infinite recursion may
2629
 * occur.
2630
 *
2631
 * @param $mlid
2632
 *   The mlid of the menu item.
2633
 *
2634
 * @return
2635
 *   A menu link, with $item['access'] filled and link translated for
2636
 *   rendering.
2637
 */
2638
function menu_link_load($mlid) {
2639
  if (is_numeric($mlid)) {
2640
    $query = db_select('menu_links', 'ml');
2641
    $query->leftJoin('menu_router', 'm', 'm.path = ml.router_path');
2642
    $query->fields('ml');
2643
    // Weight should be taken from {menu_links}, not {menu_router}.
2644
    $query->addField('ml', 'weight', 'link_weight');
2645
    $query->fields('m');
2646
    $query->condition('ml.mlid', $mlid);
2647
    if ($item = $query->execute()->fetchAssoc()) {
2648
      $item['weight'] = $item['link_weight'];
2649
      _menu_link_translate($item);
2650
      return $item;
2651
    }
2652
  }
2653
  return FALSE;
2654
}
2655

    
2656
/**
2657
 * Clears the cached cached data for a single named menu.
2658
 */
2659
function menu_cache_clear($menu_name = 'navigation') {
2660
  $cache_cleared = &drupal_static(__FUNCTION__, array());
2661

    
2662
  if (empty($cache_cleared[$menu_name])) {
2663
    cache_clear_all('links:' . $menu_name . ':', 'cache_menu', TRUE);
2664
    $cache_cleared[$menu_name] = 1;
2665
  }
2666
  elseif ($cache_cleared[$menu_name] == 1) {
2667
    drupal_register_shutdown_function('cache_clear_all', 'links:' . $menu_name . ':', 'cache_menu', TRUE);
2668
    $cache_cleared[$menu_name] = 2;
2669
  }
2670

    
2671
  // Also clear the menu system static caches.
2672
  menu_reset_static_cache();
2673
}
2674

    
2675
/**
2676
 * Clears all cached menu data.
2677
 *
2678
 * This should be called any time broad changes
2679
 * might have been made to the router items or menu links.
2680
 */
2681
function menu_cache_clear_all() {
2682
  cache_clear_all('*', 'cache_menu', TRUE);
2683
  menu_reset_static_cache();
2684
}
2685

    
2686
/**
2687
 * Resets the menu system static cache.
2688
 */
2689
function menu_reset_static_cache() {
2690
  drupal_static_reset('_menu_build_tree');
2691
  drupal_static_reset('menu_tree');
2692
  drupal_static_reset('menu_tree_all_data');
2693
  drupal_static_reset('menu_tree_page_data');
2694
  drupal_static_reset('menu_load_all');
2695
  drupal_static_reset('menu_link_get_preferred');
2696
}
2697

    
2698
/**
2699
 * Checks whether a menu_rebuild() is necessary.
2700
 */
2701
function _menu_check_rebuild() {
2702
  // To absolutely ensure that the menu rebuild is required, re-load the
2703
  // variables in case they were set by another process.
2704
  $variables = variable_initialize();
2705
  if (empty($variables['menu_rebuild_needed']) && !empty($variables['menu_masks'])) {
2706
    unset($GLOBALS['conf']['menu_rebuild_needed']);
2707
    $GLOBALS['conf']['menu_masks'] = $variables['menu_masks'];
2708
    return FALSE;
2709
  }
2710
  return TRUE;
2711
}
2712

    
2713
/**
2714
 * Populates the database tables used by various menu functions.
2715
 *
2716
 * This function will clear and populate the {menu_router} table, add entries
2717
 * to {menu_links} for new router items, and then remove stale items from
2718
 * {menu_links}. If called from update.php or install.php, it will also
2719
 * schedule a call to itself on the first real page load from
2720
 * menu_execute_active_handler(), because the maintenance page environment
2721
 * is different and leaves stale data in the menu tables.
2722
 *
2723
 * @return
2724
 *   TRUE if the menu was rebuilt, FALSE if another thread was rebuilding
2725
 *   in parallel and the current thread just waited for completion.
2726
 */
2727
function menu_rebuild() {
2728
  if (!lock_acquire('menu_rebuild')) {
2729
    // Wait for another request that is already doing this work.
2730
    // We choose to block here since otherwise the router item may not
2731
    // be available in menu_execute_active_handler() resulting in a 404.
2732
    lock_wait('menu_rebuild');
2733

    
2734
    if (_menu_check_rebuild()) {
2735
      // If we get here and menu_masks was not set, then it is possible a menu
2736
      // is being reloaded, or that the process rebuilding the menu was unable
2737
      // to complete successfully. A missing menu_masks variable could result
2738
      // in a 404, so re-run the function.
2739
      return menu_rebuild();
2740
    }
2741
    return FALSE;
2742
  }
2743

    
2744
  $transaction = db_transaction();
2745

    
2746
  try {
2747
    list($menu, $masks) = menu_router_build();
2748
    _menu_router_save($menu, $masks);
2749
    _menu_navigation_links_rebuild($menu);
2750
    // Clear the menu, page and block caches.
2751
    menu_cache_clear_all();
2752
    _menu_clear_page_cache();
2753

    
2754
    if (defined('MAINTENANCE_MODE')) {
2755
      variable_set('menu_rebuild_needed', TRUE);
2756
    }
2757
    else {
2758
      variable_del('menu_rebuild_needed');
2759
    }
2760
  }
2761
  catch (Exception $e) {
2762
    $transaction->rollback();
2763
    watchdog_exception('menu', $e);
2764
  }
2765
  // Explicitly commit the transaction now; this ensures that the database
2766
  // operations during the menu rebuild are committed before the lock is made
2767
  // available again, since locks may not always reside in the same database
2768
  // connection. The lock is acquired outside of the transaction so should also
2769
  // be released outside of it.
2770
  unset($transaction);
2771

    
2772
  lock_release('menu_rebuild');
2773
  return TRUE;
2774
}
2775

    
2776
/**
2777
 * Collects and alters the menu definitions.
2778
 */
2779
function menu_router_build() {
2780
  // We need to manually call each module so that we can know which module
2781
  // a given item came from.
2782
  $callbacks = array();
2783
  foreach (module_implements('menu') as $module) {
2784
    $router_items = call_user_func($module . '_menu');
2785
    if (isset($router_items) && is_array($router_items)) {
2786
      foreach (array_keys($router_items) as $path) {
2787
        $router_items[$path]['module'] = $module;
2788
      }
2789
      $callbacks = array_merge($callbacks, $router_items);
2790
    }
2791
  }
2792
  // Alter the menu as defined in modules, keys are like user/%user.
2793
  drupal_alter('menu', $callbacks);
2794
  list($menu, $masks) = _menu_router_build($callbacks);
2795
  _menu_router_cache($menu);
2796

    
2797
  return array($menu, $masks);
2798
}
2799

    
2800
/**
2801
 * Stores the menu router if we have it in memory.
2802
 */
2803
function _menu_router_cache($new_menu = NULL) {
2804
  $menu = &drupal_static(__FUNCTION__);
2805

    
2806
  if (isset($new_menu)) {
2807
    $menu = $new_menu;
2808
  }
2809
  return $menu;
2810
}
2811

    
2812
/**
2813
 * Gets the menu router.
2814
 */
2815
function menu_get_router() {
2816
  // Check first if we have it in memory already.
2817
  $menu = _menu_router_cache();
2818
  if (empty($menu)) {
2819
    list($menu, $masks) = menu_router_build();
2820
  }
2821
  return $menu;
2822
}
2823

    
2824
/**
2825
 * Builds a link from a router item.
2826
 */
2827
function _menu_link_build($item) {
2828
  // Suggested items are disabled by default.
2829
  if ($item['type'] == MENU_SUGGESTED_ITEM) {
2830
    $item['hidden'] = 1;
2831
  }
2832
  // Hide all items that are not visible in the tree.
2833
  elseif (!($item['type'] & MENU_VISIBLE_IN_TREE)) {
2834
    $item['hidden'] = -1;
2835
  }
2836
  // Note, we set this as 'system', so that we can be sure to distinguish all
2837
  // the menu links generated automatically from entries in {menu_router}.
2838
  $item['module'] = 'system';
2839
  $item += array(
2840
    'menu_name' => 'navigation',
2841
    'link_title' => $item['title'],
2842
    'link_path' => $item['path'],
2843
    'hidden' => 0,
2844
    'options' => empty($item['description']) ? array() : array('attributes' => array('title' => $item['description'])),
2845
  );
2846
  return $item;
2847
}
2848

    
2849
/**
2850
 * Builds menu links for the items in the menu router.
2851
 */
2852
function _menu_navigation_links_rebuild($menu) {
2853
  // Add normal and suggested items as links.
2854
  $menu_links = array();
2855
  foreach ($menu as $path => $item) {
2856
    if ($item['_visible']) {
2857
      $menu_links[$path] = $item;
2858
      $sort[$path] = $item['_number_parts'];
2859
    }
2860
  }
2861
  if ($menu_links) {
2862
    // Keep an array of processed menu links, to allow menu_link_save() to
2863
    // check this for parents instead of querying the database.
2864
    $parent_candidates = array();
2865
    // Make sure no child comes before its parent.
2866
    array_multisort($sort, SORT_NUMERIC, $menu_links);
2867

    
2868
    foreach ($menu_links as $key => $item) {
2869
      $existing_item = db_select('menu_links')
2870
        ->fields('menu_links')
2871
        ->condition('link_path', $item['path'])
2872
        ->condition('module', 'system')
2873
        ->execute()->fetchAssoc();
2874
      if ($existing_item) {
2875
        $item['mlid'] = $existing_item['mlid'];
2876
        // A change in hook_menu may move the link to a different menu
2877
        if (empty($item['menu_name']) || ($item['menu_name'] == $existing_item['menu_name'])) {
2878
          $item['menu_name'] = $existing_item['menu_name'];
2879
          $item['plid'] = $existing_item['plid'];
2880
        }
2881
        else {
2882
          // It moved to a new menu. Let menu_link_save() try to find a new
2883
          // parent based on the path.
2884
          unset($item['plid']);
2885
        }
2886
        $item['has_children'] = $existing_item['has_children'];
2887
        $item['updated'] = $existing_item['updated'];
2888
      }
2889
      if ($existing_item && $existing_item['customized']) {
2890
        $parent_candidates[$existing_item['mlid']] = $existing_item;
2891
      }
2892
      else {
2893
        $item = _menu_link_build($item);
2894
        menu_link_save($item, $existing_item, $parent_candidates);
2895
        $parent_candidates[$item['mlid']] = $item;
2896
        unset($menu_links[$key]);
2897
      }
2898
    }
2899
  }
2900
  $paths = array_keys($menu);
2901
  // Updated and customized items whose router paths are gone need new ones.
2902
  $result = db_select('menu_links', NULL, array('fetch' => PDO::FETCH_ASSOC))
2903
    ->fields('menu_links', array(
2904
      'link_path',
2905
      'mlid',
2906
      'router_path',
2907
      'updated',
2908
    ))
2909
    ->condition(db_or()
2910
      ->condition('updated', 1)
2911
      ->condition(db_and()
2912
        ->condition('router_path', $paths, 'NOT IN')
2913
        ->condition('external', 0)
2914
        ->condition('customized', 1)
2915
      )
2916
    )
2917
    ->execute();
2918
  foreach ($result as $item) {
2919
    $router_path = _menu_find_router_path($item['link_path']);
2920
    if (!empty($router_path) && ($router_path != $item['router_path'] || $item['updated'])) {
2921
      // If the router path and the link path matches, it's surely a working
2922
      // item, so we clear the updated flag.
2923
      $updated = $item['updated'] && $router_path != $item['link_path'];
2924
      db_update('menu_links')
2925
        ->fields(array(
2926
          'router_path' => $router_path,
2927
          'updated' => (int) $updated,
2928
        ))
2929
        ->condition('mlid', $item['mlid'])
2930
        ->execute();
2931
    }
2932
  }
2933
  // Find any item whose router path does not exist any more.
2934
  $result = db_select('menu_links')
2935
    ->fields('menu_links')
2936
    ->condition('router_path', $paths, 'NOT IN')
2937
    ->condition('external', 0)
2938
    ->condition('updated', 0)
2939
    ->condition('customized', 0)
2940
    ->orderBy('depth', 'DESC')
2941
    ->execute();
2942
  // Remove all such items. Starting from those with the greatest depth will
2943
  // minimize the amount of re-parenting done by menu_link_delete().
2944
  foreach ($result as $item) {
2945
    _menu_delete_item($item, TRUE);
2946
  }
2947
}
2948

    
2949
/**
2950
 * Clones an array of menu links.
2951
 *
2952
 * @param $links
2953
 *   An array of menu links to clone.
2954
 * @param $menu_name
2955
 *   (optional) The name of a menu that the links will be cloned for. If not
2956
 *   set, the cloned links will be in the same menu as the original set of
2957
 *   links that were passed in.
2958
 *
2959
 * @return
2960
 *   An array of menu links with the same properties as the passed-in array,
2961
 *   but with the link identifiers removed so that a new link will be created
2962
 *   when any of them is passed in to menu_link_save().
2963
 *
2964
 * @see menu_link_save()
2965
 */
2966
function menu_links_clone($links, $menu_name = NULL) {
2967
  foreach ($links as &$link) {
2968
    unset($link['mlid']);
2969
    unset($link['plid']);
2970
    if (isset($menu_name)) {
2971
      $link['menu_name'] = $menu_name;
2972
    }
2973
  }
2974
  return $links;
2975
}
2976

    
2977
/**
2978
 * Returns an array containing all links for a menu.
2979
 *
2980
 * @param $menu_name
2981
 *   The name of the menu whose links should be returned.
2982
 *
2983
 * @return
2984
 *   An array of menu links.
2985
 */
2986
function menu_load_links($menu_name) {
2987
  $links = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC))
2988
    ->fields('ml')
2989
    ->condition('ml.menu_name', $menu_name)
2990
    // Order by weight so as to be helpful for menus that are only one level
2991
    // deep.
2992
    ->orderBy('weight')
2993
    ->execute()
2994
    ->fetchAll();
2995

    
2996
  foreach ($links as &$link) {
2997
    $link['options'] = unserialize($link['options']);
2998
  }
2999
  return $links;
3000
}
3001

    
3002
/**
3003
 * Deletes all links for a menu.
3004
 *
3005
 * @param $menu_name
3006
 *   The name of the menu whose links will be deleted.
3007
 */
3008
function menu_delete_links($menu_name) {
3009
  $links = menu_load_links($menu_name);
3010
  foreach ($links as $link) {
3011
    // To speed up the deletion process, we reset some link properties that
3012
    // would trigger re-parenting logic in _menu_delete_item() and
3013
    // _menu_update_parental_status().
3014
    $link['has_children'] = FALSE;
3015
    $link['plid'] = 0;
3016
    _menu_delete_item($link);
3017
  }
3018
}
3019

    
3020
/**
3021
 * Delete one or several menu links.
3022
 *
3023
 * @param $mlid
3024
 *   A valid menu link mlid or NULL. If NULL, $path is used.
3025
 * @param $path
3026
 *   The path to the menu items to be deleted. $mlid must be NULL.
3027
 */
3028
function menu_link_delete($mlid, $path = NULL) {
3029
  if (isset($mlid)) {
3030
    _menu_delete_item(db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc());
3031
  }
3032
  else {
3033
    $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $path));
3034
    foreach ($result as $link) {
3035
      _menu_delete_item($link);
3036
    }
3037
  }
3038
}
3039

    
3040
/**
3041
 * Deletes a single menu link.
3042
 *
3043
 * @param $item
3044
 *   Item to be deleted.
3045
 * @param $force
3046
 *   Forces deletion. Internal use only, setting to TRUE is discouraged.
3047
 *
3048
 * @see menu_link_delete()
3049
 */
3050
function _menu_delete_item($item, $force = FALSE) {
3051
  $item = is_object($item) ? get_object_vars($item) : $item;
3052
  if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) {
3053
    // Children get re-attached to the item's parent.
3054
    if ($item['has_children']) {
3055
      $result = db_query("SELECT mlid FROM {menu_links} WHERE plid = :plid", array(':plid' => $item['mlid']));
3056
      foreach ($result as $m) {
3057
        $child = menu_link_load($m->mlid);
3058
        $child['plid'] = $item['plid'];
3059
        menu_link_save($child);
3060
      }
3061
    }
3062

    
3063
    // Notify modules we are deleting the item.
3064
    module_invoke_all('menu_link_delete', $item);
3065

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

    
3068
    // Update the has_children status of the parent.
3069
    _menu_update_parental_status($item);
3070
    menu_cache_clear($item['menu_name']);
3071
    _menu_clear_page_cache();
3072
  }
3073
}
3074

    
3075
/**
3076
 * Saves a menu link.
3077
 *
3078
 * After calling this function, rebuild the menu cache using
3079
 * menu_cache_clear_all().
3080
 *
3081
 * @param $item
3082
 *   An associative array representing a menu link item, with elements:
3083
 *   - link_path: (required) The path of the menu item, which should be
3084
 *     normalized first by calling drupal_get_normal_path() on it.
3085
 *   - link_title: (required) Title to appear in menu for the link.
3086
 *   - menu_name: (optional) The machine name of the menu for the link.
3087
 *     Defaults to 'navigation'.
3088
 *   - weight: (optional) Integer to determine position in menu. Default is 0.
3089
 *   - expanded: (optional) Boolean that determines if the item is expanded.
3090
 *   - options: (optional) An array of options, see l() for more.
3091
 *   - mlid: (optional) Menu link identifier, the primary integer key for each
3092
 *     menu link. Can be set to an existing value, or to 0 or NULL
3093
 *     to insert a new link.
3094
 *   - plid: (optional) The mlid of the parent.
3095
 *   - router_path: (optional) The path of the relevant router item.
3096
 * @param $existing_item
3097
 *   Optional, the current record from the {menu_links} table as an array.
3098
 * @param $parent_candidates
3099
 *   Optional array of menu links keyed by mlid. Used by
3100
 *   _menu_navigation_links_rebuild() only.
3101
 *
3102
 * @return
3103
 *   The mlid of the saved menu link, or FALSE if the menu link could not be
3104
 *   saved.
3105
 */
3106
function menu_link_save(&$item, $existing_item = array(), $parent_candidates = array()) {
3107
  drupal_alter('menu_link', $item);
3108

    
3109
  // This is the easiest way to handle the unique internal path '<front>',
3110
  // since a path marked as external does not need to match a router path.
3111
  $item['external'] = (url_is_external($item['link_path'])  || $item['link_path'] == '<front>') ? 1 : 0;
3112
  // Load defaults.
3113
  $item += array(
3114
    'menu_name' => 'navigation',
3115
    'weight' => 0,
3116
    'link_title' => '',
3117
    'hidden' => 0,
3118
    'has_children' => 0,
3119
    'expanded' => 0,
3120
    'options' => array(),
3121
    'module' => 'menu',
3122
    'customized' => 0,
3123
    'updated' => 0,
3124
  );
3125
  if (isset($item['mlid'])) {
3126
    if (!$existing_item) {
3127
      $existing_item = db_query('SELECT * FROM {menu_links} WHERE mlid = :mlid', array('mlid' => $item['mlid']))->fetchAssoc();
3128
    }
3129
    if ($existing_item) {
3130
      $existing_item['options'] = unserialize($existing_item['options']);
3131
    }
3132
  }
3133
  else {
3134
    $existing_item = FALSE;
3135
  }
3136

    
3137
  // Try to find a parent link. If found, assign it and derive its menu.
3138
  $parent = _menu_link_find_parent($item, $parent_candidates);
3139
  if (!empty($parent['mlid'])) {
3140
    $item['plid'] = $parent['mlid'];
3141
    $item['menu_name'] = $parent['menu_name'];
3142
  }
3143
  // If no corresponding parent link was found, move the link to the top-level.
3144
  else {
3145
    $item['plid'] = 0;
3146
  }
3147
  $menu_name = $item['menu_name'];
3148

    
3149
  if (!$existing_item) {
3150
    $item['mlid'] = db_insert('menu_links')
3151
      ->fields(array(
3152
        'menu_name' => $item['menu_name'],
3153
        'plid' => $item['plid'],
3154
        'link_path' => $item['link_path'],
3155
        'hidden' => $item['hidden'],
3156
        'external' => $item['external'],
3157
        'has_children' => $item['has_children'],
3158
        'expanded' => $item['expanded'],
3159
        'weight' => $item['weight'],
3160
        'module' => $item['module'],
3161
        'link_title' => $item['link_title'],
3162
        'options' => serialize($item['options']),
3163
        'customized' => $item['customized'],
3164
        'updated' => $item['updated'],
3165
      ))
3166
      ->execute();
3167
  }
3168

    
3169
  // Directly fill parents for top-level links.
3170
  if ($item['plid'] == 0) {
3171
    $item['p1'] = $item['mlid'];
3172
    for ($i = 2; $i <= MENU_MAX_DEPTH; $i++) {
3173
      $item["p$i"] = 0;
3174
    }
3175
    $item['depth'] = 1;
3176
  }
3177
  // Otherwise, ensure that this link's depth is not beyond the maximum depth
3178
  // and fill parents based on the parent link.
3179
  else {
3180
    if ($item['has_children'] && $existing_item) {
3181
      $limit = MENU_MAX_DEPTH - menu_link_children_relative_depth($existing_item) - 1;
3182
    }
3183
    else {
3184
      $limit = MENU_MAX_DEPTH - 1;
3185
    }
3186
    if ($parent['depth'] > $limit) {
3187
      return FALSE;
3188
    }
3189
    $item['depth'] = $parent['depth'] + 1;
3190
    _menu_link_parents_set($item, $parent);
3191
  }
3192
  // Need to check both plid and menu_name, since plid can be 0 in any menu.
3193
  if ($existing_item && ($item['plid'] != $existing_item['plid'] || $menu_name != $existing_item['menu_name'])) {
3194
    _menu_link_move_children($item, $existing_item);
3195
  }
3196
  // Find the router_path.
3197
  if (empty($item['router_path'])  || !$existing_item || ($existing_item['link_path'] != $item['link_path'])) {
3198
    if ($item['external']) {
3199
      $item['router_path'] = '';
3200
    }
3201
    else {
3202
      // Find the router path which will serve this path.
3203
      $item['parts'] = explode('/', $item['link_path'], MENU_MAX_PARTS);
3204
      $item['router_path'] = _menu_find_router_path($item['link_path']);
3205
    }
3206
  }
3207
  // If every value in $existing_item is the same in the $item, there is no
3208
  // reason to run the update queries or clear the caches. We use
3209
  // array_intersect_key() with the $item as the first parameter because
3210
  // $item may have additional keys left over from building a router entry.
3211
  // The intersect removes the extra keys, allowing a meaningful comparison.
3212
  if (!$existing_item || (array_intersect_key($item, $existing_item) != $existing_item)) {
3213
    db_update('menu_links')
3214
      ->fields(array(
3215
        'menu_name' => $item['menu_name'],
3216
        'plid' => $item['plid'],
3217
        'link_path' => $item['link_path'],
3218
        'router_path' => $item['router_path'],
3219
        'hidden' => $item['hidden'],
3220
        'external' => $item['external'],
3221
        'has_children' => $item['has_children'],
3222
        'expanded' => $item['expanded'],
3223
        'weight' => $item['weight'],
3224
        'depth' => $item['depth'],
3225
        'p1' => $item['p1'],
3226
        'p2' => $item['p2'],
3227
        'p3' => $item['p3'],
3228
        'p4' => $item['p4'],
3229
        'p5' => $item['p5'],
3230
        'p6' => $item['p6'],
3231
        'p7' => $item['p7'],
3232
        'p8' => $item['p8'],
3233
        'p9' => $item['p9'],
3234
        'module' => $item['module'],
3235
        'link_title' => $item['link_title'],
3236
        'options' => serialize($item['options']),
3237
        'customized' => $item['customized'],
3238
      ))
3239
      ->condition('mlid', $item['mlid'])
3240
      ->execute();
3241
    // Check the has_children status of the parent.
3242
    _menu_update_parental_status($item);
3243
    menu_cache_clear($menu_name);
3244
    if ($existing_item && $menu_name != $existing_item['menu_name']) {
3245
      menu_cache_clear($existing_item['menu_name']);
3246
    }
3247
    // Notify modules we have acted on a menu item.
3248
    $hook = 'menu_link_insert';
3249
    if ($existing_item) {
3250
      $hook = 'menu_link_update';
3251
    }
3252
    module_invoke_all($hook, $item);
3253
    // Now clear the cache.
3254
    _menu_clear_page_cache();
3255
  }
3256
  return $item['mlid'];
3257
}
3258

    
3259
/**
3260
 * Finds a possible parent for a given menu link.
3261
 *
3262
 * Because the parent of a given link might not exist anymore in the database,
3263
 * we apply a set of heuristics to determine a proper parent:
3264
 *
3265
 *  - use the passed parent link if specified and existing.
3266
 *  - else, use the first existing link down the previous link hierarchy
3267
 *  - else, for system menu links (derived from hook_menu()), reparent
3268
 *    based on the path hierarchy.
3269
 *
3270
 * @param $menu_link
3271
 *   A menu link.
3272
 * @param $parent_candidates
3273
 *   An array of menu links keyed by mlid.
3274
 *
3275
 * @return
3276
 *   A menu link structure of the possible parent or FALSE if no valid parent
3277
 *   has been found.
3278
 */
3279
function _menu_link_find_parent($menu_link, $parent_candidates = array()) {
3280
  $parent = FALSE;
3281

    
3282
  // This item is explicitely top-level, skip the rest of the parenting.
3283
  if (isset($menu_link['plid']) && empty($menu_link['plid'])) {
3284
    return $parent;
3285
  }
3286

    
3287
  // If we have a parent link ID, try to use that.
3288
  $candidates = array();
3289
  if (isset($menu_link['plid'])) {
3290
    $candidates[] = $menu_link['plid'];
3291
  }
3292

    
3293
  // Else, if we have a link hierarchy try to find a valid parent in there.
3294
  if (!empty($menu_link['depth']) && $menu_link['depth'] > 1) {
3295
    for ($depth = $menu_link['depth'] - 1; $depth >= 1; $depth--) {
3296
      $candidates[] = $menu_link['p' . $depth];
3297
    }
3298
  }
3299

    
3300
  foreach ($candidates as $mlid) {
3301
    if (isset($parent_candidates[$mlid])) {
3302
      $parent = $parent_candidates[$mlid];
3303
    }
3304
    else {
3305
      $parent = db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc();
3306
    }
3307
    if ($parent) {
3308
      return $parent;
3309
    }
3310
  }
3311

    
3312
  // If everything else failed, try to derive the parent from the path
3313
  // hierarchy. This only makes sense for links derived from menu router
3314
  // items (ie. from hook_menu()).
3315
  if ($menu_link['module'] == 'system') {
3316
    $query = db_select('menu_links');
3317
    $query->condition('module', 'system');
3318
    // We always respect the link's 'menu_name'; inheritance for router items is
3319
    // ensured in _menu_router_build().
3320
    $query->condition('menu_name', $menu_link['menu_name']);
3321

    
3322
    // Find the parent - it must be unique.
3323
    $parent_path = $menu_link['link_path'];
3324
    do {
3325
      $parent = FALSE;
3326
      $parent_path = substr($parent_path, 0, strrpos($parent_path, '/'));
3327
      $new_query = clone $query;
3328
      $new_query->condition('link_path', $parent_path);
3329
      // Only valid if we get a unique result.
3330
      if ($new_query->countQuery()->execute()->fetchField() == 1) {
3331
        $parent = $new_query->fields('menu_links')->execute()->fetchAssoc();
3332
      }
3333
    } while ($parent === FALSE && $parent_path);
3334
  }
3335

    
3336
  return $parent;
3337
}
3338

    
3339
/**
3340
 * Clears the page and block caches at most twice per page load.
3341
 */
3342
function _menu_clear_page_cache() {
3343
  $cache_cleared = &drupal_static(__FUNCTION__, 0);
3344

    
3345
  // Clear the page and block caches, but at most twice, including at
3346
  //  the end of the page load when there are multiple links saved or deleted.
3347
  if ($cache_cleared == 0) {
3348
    cache_clear_all();
3349
    // Keep track of which menus have expanded items.
3350
    _menu_set_expanded_menus();
3351
    $cache_cleared = 1;
3352
  }
3353
  elseif ($cache_cleared == 1) {
3354
    drupal_register_shutdown_function('cache_clear_all');
3355
    // Keep track of which menus have expanded items.
3356
    drupal_register_shutdown_function('_menu_set_expanded_menus');
3357
    $cache_cleared = 2;
3358
  }
3359
}
3360

    
3361
/**
3362
 * Updates a list of menus with expanded items.
3363
 */
3364
function _menu_set_expanded_menus() {
3365
  $names = db_query("SELECT menu_name FROM {menu_links} WHERE expanded <> 0 GROUP BY menu_name")->fetchCol();
3366
  variable_set('menu_expanded', $names);
3367
}
3368

    
3369
/**
3370
 * Finds the router path which will serve this path.
3371
 *
3372
 * @param $link_path
3373
 *  The path for we are looking up its router path.
3374
 *
3375
 * @return
3376
 *  A path from $menu keys or empty if $link_path points to a nonexisting
3377
 *  place.
3378
 */
3379
function _menu_find_router_path($link_path) {
3380
  // $menu will only have data during a menu rebuild.
3381
  $menu = _menu_router_cache();
3382

    
3383
  $router_path = $link_path;
3384
  $parts = explode('/', $link_path, MENU_MAX_PARTS);
3385
  $ancestors = menu_get_ancestors($parts);
3386

    
3387
  if (empty($menu)) {
3388
    // Not during a menu rebuild, so look up in the database.
3389
    $router_path = (string) db_select('menu_router')
3390
      ->fields('menu_router', array('path'))
3391
      ->condition('path', $ancestors, 'IN')
3392
      ->orderBy('fit', 'DESC')
3393
      ->range(0, 1)
3394
      ->execute()->fetchField();
3395
  }
3396
  elseif (!isset($menu[$router_path])) {
3397
    // Add an empty router path as a fallback.
3398
    $ancestors[] = '';
3399
    foreach ($ancestors as $key => $router_path) {
3400
      if (isset($menu[$router_path])) {
3401
        // Exit the loop leaving $router_path as the first match.
3402
        break;
3403
      }
3404
    }
3405
    // If we did not find the path, $router_path will be the empty string
3406
    // at the end of $ancestors.
3407
  }
3408
  return $router_path;
3409
}
3410

    
3411
/**
3412
 * Inserts, updates, or deletes an uncustomized menu link related to a module.
3413
 *
3414
 * @param $module
3415
 *   The name of the module.
3416
 * @param $op
3417
 *   Operation to perform: insert, update or delete.
3418
 * @param $link_path
3419
 *   The path this link points to.
3420
 * @param $link_title
3421
 *   Title of the link to insert or new title to update the link to.
3422
 *   Unused for delete.
3423
 *
3424
 * @return
3425
 *   The insert op returns the mlid of the new item. Others op return NULL.
3426
 */
3427
function menu_link_maintain($module, $op, $link_path, $link_title) {
3428
  switch ($op) {
3429
    case 'insert':
3430
      $menu_link = array(
3431
        'link_title' => $link_title,
3432
        'link_path' => $link_path,
3433
        'module' => $module,
3434
      );
3435
      return menu_link_save($menu_link);
3436
      break;
3437
    case 'update':
3438
      $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);
3439
      foreach ($result as $link) {
3440
        $link['link_title'] = $link_title;
3441
        $link['options'] = unserialize($link['options']);
3442
        menu_link_save($link);
3443
      }
3444
      break;
3445
    case 'delete':
3446
      menu_link_delete(NULL, $link_path);
3447
      break;
3448
  }
3449
}
3450

    
3451
/**
3452
 * Finds the depth of an item's children relative to its depth.
3453
 *
3454
 * For example, if the item has a depth of 2, and the maximum of any child in
3455
 * the menu link tree is 5, the relative depth is 3.
3456
 *
3457
 * @param $item
3458
 *   An array representing a menu link item.
3459
 *
3460
 * @return
3461
 *   The relative depth, or zero.
3462
 *
3463
 */
3464
function menu_link_children_relative_depth($item) {
3465
  $query = db_select('menu_links');
3466
  $query->addField('menu_links', 'depth');
3467
  $query->condition('menu_name', $item['menu_name']);
3468
  $query->orderBy('depth', 'DESC');
3469
  $query->range(0, 1);
3470

    
3471
  $i = 1;
3472
  $p = 'p1';
3473
  while ($i <= MENU_MAX_DEPTH && $item[$p]) {
3474
    $query->condition($p, $item[$p]);
3475
    $p = 'p' . ++$i;
3476
  }
3477

    
3478
  $max_depth = $query->execute()->fetchField();
3479

    
3480
  return ($max_depth > $item['depth']) ? $max_depth - $item['depth'] : 0;
3481
}
3482

    
3483
/**
3484
 * Updates the children of a menu link that is being moved.
3485
 *
3486
 * The menu name, parents (p1 - p6), and depth are updated for all children of
3487
 * the link, and the has_children status of the previous parent is updated.
3488
 */
3489
function _menu_link_move_children($item, $existing_item) {
3490
  $query = db_update('menu_links');
3491

    
3492
  $query->fields(array('menu_name' => $item['menu_name']));
3493

    
3494
  $p = 'p1';
3495
  $expressions = array();
3496
  for ($i = 1; $i <= $item['depth']; $p = 'p' . ++$i) {
3497
    $expressions[] = array($p, ":p_$i", array(":p_$i" => $item[$p]));
3498
  }
3499
  $j = $existing_item['depth'] + 1;
3500
  while ($i <= MENU_MAX_DEPTH && $j <= MENU_MAX_DEPTH) {
3501
    $expressions[] = array('p' . $i++, 'p' . $j++, array());
3502
  }
3503
  while ($i <= MENU_MAX_DEPTH) {
3504
    $expressions[] = array('p' . $i++, 0, array());
3505
  }
3506

    
3507
  $shift = $item['depth'] - $existing_item['depth'];
3508
  if ($shift > 0) {
3509
    // The order of expressions must be reversed so the new values don't
3510
    // overwrite the old ones before they can be used because "Single-table
3511
    // UPDATE assignments are generally evaluated from left to right"
3512
    // see: http://dev.mysql.com/doc/refman/5.0/en/update.html
3513
    $expressions = array_reverse($expressions);
3514
  }
3515
  foreach ($expressions as $expression) {
3516
    $query->expression($expression[0], $expression[1], $expression[2]);
3517
  }
3518

    
3519
  $query->expression('depth', 'depth + :depth', array(':depth' => $shift));
3520
  $query->condition('menu_name', $existing_item['menu_name']);
3521
  $p = 'p1';
3522
  for ($i = 1; $i <= MENU_MAX_DEPTH && $existing_item[$p]; $p = 'p' . ++$i) {
3523
    $query->condition($p, $existing_item[$p]);
3524
  }
3525

    
3526
  $query->execute();
3527

    
3528
  // Check the has_children status of the parent, while excluding this item.
3529
  _menu_update_parental_status($existing_item, TRUE);
3530
}
3531

    
3532
/**
3533
 * Checks and updates the 'has_children' status for the parent of a link.
3534
 */
3535
function _menu_update_parental_status($item, $exclude = FALSE) {
3536
  // If plid == 0, there is nothing to update.
3537
  if ($item['plid']) {
3538
    // Check if at least one visible child exists in the table.
3539
    $query = db_select('menu_links');
3540
    $query->addField('menu_links', 'mlid');
3541
    $query->condition('menu_name', $item['menu_name']);
3542
    $query->condition('hidden', 0);
3543
    $query->condition('plid', $item['plid']);
3544
    $query->range(0, 1);
3545
    if ($exclude) {
3546
      $query->condition('mlid', $item['mlid'], '<>');
3547
    }
3548
    $parent_has_children = ((bool) $query->execute()->fetchField()) ? 1 : 0;
3549
    db_update('menu_links')
3550
      ->fields(array('has_children' => $parent_has_children))
3551
      ->condition('mlid', $item['plid'])
3552
      ->execute();
3553
  }
3554
}
3555

    
3556
/**
3557
 * Sets the p1 through p9 values for a menu link being saved.
3558
 */
3559
function _menu_link_parents_set(&$item, $parent) {
3560
  $i = 1;
3561
  while ($i < $item['depth']) {
3562
    $p = 'p' . $i++;
3563
    $item[$p] = $parent[$p];
3564
  }
3565
  $p = 'p' . $i++;
3566
  // The parent (p1 - p9) corresponding to the depth always equals the mlid.
3567
  $item[$p] = $item['mlid'];
3568
  while ($i <= MENU_MAX_DEPTH) {
3569
    $p = 'p' . $i++;
3570
    $item[$p] = 0;
3571
  }
3572
}
3573

    
3574
/**
3575
 * Builds the router table based on the data from hook_menu().
3576
 */
3577
function _menu_router_build($callbacks) {
3578
  // First pass: separate callbacks from paths, making paths ready for
3579
  // matching. Calculate fitness, and fill some default values.
3580
  $menu = array();
3581
  $masks = array();
3582
  foreach ($callbacks as $path => $item) {
3583
    $load_functions = array();
3584
    $to_arg_functions = array();
3585
    $fit = 0;
3586
    $move = FALSE;
3587

    
3588
    $parts = explode('/', $path, MENU_MAX_PARTS);
3589
    $number_parts = count($parts);
3590
    // We store the highest index of parts here to save some work in the fit
3591
    // calculation loop.
3592
    $slashes = $number_parts - 1;
3593
    // Extract load and to_arg functions.
3594
    foreach ($parts as $k => $part) {
3595
      $match = FALSE;
3596
      // Look for wildcards in the form allowed to be used in PHP functions,
3597
      // because we are using these to construct the load function names.
3598
      if (preg_match('/^%(|' . DRUPAL_PHP_FUNCTION_PATTERN . ')$/', $part, $matches)) {
3599
        if (empty($matches[1])) {
3600
          $match = TRUE;
3601
          $load_functions[$k] = NULL;
3602
        }
3603
        else {
3604
          if (function_exists($matches[1] . '_to_arg')) {
3605
            $to_arg_functions[$k] = $matches[1] . '_to_arg';
3606
            $load_functions[$k] = NULL;
3607
            $match = TRUE;
3608
          }
3609
          if (function_exists($matches[1] . '_load')) {
3610
            $function = $matches[1] . '_load';
3611
            // Create an array of arguments that will be passed to the _load
3612
            // function when this menu path is checked, if 'load arguments'
3613
            // exists.
3614
            $load_functions[$k] = isset($item['load arguments']) ? array($function => $item['load arguments']) : $function;
3615
            $match = TRUE;
3616
          }
3617
        }
3618
      }
3619
      if ($match) {
3620
        $parts[$k] = '%';
3621
      }
3622
      else {
3623
        $fit |=  1 << ($slashes - $k);
3624
      }
3625
    }
3626
    if ($fit) {
3627
      $move = TRUE;
3628
    }
3629
    else {
3630
      // If there is no %, it fits maximally.
3631
      $fit = (1 << $number_parts) - 1;
3632
    }
3633
    $masks[$fit] = 1;
3634
    $item['_load_functions'] = $load_functions;
3635
    $item['to_arg_functions'] = empty($to_arg_functions) ? '' : serialize($to_arg_functions);
3636
    $item += array(
3637
      'title' => '',
3638
      'weight' => 0,
3639
      'type' => MENU_NORMAL_ITEM,
3640
      'module' => '',
3641
      '_number_parts' => $number_parts,
3642
      '_parts' => $parts,
3643
      '_fit' => $fit,
3644
    );
3645
    $item += array(
3646
      '_visible' => (bool) ($item['type'] & MENU_VISIBLE_IN_BREADCRUMB),
3647
      '_tab' => (bool) ($item['type'] & MENU_IS_LOCAL_TASK),
3648
    );
3649
    if ($move) {
3650
      $new_path = implode('/', $item['_parts']);
3651
      $menu[$new_path] = $item;
3652
      $sort[$new_path] = $number_parts;
3653
    }
3654
    else {
3655
      $menu[$path] = $item;
3656
      $sort[$path] = $number_parts;
3657
    }
3658
  }
3659
  array_multisort($sort, SORT_NUMERIC, $menu);
3660
  // Apply inheritance rules.
3661
  foreach ($menu as $path => $v) {
3662
    $item = &$menu[$path];
3663
    if (!$item['_tab']) {
3664
      // Non-tab items.
3665
      $item['tab_parent'] = '';
3666
      $item['tab_root'] = $path;
3667
    }
3668
    // If not specified, assign the default tab type for local tasks.
3669
    elseif (!isset($item['context'])) {
3670
      $item['context'] = MENU_CONTEXT_PAGE;
3671
    }
3672
    for ($i = $item['_number_parts'] - 1; $i; $i--) {
3673
      $parent_path = implode('/', array_slice($item['_parts'], 0, $i));
3674
      if (isset($menu[$parent_path])) {
3675

    
3676
        $parent = &$menu[$parent_path];
3677

    
3678
        // If we have no menu name, try to inherit it from parent items.
3679
        if (!isset($item['menu_name'])) {
3680
          // If the parent item of this item does not define a menu name (and no
3681
          // previous iteration assigned one already), try to find the menu name
3682
          // of the parent item in the currently stored menu links.
3683
          if (!isset($parent['menu_name'])) {
3684
            $menu_name = db_query("SELECT menu_name FROM {menu_links} WHERE router_path = :router_path AND module = 'system'", array(':router_path' => $parent_path))->fetchField();
3685
            if ($menu_name) {
3686
              $parent['menu_name'] = $menu_name;
3687
            }
3688
          }
3689
          // If the parent item defines a menu name, inherit it.
3690
          if (!empty($parent['menu_name'])) {
3691
            $item['menu_name'] = $parent['menu_name'];
3692
          }
3693
        }
3694
        if (!isset($item['tab_parent'])) {
3695
          // Parent stores the parent of the path.
3696
          $item['tab_parent'] = $parent_path;
3697
        }
3698
        if (!isset($item['tab_root']) && !$parent['_tab']) {
3699
          $item['tab_root'] = $parent_path;
3700
        }
3701
        // If an access callback is not found for a default local task we use
3702
        // the callback from the parent, since we expect them to be identical.
3703
        // In all other cases, the access parameters must be specified.
3704
        if (($item['type'] == MENU_DEFAULT_LOCAL_TASK) && !isset($item['access callback']) && isset($parent['access callback'])) {
3705
          $item['access callback'] = $parent['access callback'];
3706
          if (!isset($item['access arguments']) && isset($parent['access arguments'])) {
3707
            $item['access arguments'] = $parent['access arguments'];
3708
          }
3709
        }
3710
        // Same for page callbacks.
3711
        if (!isset($item['page callback']) && isset($parent['page callback'])) {
3712
          $item['page callback'] = $parent['page callback'];
3713
          if (!isset($item['page arguments']) && isset($parent['page arguments'])) {
3714
            $item['page arguments'] = $parent['page arguments'];
3715
          }
3716
          if (!isset($item['file path']) && isset($parent['file path'])) {
3717
            $item['file path'] = $parent['file path'];
3718
          }
3719
          if (!isset($item['file']) && isset($parent['file'])) {
3720
            $item['file'] = $parent['file'];
3721
            if (empty($item['file path']) && isset($item['module']) && isset($parent['module']) && $item['module'] != $parent['module']) {
3722
              $item['file path'] = drupal_get_path('module', $parent['module']);
3723
            }
3724
          }
3725
        }
3726
        // Same for delivery callbacks.
3727
        if (!isset($item['delivery callback']) && isset($parent['delivery callback'])) {
3728
          $item['delivery callback'] = $parent['delivery callback'];
3729
        }
3730
        // Same for theme callbacks.
3731
        if (!isset($item['theme callback']) && isset($parent['theme callback'])) {
3732
          $item['theme callback'] = $parent['theme callback'];
3733
          if (!isset($item['theme arguments']) && isset($parent['theme arguments'])) {
3734
            $item['theme arguments'] = $parent['theme arguments'];
3735
          }
3736
        }
3737
        // Same for load arguments: if a loader doesn't have any explict
3738
        // arguments, try to find arguments in the parent.
3739
        if (!isset($item['load arguments'])) {
3740
          foreach ($item['_load_functions'] as $k => $function) {
3741
            // This loader doesn't have any explict arguments...
3742
            if (!is_array($function)) {
3743
              // ... check the parent for a loader at the same position
3744
              // using the same function name and defining arguments...
3745
              if (isset($parent['_load_functions'][$k]) && is_array($parent['_load_functions'][$k]) && key($parent['_load_functions'][$k]) === $function) {
3746
                // ... and inherit the arguments on the child.
3747
                $item['_load_functions'][$k] = $parent['_load_functions'][$k];
3748
              }
3749
            }
3750
          }
3751
        }
3752
      }
3753
    }
3754
    if (!isset($item['access callback']) && isset($item['access arguments'])) {
3755
      // Default callback.
3756
      $item['access callback'] = 'user_access';
3757
    }
3758
    if (!isset($item['access callback']) || empty($item['page callback'])) {
3759
      $item['access callback'] = 0;
3760
    }
3761
    if (is_bool($item['access callback'])) {
3762
      $item['access callback'] = intval($item['access callback']);
3763
    }
3764

    
3765
    $item['load_functions'] = empty($item['_load_functions']) ? '' : serialize($item['_load_functions']);
3766
    $item += array(
3767
      'access arguments' => array(),
3768
      'access callback' => '',
3769
      'page arguments' => array(),
3770
      'page callback' => '',
3771
      'delivery callback' => '',
3772
      'title arguments' => array(),
3773
      'title callback' => 't',
3774
      'theme arguments' => array(),
3775
      'theme callback' => '',
3776
      'description' => '',
3777
      'position' => '',
3778
      'context' => 0,
3779
      'tab_parent' => '',
3780
      'tab_root' => $path,
3781
      'path' => $path,
3782
      'file' => '',
3783
      'file path' => '',
3784
      'include file' => '',
3785
    );
3786

    
3787
    // Calculate out the file to be included for each callback, if any.
3788
    if ($item['file']) {
3789
      $file_path = $item['file path'] ? $item['file path'] : drupal_get_path('module', $item['module']);
3790
      $item['include file'] = $file_path . '/' . $item['file'];
3791
    }
3792
  }
3793

    
3794
  // Sort the masks so they are in order of descending fit.
3795
  $masks = array_keys($masks);
3796
  rsort($masks);
3797

    
3798
  return array($menu, $masks);
3799
}
3800

    
3801
/**
3802
 * Saves data from menu_router_build() to the router table.
3803
 */
3804
function _menu_router_save($menu, $masks) {
3805
  // Delete the existing router since we have some data to replace it.
3806
  db_truncate('menu_router')->execute();
3807

    
3808
  // Prepare insert object.
3809
  $insert = db_insert('menu_router')
3810
    ->fields(array(
3811
      'path',
3812
      'load_functions',
3813
      'to_arg_functions',
3814
      'access_callback',
3815
      'access_arguments',
3816
      'page_callback',
3817
      'page_arguments',
3818
      'delivery_callback',
3819
      'fit',
3820
      'number_parts',
3821
      'context',
3822
      'tab_parent',
3823
      'tab_root',
3824
      'title',
3825
      'title_callback',
3826
      'title_arguments',
3827
      'theme_callback',
3828
      'theme_arguments',
3829
      'type',
3830
      'description',
3831
      'position',
3832
      'weight',
3833
      'include_file',
3834
    ));
3835

    
3836
  $num_records = 0;
3837

    
3838
  foreach ($menu as $path => $item) {
3839
    // Fill in insert object values.
3840
    $insert->values(array(
3841
      'path' => $item['path'],
3842
      'load_functions' => $item['load_functions'],
3843
      'to_arg_functions' => $item['to_arg_functions'],
3844
      'access_callback' => $item['access callback'],
3845
      'access_arguments' => serialize($item['access arguments']),
3846
      'page_callback' => $item['page callback'],
3847
      'page_arguments' => serialize($item['page arguments']),
3848
      'delivery_callback' => $item['delivery callback'],
3849
      'fit' => $item['_fit'],
3850
      'number_parts' => $item['_number_parts'],
3851
      'context' => $item['context'],
3852
      'tab_parent' => $item['tab_parent'],
3853
      'tab_root' => $item['tab_root'],
3854
      'title' => $item['title'],
3855
      'title_callback' => $item['title callback'],
3856
      'title_arguments' => ($item['title arguments'] ? serialize($item['title arguments']) : ''),
3857
      'theme_callback' => $item['theme callback'],
3858
      'theme_arguments' => serialize($item['theme arguments']),
3859
      'type' => $item['type'],
3860
      'description' => $item['description'],
3861
      'position' => $item['position'],
3862
      'weight' => $item['weight'],
3863
      'include_file' => $item['include file'],
3864
    ));
3865

    
3866
    // Execute in batches to avoid the memory overhead of all of those records
3867
    // in the query object.
3868
    if (++$num_records == 20) {
3869
      $insert->execute();
3870
      $num_records = 0;
3871
    }
3872
  }
3873
  // Insert any remaining records.
3874
  $insert->execute();
3875
  // Store the masks.
3876
  variable_set('menu_masks', $masks);
3877

    
3878
  return $menu;
3879
}
3880

    
3881
/**
3882
 * Checks whether the site is in maintenance mode.
3883
 *
3884
 * This function will log the current user out and redirect to front page
3885
 * if the current user has no 'access site in maintenance mode' permission.
3886
 *
3887
 * @param $check_only
3888
 *   If this is set to TRUE, the function will perform the access checks and
3889
 *   return the site offline status, but not log the user out or display any
3890
 *   messages.
3891
 *
3892
 * @return
3893
 *   FALSE if the site is not in maintenance mode, the user login page is
3894
 *   displayed, or the user has the 'access site in maintenance mode'
3895
 *   permission. TRUE for anonymous users not being on the login page when the
3896
 *   site is in maintenance mode.
3897
 */
3898
function _menu_site_is_offline($check_only = FALSE) {
3899
  // Check if site is in maintenance mode.
3900
  if (variable_get('maintenance_mode', 0)) {
3901
    if (user_access('access site in maintenance mode')) {
3902
      // Ensure that the maintenance mode message is displayed only once
3903
      // (allowing for page redirects) and specifically suppress its display on
3904
      // the maintenance mode settings page.
3905
      if (!$check_only && $_GET['q'] != 'admin/config/development/maintenance') {
3906
        if (user_access('administer site configuration')) {
3907
          drupal_set_message(t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance'))), 'status', FALSE);
3908
        }
3909
        else {
3910
          drupal_set_message(t('Operating in maintenance mode.'), 'status', FALSE);
3911
        }
3912
      }
3913
    }
3914
    else {
3915
      return TRUE;
3916
    }
3917
  }
3918
  return FALSE;
3919
}
3920

    
3921
/**
3922
 * @} End of "defgroup menu".
3923
 */