Issue #1260932 by DjebbZ, pwolanin: hook_nodeapi() optional arguments should not...
[project/drupal.git] / includes / menu.inc
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.
17 *
18 * Drupal's menu system follows a simple hierarchy defined by paths.
19 * Implementations of hook_menu() define menu items and assign them to
20 * paths (which should be unique). The menu system aggregates these items
21 * and determines the menu hierarchy from the paths. For example, if the
22 * paths defined were a, a/b, e, a/b/c/d, f/g, and a/b/h, the menu system
23 * would form the structure:
24 * - a
25 * - a/b
26 * - a/b/c/d
27 * - a/b/h
28 * - e
29 * - f/g
30 * Note that the number of elements in the path does not necessarily
31 * determine the depth of the menu item in the tree.
32 *
33 * When responding to a page request, the menu system looks to see if the
34 * path requested by the browser is registered as a menu item with a
35 * callback. If not, the system searches up the menu tree for the most
36 * complete match with a callback it can find. If the path a/b/i is
37 * requested in the tree above, the callback for a/b would be used.
38 *
39 * The found callback function is called with any arguments specified
40 * in the "page arguments" attribute of its menu item. The
41 * attribute must be an array. After these arguments, any remaining
42 * components of the path are appended as further arguments. In this
43 * way, the callback for a/b above could respond to a request for
44 * a/b/i differently than a request for a/b/j.
45 *
46 * For an illustration of this process, see page_example.module.
47 *
48 * Access to the callback functions is also protected by the menu system.
49 * The "access callback" with an optional "access arguments" of each menu
50 * item is called before the page callback proceeds. If this returns TRUE,
51 * then access is granted; if FALSE, then access is denied. Menu items may
52 * omit this attribute to use the value provided by an ancestor item.
53 *
54 * In the default Drupal interface, you will notice many links rendered as
55 * tabs. These are known in the menu system as "local tasks", and they are
56 * rendered as tabs by default, though other presentations are possible.
57 * Local tasks function just as other menu items in most respects. It is
58 * convention that the names of these tasks should be short verbs if
59 * possible. In addition, a "default" local task should be provided for
60 * each set. When visiting a local task's parent menu item, the default
61 * local task will be rendered as if it is selected; this provides for a
62 * normal tab user experience. This default task is special in that it
63 * links not to its provided path, but to its parent item's path instead.
64 * The default task's path is only used to place it appropriately in the
65 * menu hierarchy.
66 *
67 * Everything described so far is stored in the menu_router table. The
68 * menu_links table holds the visible menu links. By default these are
69 * derived from the same hook_menu definitions, however you are free to
70 * add more with menu_link_save().
71 */
72
73 /**
74 * @defgroup menu_flags Menu flags
75 * @{
76 * Flags for use in the "type" attribute of menu items.
77 */
78
79 define('MENU_IS_ROOT', 0x0001);
80 define('MENU_VISIBLE_IN_TREE', 0x0002);
81 define('MENU_VISIBLE_IN_BREADCRUMB', 0x0004);
82 define('MENU_LINKS_TO_PARENT', 0x0008);
83 define('MENU_MODIFIED_BY_ADMIN', 0x0020);
84 define('MENU_CREATED_BY_ADMIN', 0x0040);
85 define('MENU_IS_LOCAL_TASK', 0x0080);
86
87 /**
88 * @} End of "Menu flags".
89 */
90
91 /**
92 * @defgroup menu_item_types Menu item types
93 * @{
94 * Definitions for various menu item types.
95 *
96 * Menu item definitions provide one of these constants, which are shortcuts for
97 * combinations of the above flags.
98 */
99
100 /**
101 * Normal menu items show up in the menu tree and can be moved/hidden by
102 * the administrator. Use this for most menu items. It is the default value if
103 * no menu item type is specified.
104 */
105 define('MENU_NORMAL_ITEM', MENU_VISIBLE_IN_TREE | MENU_VISIBLE_IN_BREADCRUMB);
106
107 /**
108 * Callbacks simply register a path so that the correct function is fired
109 * when the URL is accessed. They are not shown in the menu.
110 */
111 define('MENU_CALLBACK', MENU_VISIBLE_IN_BREADCRUMB);
112
113 /**
114 * Modules may "suggest" menu items that the administrator may enable. They act
115 * just as callbacks do until enabled, at which time they act like normal items.
116 * Note for the value: 0x0010 was a flag which is no longer used, but this way
117 * the values of MENU_CALLBACK and MENU_SUGGESTED_ITEM are separate.
118 */
119 define('MENU_SUGGESTED_ITEM', MENU_VISIBLE_IN_BREADCRUMB | 0x0010);
120
121 /**
122 * Local tasks are rendered as tabs by default. Use this for menu items that
123 * describe actions to be performed on their parent item. An example is the path
124 * "node/52/edit", which performs the "edit" task on "node/52".
125 */
126 define('MENU_LOCAL_TASK', MENU_IS_LOCAL_TASK);
127
128 /**
129 * Every set of local tasks should provide one "default" task, that links to the
130 * same path as its parent when clicked.
131 */
132 define('MENU_DEFAULT_LOCAL_TASK', MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT);
133
134 /**
135 * @} End of "Menu item types".
136 */
137
138 /**
139 * @defgroup menu_status_codes Menu status codes
140 * @{
141 * Status codes for menu callbacks.
142 */
143
144 define('MENU_FOUND', 1);
145 define('MENU_NOT_FOUND', 2);
146 define('MENU_ACCESS_DENIED', 3);
147 define('MENU_SITE_OFFLINE', 4);
148
149 /**
150 * @} End of "Menu status codes".
151 */
152
153 /**
154 * @defgroup menu_tree_parameters Menu tree parameters
155 * @{
156 * Parameters for a menu tree.
157 */
158
159 /**
160 * The maximum number of path elements for a menu callback
161 */
162 define('MENU_MAX_PARTS', 7);
163
164
165 /**
166 * The maximum depth of a menu links tree - matches the number of p columns.
167 */
168 define('MENU_MAX_DEPTH', 9);
169
170
171 /**
172 * @} End of "Menu tree parameters".
173 */
174
175 /**
176 * Returns the ancestors (and relevant placeholders) for any given path.
177 *
178 * For example, the ancestors of node/12345/edit are:
179 * - node/12345/edit
180 * - node/12345/%
181 * - node/%/edit
182 * - node/%/%
183 * - node/12345
184 * - node/%
185 * - node
186 *
187 * To generate these, we will use binary numbers. Each bit represents a
188 * part of the path. If the bit is 1, then it represents the original
189 * value while 0 means wildcard. If the path is node/12/edit/foo
190 * then the 1011 bitstring represents node/%/edit/foo where % means that
191 * any argument matches that part. We limit ourselves to using binary
192 * numbers that correspond the patterns of wildcards of router items that
193 * actually exists. This list of 'masks' is built in menu_rebuild().
194 *
195 * @param $parts
196 * An array of path parts, for the above example
197 * array('node', '12345', 'edit').
198 * @return
199 * An array which contains the ancestors and placeholders. Placeholders
200 * simply contain as many '%s' as the ancestors.
201 */
202 function menu_get_ancestors($parts) {
203 $number_parts = count($parts);
204 $placeholders = array();
205 $ancestors = array();
206 $length = $number_parts - 1;
207 $end = (1 << $number_parts) - 1;
208 $masks = variable_get('menu_masks', array());
209 // Only examine patterns that actually exist as router items (the masks).
210 foreach ($masks as $i) {
211 if ($i > $end) {
212 // Only look at masks that are not longer than the path of interest.
213 continue;
214 }
215 elseif ($i < (1 << $length)) {
216 // We have exhausted the masks of a given length, so decrease the length.
217 --$length;
218 }
219 $current = '';
220 for ($j = $length; $j >= 0; $j--) {
221 if ($i & (1 << $j)) {
222 $current .= $parts[$length - $j];
223 }
224 else {
225 $current .= '%';
226 }
227 if ($j) {
228 $current .= '/';
229 }
230 }
231 $placeholders[] = "'%s'";
232 $ancestors[] = $current;
233 }
234 return array($ancestors, $placeholders);
235 }
236
237 /**
238 * The menu system uses serialized arrays stored in the database for
239 * arguments. However, often these need to change according to the
240 * current path. This function unserializes such an array and does the
241 * necessary change.
242 *
243 * Integer values are mapped according to the $map parameter. For
244 * example, if unserialize($data) is array('view', 1) and $map is
245 * array('node', '12345') then 'view' will not be changed because
246 * it is not an integer, but 1 will as it is an integer. As $map[1]
247 * is '12345', 1 will be replaced with '12345'. So the result will
248 * be array('node_load', '12345').
249 *
250 * @param @data
251 * A serialized array.
252 * @param @map
253 * An array of potential replacements.
254 * @return
255 * The $data array unserialized and mapped.
256 */
257 function menu_unserialize($data, $map) {
258 if ($data = unserialize($data)) {
259 foreach ($data as $k => $v) {
260 if (is_int($v)) {
261 $data[$k] = isset($map[$v]) ? $map[$v] : '';
262 }
263 }
264 return $data;
265 }
266 else {
267 return array();
268 }
269 }
270
271
272
273 /**
274 * Replaces the statically cached item for a given path.
275 *
276 * @param $path
277 * The path.
278 * @param $router_item
279 * The router item. Usually you take a router entry from menu_get_item and
280 * set it back either modified or to a different path. This lets you modify the
281 * navigation block, the page title, the breadcrumb and the page help in one
282 * call.
283 */
284 function menu_set_item($path, $router_item) {
285 menu_get_item($path, $router_item);
286 }
287
288 /**
289 * Get a router item.
290 *
291 * @param $path
292 * The path, for example node/5. The function will find the corresponding
293 * node/% item and return that.
294 * @param $router_item
295 * Internal use only.
296 * @return
297 * The router item, an associate array corresponding to one row in the
298 * menu_router table. The value of key map holds the loaded objects. The
299 * value of key access is TRUE if the current user can access this page.
300 * The values for key title, page_arguments, access_arguments will be
301 * filled in based on the database values and the objects loaded.
302 */
303 function menu_get_item($path = NULL, $router_item = NULL) {
304 static $router_items;
305 if (!isset($path)) {
306 $path = $_GET['q'];
307 }
308 if (isset($router_item)) {
309 $router_items[$path] = $router_item;
310 }
311 if (!isset($router_items[$path])) {
312 $original_map = arg(NULL, $path);
313 $parts = array_slice($original_map, 0, MENU_MAX_PARTS);
314 list($ancestors, $placeholders) = menu_get_ancestors($parts);
315
316 if ($router_item = db_fetch_array(db_query_range('SELECT * FROM {menu_router} WHERE path IN ('. implode (',', $placeholders) .') ORDER BY fit DESC', $ancestors, 0, 1))) {
317 $map = _menu_translate($router_item, $original_map);
318 if ($map === FALSE) {
319 $router_items[$path] = FALSE;
320 return FALSE;
321 }
322 if ($router_item['access']) {
323 $router_item['map'] = $map;
324 $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
325 }
326 }
327 $router_items[$path] = $router_item;
328 }
329 return $router_items[$path];
330 }
331
332 /**
333 * Execute the page callback associated with the current path
334 */
335 function menu_execute_active_handler($path = NULL) {
336 if (_menu_site_is_offline()) {
337 return MENU_SITE_OFFLINE;
338 }
339 // Rebuild if we know it's needed, or if the menu masks are missing which
340 // occurs rarely, likely due to a race condition of multiple rebuilds.
341 if (variable_get('menu_rebuild_needed', FALSE) || !variable_get('menu_masks', array())) {
342 menu_rebuild();
343 }
344 if ($router_item = menu_get_item($path)) {
345 if ($router_item['access']) {
346 if ($router_item['file']) {
347 require_once($router_item['file']);
348 }
349 return call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
350 }
351 else {
352 return MENU_ACCESS_DENIED;
353 }
354 }
355 return MENU_NOT_FOUND;
356 }
357
358 /**
359 * Loads objects into the map as defined in the $item['load_functions'].
360 *
361 * @param $item
362 * A menu router or menu link item
363 * @param $map
364 * An array of path arguments (ex: array('node', '5'))
365 * @return
366 * Returns TRUE for success, FALSE if an object cannot be loaded.
367 * Names of object loading functions are placed in $item['load_functions'].
368 * Loaded objects are placed in $map[]; keys are the same as keys in the
369 * $item['load_functions'] array.
370 * $item['access'] is set to FALSE if an object cannot be loaded.
371 */
372 function _menu_load_objects(&$item, &$map) {
373 if ($load_functions = $item['load_functions']) {
374 // If someone calls this function twice, then unserialize will fail.
375 if ($load_functions_unserialized = unserialize($load_functions)) {
376 $load_functions = $load_functions_unserialized;
377 }
378 $path_map = $map;
379 foreach ($load_functions as $index => $function) {
380 if ($function) {
381 $value = isset($path_map[$index]) ? $path_map[$index] : '';
382 if (is_array($function)) {
383 // Set up arguments for the load function. These were pulled from
384 // 'load arguments' in the hook_menu() entry, but they need
385 // some processing. In this case the $function is the key to the
386 // load_function array, and the value is the list of arguments.
387 list($function, $args) = each($function);
388 $load_functions[$index] = $function;
389
390 // Some arguments are placeholders for dynamic items to process.
391 foreach ($args as $i => $arg) {
392 if ($arg === '%index') {
393 // Pass on argument index to the load function, so multiple
394 // occurances of the same placeholder can be identified.
395 $args[$i] = $index;
396 }
397 if ($arg === '%map') {
398 // Pass on menu map by reference. The accepting function must
399 // also declare this as a reference if it wants to modify
400 // the map.
401 $args[$i] = &$map;
402 }
403 if (is_int($arg)) {
404 $args[$i] = isset($path_map[$arg]) ? $path_map[$arg] : '';
405 }
406 }
407 array_unshift($args, $value);
408 $return = call_user_func_array($function, $args);
409 }
410 else {
411 $return = $function($value);
412 }
413 // If callback returned an error or there is no callback, trigger 404.
414 if ($return === FALSE) {
415 $item['access'] = FALSE;
416 $map = FALSE;
417 return FALSE;
418 }
419 $map[$index] = $return;
420 }
421 }
422 $item['load_functions'] = $load_functions;
423 }
424 return TRUE;
425 }
426
427 /**
428 * Check access to a menu item using the access callback
429 *
430 * @param $item
431 * A menu router or menu link item
432 * @param $map
433 * An array of path arguments (ex: array('node', '5'))
434 * @return
435 * $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
436 */
437 function _menu_check_access(&$item, $map) {
438 // Determine access callback, which will decide whether or not the current
439 // user has access to this path.
440 $callback = empty($item['access_callback']) ? 0 : trim($item['access_callback']);
441 // Check for a TRUE or FALSE value.
442 if (is_numeric($callback)) {
443 $item['access'] = (bool)$callback;
444 }
445 else {
446 $arguments = menu_unserialize($item['access_arguments'], $map);
447 // As call_user_func_array is quite slow and user_access is a very common
448 // callback, it is worth making a special case for it.
449 if ($callback == 'user_access') {
450 $item['access'] = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
451 }
452 else {
453 $item['access'] = call_user_func_array($callback, $arguments);
454 }
455 }
456 }
457
458 /**
459 * Localize the router item title using t() or another callback.
460 *
461 * Translate the title and description to allow storage of English title
462 * strings in the database, yet display of them in the language required
463 * by the current user.
464 *
465 * @param $item
466 * A menu router item or a menu link item.
467 * @param $map
468 * The path as an array with objects already replaced. E.g., for path
469 * node/123 $map would be array('node', $node) where $node is the node
470 * object for node 123.
471 * @param $link_translate
472 * TRUE if we are translating a menu link item; FALSE if we are
473 * translating a menu router item.
474 * @return
475 * No return value.
476 * $item['title'] is localized according to $item['title_callback'].
477 * If an item's callback is check_plain(), $item['options']['html'] becomes
478 * TRUE.
479 * $item['description'] is translated using t().
480 * When doing link translation and the $item['options']['attributes']['title']
481 * (link title attribute) matches the description, it is translated as well.
482 */
483 function _menu_item_localize(&$item, $map, $link_translate = FALSE) {
484 $callback = $item['title_callback'];
485 $item['localized_options'] = $item['options'];
486 // If we are translating the title of a menu link, and its title is the same
487 // as the corresponding router item, then we can use the title information
488 // from the router. If it's customized, then we need to use the link title
489 // itself; can't localize.
490 // If we are translating a router item (tabs, page, breadcrumb), then we
491 // can always use the information from the router item.
492 if (!$link_translate || ($item['title'] == $item['link_title'])) {
493 // t() is a special case. Since it is used very close to all the time,
494 // we handle it directly instead of using indirect, slower methods.
495 if ($callback == 't') {
496 if (empty($item['title_arguments'])) {
497 $item['title'] = t($item['title']);
498 }
499 else {
500 $item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));
501 }
502 }
503 elseif ($callback) {
504 if (empty($item['title_arguments'])) {
505 $item['title'] = $callback($item['title']);
506 }
507 else {
508 $item['title'] = call_user_func_array($callback, menu_unserialize($item['title_arguments'], $map));
509 }
510 // Avoid calling check_plain again on l() function.
511 if ($callback == 'check_plain') {
512 $item['localized_options']['html'] = TRUE;
513 }
514 }
515 }
516 elseif ($link_translate) {
517 $item['title'] = $item['link_title'];
518 }
519
520 // Translate description, see the motivation above.
521 if (!empty($item['description'])) {
522 $original_description = $item['description'];
523 $item['description'] = t($item['description']);
524 if ($link_translate && isset($item['options']['attributes']['title']) && $item['options']['attributes']['title'] == $original_description) {
525 $item['localized_options']['attributes']['title'] = $item['description'];
526 }
527 }
528 }
529
530 /**
531 * Handles dynamic path translation and menu access control.
532 *
533 * When a user arrives on a page such as node/5, this function determines
534 * what "5" corresponds to, by inspecting the page's menu path definition,
535 * node/%node. This will call node_load(5) to load the corresponding node
536 * object.
537 *
538 * It also works in reverse, to allow the display of tabs and menu items which
539 * contain these dynamic arguments, translating node/%node to node/5.
540 *
541 * Translation of menu item titles and descriptions are done here to
542 * allow for storage of English strings in the database, and translation
543 * to the language required to generate the current page
544 *
545 * @param $router_item
546 * A menu router item
547 * @param $map
548 * An array of path arguments (ex: array('node', '5'))
549 * @param $to_arg
550 * Execute $item['to_arg_functions'] or not. Use only if you want to render a
551 * path from the menu table, for example tabs.
552 * @return
553 * Returns the map with objects loaded as defined in the
554 * $item['load_functions']. $item['access'] becomes TRUE if the item is
555 * accessible, FALSE otherwise. $item['href'] is set according to the map.
556 * If an error occurs during calling the load_functions (like trying to load
557 * a non existing node) then this function return FALSE.
558 */
559 function _menu_translate(&$router_item, $map, $to_arg = FALSE) {
560 if ($to_arg) {
561 // Fill in missing path elements, such as the current uid.
562 _menu_link_map_translate($map, $router_item['to_arg_functions']);
563 }
564 // The $path_map saves the pieces of the path as strings, while elements in
565 // $map may be replaced with loaded objects.
566 $path_map = $map;
567 if (!_menu_load_objects($router_item, $map)) {
568 // An error occurred loading an object.
569 $router_item['access'] = FALSE;
570 return FALSE;
571 }
572
573 // Generate the link path for the page request or local tasks.
574 $link_map = explode('/', $router_item['path']);
575 for ($i = 0; $i < $router_item['number_parts']; $i++) {
576 if ($link_map[$i] == '%') {
577 $link_map[$i] = $path_map[$i];
578 }
579 }
580 $router_item['href'] = implode('/', $link_map);
581 $router_item['options'] = array();
582 _menu_check_access($router_item, $map);
583
584 // For performance, don't localize an item the user can't access.
585 if ($router_item['access']) {
586 _menu_item_localize($router_item, $map);
587 }
588
589 return $map;
590 }
591
592 /**
593 * This function translates the path elements in the map using any to_arg
594 * helper function. These functions take an argument and return an object.
595 * See http://drupal.org/node/109153 for more information.
596 *
597 * @param map
598 * An array of path arguments (ex: array('node', '5'))
599 * @param $to_arg_functions
600 * An array of helper function (ex: array(2 => 'menu_tail_to_arg'))
601 */
602 function _menu_link_map_translate(&$map, $to_arg_functions) {
603 if ($to_arg_functions) {
604 $to_arg_functions = unserialize($to_arg_functions);
605 foreach ($to_arg_functions as $index => $function) {
606 // Translate place-holders into real values.
607 $arg = $function(!empty($map[$index]) ? $map[$index] : '', $map, $index);
608 if (!empty($map[$index]) || isset($arg)) {
609 $map[$index] = $arg;
610 }
611 else {
612 unset($map[$index]);
613 }
614 }
615 }
616 }
617
618 function menu_tail_to_arg($arg, $map, $index) {
619 return implode('/', array_slice($map, $index));
620 }
621
622 /**
623 * This function is similar to _menu_translate() but does link-specific
624 * preparation such as always calling to_arg functions.
625 *
626 * @param $item
627 * A menu link
628 * @return
629 * Returns the map of path arguments with objects loaded as defined in the
630 * $item['load_functions']:
631 * - $item['access'] becomes TRUE if the item is accessible, FALSE otherwise.
632 * - $item['href'] is generated from link_path, possibly by to_arg functions.
633 * - $item['title'] is generated from link_title, and may be localized.
634 * - $item['options'] is unserialized; it is also changed within the call
635 * here to $item['localized_options'] by _menu_item_localize().
636 */
637 function _menu_link_translate(&$item) {
638 $item['options'] = unserialize($item['options']);
639 if ($item['external']) {
640 $item['access'] = 1;
641 $map = array();
642 $item['href'] = $item['link_path'];
643 $item['title'] = $item['link_title'];
644 $item['localized_options'] = $item['options'];
645 }
646 else {
647 $map = explode('/', $item['link_path']);
648 _menu_link_map_translate($map, $item['to_arg_functions']);
649 $item['href'] = implode('/', $map);
650
651 // Note - skip callbacks without real values for their arguments.
652 if (strpos($item['href'], '%') !== FALSE) {
653 $item['access'] = FALSE;
654 return FALSE;
655 }
656 // menu_tree_check_access() may set this ahead of time for links to nodes.
657 if (!isset($item['access'])) {
658 if (!_menu_load_objects($item, $map)) {
659 // An error occurred loading an object.
660 $item['access'] = FALSE;
661 return FALSE;
662 }
663 _menu_check_access($item, $map);
664 }
665 // For performance, don't localize a link the user can't access.
666 if ($item['access']) {
667 _menu_item_localize($item, $map, TRUE);
668 }
669 }
670
671 // Allow other customizations - e.g. adding a page-specific query string to the
672 // options array. For performance reasons we only invoke this hook if the link
673 // has the 'alter' flag set in the options array.
674 if (!empty($item['options']['alter'])) {
675 drupal_alter('translated_menu_link', $item, $map);
676 }
677
678 return $map;
679 }
680
681 /**
682 * Get a loaded object from a router item.
683 *
684 * menu_get_object() will provide you the current node on paths like node/5,
685 * node/5/revisions/48 etc. menu_get_object('user') will give you the user
686 * account on user/5 etc. Note - this function should never be called within a
687 * _to_arg function (like user_current_to_arg()) since this may result in an
688 * infinite recursion.
689 *
690 * @param $type
691 * Type of the object. These appear in hook_menu definitons as %type. Core
692 * provides aggregator_feed, aggregator_category, contact, filter_format,
693 * forum_term, menu, menu_link, node, taxonomy_vocabulary, user. See the
694 * relevant {$type}_load function for more on each. Defaults to node.
695 * @param $position
696 * The expected position for $type object. For node/%node this is 1, for
697 * comment/reply/%node this is 2. Defaults to 1.
698 * @param $path
699 * See menu_get_item() for more on this. Defaults to the current path.
700 */
701 function menu_get_object($type = 'node', $position = 1, $path = NULL) {
702 $router_item = menu_get_item($path);
703 if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type .'_load') {
704 return $router_item['map'][$position];
705 }
706 }
707
708 /**
709 * Render a menu tree based on the current path.
710 *
711 * The tree is expanded based on the current path and dynamic paths are also
712 * changed according to the defined to_arg functions (for example the 'My account'
713 * link is changed from user/% to a link with the current user's uid).
714 *
715 * @param $menu_name
716 * The name of the menu.
717 * @return
718 * The rendered HTML of that menu on the current page.
719 */
720 function menu_tree($menu_name = 'navigation') {
721 static $menu_output = array();
722
723 if (!isset($menu_output[$menu_name])) {
724 $tree = menu_tree_page_data($menu_name);
725 $menu_output[$menu_name] = menu_tree_output($tree);
726 }
727 return $menu_output[$menu_name];
728 }
729
730 /**
731 * Returns a rendered menu tree.
732 *
733 * @param $tree
734 * A data structure representing the tree as returned from menu_tree_data.
735 * @return
736 * The rendered HTML of that data structure.
737 */
738 function menu_tree_output($tree) {
739 $output = '';
740 $items = array();
741
742 // Pull out just the menu items we are going to render so that we
743 // get an accurate count for the first/last classes.
744 foreach ($tree as $data) {
745 if (!$data['link']['hidden']) {
746 $items[] = $data;
747 }
748 }
749
750 $num_items = count($items);
751 foreach ($items as $i => $data) {
752 $extra_class = array();
753 if ($i == 0) {
754 $extra_class[] = 'first';
755 }
756 if ($i == $num_items - 1) {
757 $extra_class[] = 'last';
758 }
759 $extra_class = implode(' ', $extra_class);
760 $link = theme('menu_item_link', $data['link']);
761 if ($data['below']) {
762 $output .= theme('menu_item', $link, $data['link']['has_children'], menu_tree_output($data['below']), $data['link']['in_active_trail'], $extra_class);
763 }
764 else {
765 $output .= theme('menu_item', $link, $data['link']['has_children'], '', $data['link']['in_active_trail'], $extra_class);
766 }
767 }
768 return $output ? theme('menu_tree', $output) : '';
769 }
770
771 /**
772 * Get the data structure representing a named menu tree.
773 *
774 * Since this can be the full tree including hidden items, the data returned
775 * may be used for generating an an admin interface or a select.
776 *
777 * @param $menu_name
778 * The named menu links to return
779 * @param $item
780 * A fully loaded menu link, or NULL. If a link is supplied, only the
781 * path to root will be included in the returned tree- as if this link
782 * represented the current page in a visible menu.
783 * @return
784 * An tree of menu links in an array, in the order they should be rendered.
785 */
786 function menu_tree_all_data($menu_name = 'navigation', $item = NULL) {
787 static $tree = array();
788
789 // Use $mlid as a flag for whether the data being loaded is for the whole tree.
790 $mlid = isset($item['mlid']) ? $item['mlid'] : 0;
791 // Generate a cache ID (cid) specific for this $menu_name and $item.
792 $cid = 'links:'. $menu_name .':all-cid:'. $mlid;
793
794 if (!isset($tree[$cid])) {
795 // If the static variable doesn't have the data, check {cache_menu}.
796 $cache = cache_get($cid, 'cache_menu');
797 if ($cache && isset($cache->data)) {
798 // If the cache entry exists, it will just be the cid for the actual data.
799 // This avoids duplication of large amounts of data.
800 $cache = cache_get($cache->data, 'cache_menu');
801 if ($cache && isset($cache->data)) {
802 $data = $cache->data;
803 }
804 }
805 // If the tree data was not in the cache, $data will be NULL.
806 if (!isset($data)) {
807 // Build and run the query, and build the tree.
808 if ($mlid) {
809 // The tree is for a single item, so we need to match the values in its
810 // p columns and 0 (the top level) with the plid values of other links.
811 $args = array(0);
812 for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
813 $args[] = $item["p$i"];
814 }
815 $args = array_unique($args);
816 $placeholders = implode(', ', array_fill(0, count($args), '%d'));
817 $where = ' AND ml.plid IN ('. $placeholders .')';
818 $parents = $args;
819 $parents[] = $item['mlid'];
820 }
821 else {
822 // Get all links in this menu.
823 $where = '';
824 $args = array();
825 $parents = array();
826 }
827 array_unshift($args, $menu_name);
828 // Select the links from the table, and recursively build the tree. We
829 // LEFT JOIN since there is no match in {menu_router} for an external
830 // link.
831 $data['tree'] = menu_tree_data(db_query("
832 SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.*
833 FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
834 WHERE ml.menu_name = '%s'". $where ."
835 ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC", $args), $parents);
836 $data['node_links'] = array();
837 menu_tree_collect_node_links($data['tree'], $data['node_links']);
838 // Cache the data, if it is not already in the cache.
839 $tree_cid = _menu_tree_cid($menu_name, $data);
840 if (!cache_get($tree_cid, 'cache_menu')) {
841 cache_set($tree_cid, $data, 'cache_menu');
842 }
843 // Cache the cid of the (shared) data using the menu and item-specific cid.
844 cache_set($cid, $tree_cid, 'cache_menu');
845 }
846 // Check access for the current user to each item in the tree.
847 menu_tree_check_access($data['tree'], $data['node_links']);
848 $tree[$cid] = $data['tree'];
849 }
850
851 return $tree[$cid];
852 }
853
854 /**
855 * Get the data structure representing a named menu tree, based on the current page.
856 *
857 * The tree order is maintained by storing each parent in an individual
858 * field, see http://drupal.org/node/141866 for more.
859 *
860 * @param $menu_name
861 * The named menu links to return
862 * @return
863 * An array of menu links, in the order they should be rendered. The array
864 * is a list of associative arrays -- these have two keys, link and below.
865 * link is a menu item, ready for theming as a link. Below represents the
866 * submenu below the link if there is one, and it is a subtree that has the
867 * same structure described for the top-level array.
868 */
869 function menu_tree_page_data($menu_name = 'navigation') {
870 static $tree = array();
871
872 // Load the menu item corresponding to the current page.
873 if ($item = menu_get_item()) {
874 // Generate a cache ID (cid) specific for this page.
875 $cid = 'links:'. $menu_name .':page-cid:'. $item['href'] .':'. (int)$item['access'];
876
877 if (!isset($tree[$cid])) {
878 // If the static variable doesn't have the data, check {cache_menu}.
879 $cache = cache_get($cid, 'cache_menu');
880 if ($cache && isset($cache->data)) {
881 // If the cache entry exists, it will just be the cid for the actual data.
882 // This avoids duplication of large amounts of data.
883 $cache = cache_get($cache->data, 'cache_menu');
884 if ($cache && isset($cache->data)) {
885 $data = $cache->data;
886 }
887 }
888 // If the tree data was not in the cache, $data will be NULL.
889 if (!isset($data)) {
890 // Build and run the query, and build the tree.
891 if ($item['access']) {
892 // Check whether a menu link exists that corresponds to the current path.
893 $args = array($menu_name, $item['href']);
894 $placeholders = "'%s'";
895 if (drupal_is_front_page()) {
896 $args[] = '<front>';
897 $placeholders .= ", '%s'";
898 }
899 $parents = db_fetch_array(db_query("SELECT p1, p2, p3, p4, p5, p6, p7, p8 FROM {menu_links} WHERE menu_name = '%s' AND link_path IN (". $placeholders .")", $args));
900
901 if (empty($parents)) {
902 // If no link exists, we may be on a local task that's not in the links.
903 // TODO: Handle the case like a local task on a specific node in the menu.
904 $parents = db_fetch_array(db_query("SELECT p1, p2, p3, p4, p5, p6, p7, p8 FROM {menu_links} WHERE menu_name = '%s' AND link_path = '%s'", $menu_name, $item['tab_root']));
905 }
906 // We always want all the top-level links with plid == 0.
907 $parents[] = '0';
908
909 // Use array_values() so that the indices are numeric for array_merge().
910 $args = $parents = array_unique(array_values($parents));
911 $placeholders = implode(', ', array_fill(0, count($args), '%d'));
912 $expanded = variable_get('menu_expanded', array());
913 // Check whether the current menu has any links set to be expanded.
914 if (in_array($menu_name, $expanded)) {
915 // Collect all the links set to be expanded, and then add all of
916 // their children to the list as well.
917 do {
918 $result = db_query("SELECT mlid FROM {menu_links} WHERE menu_name = '%s' AND expanded = 1 AND has_children = 1 AND plid IN (". $placeholders .') AND mlid NOT IN ('. $placeholders .')', array_merge(array($menu_name), $args, $args));
919 $num_rows = FALSE;
920 while ($item = db_fetch_array($result)) {
921 $args[] = $item['mlid'];
922 $num_rows = TRUE;
923 }
924 $placeholders = implode(', ', array_fill(0, count($args), '%d'));
925 } while ($num_rows);
926 }
927 array_unshift($args, $menu_name);
928 }
929 else {
930 // Show only the top-level menu items when access is denied.
931 $args = array($menu_name, '0');
932 $placeholders = '%d';
933 $parents = array();
934 }
935 // Select the links from the table, and recursively build the tree. We
936 // LEFT JOIN since there is no match in {menu_router} for an external
937 // link.
938 $data['tree'] = menu_tree_data(db_query("
939 SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.*
940 FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
941 WHERE ml.menu_name = '%s' AND ml.plid IN (". $placeholders .")
942 ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC", $args), $parents);
943 $data['node_links'] = array();
944 menu_tree_collect_node_links($data['tree'], $data['node_links']);
945 // Cache the data, if it is not already in the cache.
946 $tree_cid = _menu_tree_cid($menu_name, $data);
947 if (!cache_get($tree_cid, 'cache_menu')) {
948 cache_set($tree_cid, $data, 'cache_menu');
949 }
950 // Cache the cid of the (shared) data using the page-specific cid.
951 cache_set($cid, $tree_cid, 'cache_menu');
952 }
953 // Check access for the current user to each item in the tree.
954 menu_tree_check_access($data['tree'], $data['node_links']);
955 $tree[$cid] = $data['tree'];
956 }
957 return $tree[$cid];
958 }
959
960 return array();
961 }
962
963 /**
964 * Helper function - compute the real cache ID for menu tree data.
965 */
966 function _menu_tree_cid($menu_name, $data) {
967 return 'links:'. $menu_name .':tree-data:'. md5(serialize($data));
968 }
969
970 /**
971 * Recursive helper function - collect node links.
972 *
973 * @param $tree
974 * The menu tree you wish to collect node links from.
975 * @param $node_links
976 * An array in which to store the collected node links.
977 */
978 function menu_tree_collect_node_links(&$tree, &$node_links) {
979 foreach ($tree as $key => $v) {
980 if ($tree[$key]['link']['router_path'] == 'node/%') {
981 $nid = substr($tree[$key]['link']['link_path'], 5);
982 if (is_numeric($nid)) {
983 $node_links[$nid][$tree[$key]['link']['mlid']] = &$tree[$key]['link'];
984 $tree[$key]['link']['access'] = FALSE;
985 }
986 }
987 if ($tree[$key]['below']) {
988 menu_tree_collect_node_links($tree[$key]['below'], $node_links);
989 }
990 }
991 }
992
993 /**
994 * Check access and perform other dynamic operations for each link in the tree.
995 *
996 * @param $tree
997 * The menu tree you wish to operate on.
998 * @param $node_links
999 * A collection of node link references generated from $tree by
1000 * menu_tree_collect_node_links().
1001 */
1002 function menu_tree_check_access(&$tree, $node_links = array()) {
1003
1004 if ($node_links) {
1005 // Use db_rewrite_sql to evaluate view access without loading each full node.
1006 $nids = array_keys($node_links);
1007 $placeholders = '%d'. str_repeat(', %d', count($nids) - 1);
1008 $result = db_query(db_rewrite_sql("SELECT n.nid FROM {node} n WHERE n.status = 1 AND n.nid IN (". $placeholders .")"), $nids);
1009 while ($node = db_fetch_array($result)) {
1010 $nid = $node['nid'];
1011 foreach ($node_links[$nid] as $mlid => $link) {
1012 $node_links[$nid][$mlid]['access'] = TRUE;
1013 }
1014 }
1015 }
1016 _menu_tree_check_access($tree);
1017 return;
1018 }
1019
1020 /**
1021 * Recursive helper function for menu_tree_check_access()
1022 */
1023 function _menu_tree_check_access(&$tree) {
1024 $new_tree = array();
1025 foreach ($tree as $key => $v) {
1026 $item = &$tree[$key]['link'];
1027 _menu_link_translate($item);
1028 if ($item['access']) {
1029 if ($tree[$key]['below']) {
1030 _menu_tree_check_access($tree[$key]['below']);
1031 }
1032 // The weights are made a uniform 5 digits by adding 50000 as an offset.
1033 // After _menu_link_translate(), $item['title'] has the localized link title.
1034 // Adding the mlid to the end of the index insures that it is unique.
1035 $new_tree[(50000 + $item['weight']) .' '. $item['title'] .' '. $item['mlid']] = $tree[$key];
1036 }
1037 }
1038 // Sort siblings in the tree based on the weights and localized titles.
1039 ksort($new_tree);
1040 $tree = $new_tree;
1041 }
1042
1043 /**
1044 * Build the data representing a menu tree.
1045 *
1046 * @param $result
1047 * The database result.
1048 * @param $parents
1049 * An array of the plid values that represent the path from the current page
1050 * to the root of the menu tree.
1051 * @param $depth
1052 * The depth of the current menu tree.
1053 * @return
1054 * See menu_tree_page_data for a description of the data structure.
1055 */
1056 function menu_tree_data($result = NULL, $parents = array(), $depth = 1) {
1057 list(, $tree) = _menu_tree_data($result, $parents, $depth);
1058 return $tree;
1059 }
1060
1061 /**
1062 * Recursive helper function to build the data representing a menu tree.
1063 *
1064 * The function is a bit complex because the rendering of an item depends on
1065 * the next menu item. So we are always rendering the element previously
1066 * processed not the current one.
1067 */
1068 function _menu_tree_data($result, $parents, $depth, $previous_element = '') {
1069 $remnant = NULL;
1070 $tree = array();
1071 while ($item = db_fetch_array($result)) {
1072 // We need to determine if we're on the path to root so we can later build
1073 // the correct active trail and breadcrumb.
1074 $item['in_active_trail'] = in_array($item['mlid'], $parents);
1075 // The current item is the first in a new submenu.
1076 if ($item['depth'] > $depth) {
1077 // _menu_tree returns an item and the menu tree structure.
1078 list($item, $below) = _menu_tree_data($result, $parents, $item['depth'], $item);
1079 if ($previous_element) {
1080 $tree[$previous_element['mlid']] = array(
1081 'link' => $previous_element,
1082 'below' => $below,
1083 );
1084 }
1085 else {
1086 $tree = $below;
1087 }
1088 // We need to fall back one level.
1089 if (!isset($item) || $item['depth'] < $depth) {
1090 return array($item, $tree);
1091 }
1092 // This will be the link to be output in the next iteration.
1093 $previous_element = $item;
1094 }
1095 // We are at the same depth, so we use the previous element.
1096 elseif ($item['depth'] == $depth) {
1097 if ($previous_element) {
1098 // Only the first time.
1099 $tree[$previous_element['mlid']] = array(
1100 'link' => $previous_element,
1101 'below' => FALSE,
1102 );
1103 }
1104 // This will be the link to be output in the next iteration.
1105 $previous_element = $item;
1106 }
1107 // The submenu ended with the previous item, so pass back the current item.
1108 else {
1109 $remnant = $item;
1110 break;
1111 }
1112 }
1113 if ($previous_element) {
1114 // We have one more link dangling.
1115 $tree[$previous_element['mlid']] = array(
1116 'link' => $previous_element,
1117 'below' => FALSE,
1118 );
1119 }
1120 return array($remnant, $tree);
1121 }
1122
1123 /**
1124 * Generate the HTML output for a single menu link.
1125 *
1126 * @ingroup themeable
1127 */
1128 function theme_menu_item_link($link) {
1129 if (empty($link['localized_options'])) {
1130 $link['localized_options'] = array();
1131 }
1132
1133 return l($link['title'], $link['href'], $link['localized_options']);
1134 }
1135
1136 /**
1137 * Generate the HTML output for a menu tree
1138 *
1139 * @ingroup themeable
1140 */
1141 function theme_menu_tree($tree) {
1142 return '<ul class="menu">'. $tree .'</ul>';
1143 }
1144
1145 /**
1146 * Generate the HTML output for a menu item and submenu.
1147 *
1148 * @ingroup themeable
1149 */
1150 function theme_menu_item($link, $has_children, $menu = '', $in_active_trail = FALSE, $extra_class = NULL) {
1151 $class = ($menu ? 'expanded' : ($has_children ? 'collapsed' : 'leaf'));
1152 if (!empty($extra_class)) {
1153 $class .= ' '. $extra_class;
1154 }
1155 if ($in_active_trail) {
1156 $class .= ' active-trail';
1157 }
1158 return '<li class="'. $class .'">'. $link . $menu ."</li>\n";
1159 }
1160
1161 /**
1162 * Generate the HTML output for a single local task link.
1163 *
1164 * @ingroup themeable
1165 */
1166 function theme_menu_local_task($link, $active = FALSE) {
1167 return '<li '. ($active ? 'class="active" ' : '') .'>'. $link ."</li>\n";
1168 }
1169
1170 /**
1171 * Generates elements for the $arg array in the help hook.
1172 */
1173 function drupal_help_arg($arg = array()) {
1174 // Note - the number of empty elements should be > MENU_MAX_PARTS.
1175 return $arg + array('', '', '', '', '', '', '', '', '', '', '', '');
1176 }
1177
1178 /**
1179 * Returns the help associated with the active menu item.
1180 */
1181 function menu_get_active_help() {
1182 $output = '';
1183 $router_path = menu_tab_root_path();
1184 // We will always have a path unless we are on a 403 or 404.
1185 if (!$router_path) {
1186 return '';
1187 }
1188
1189 $arg = drupal_help_arg(arg(NULL));
1190 $empty_arg = drupal_help_arg();
1191
1192 foreach (module_list() as $name) {
1193 if (module_hook($name, 'help')) {
1194 // Lookup help for this path.
1195 if ($help = module_invoke($name, 'help', $router_path, $arg)) {
1196 $output .= $help ."\n";
1197 }
1198 // Add "more help" link on admin pages if the module provides a
1199 // standalone help page.
1200 if ($arg[0] == "admin" && module_exists('help') && module_invoke($name, 'help', 'admin/help#'. $arg[2], $empty_arg) && $help) {
1201 $output .= theme("more_help_link", url('admin/help/'. $arg[2]));
1202 }
1203 }
1204 }
1205 return $output;
1206 }
1207
1208 /**
1209 * Build a list of named menus.
1210 */
1211 function menu_get_names($reset = FALSE) {
1212 static $names;
1213
1214 if ($reset || empty($names)) {
1215 $names = array();
1216 $result = db_query("SELECT DISTINCT(menu_name) FROM {menu_links} ORDER BY menu_name");
1217 while ($name = db_fetch_array($result)) {
1218 $names[] = $name['menu_name'];
1219 }
1220 }
1221 return $names;
1222 }
1223
1224 /**
1225 * Return an array containing the names of system-defined (default) menus.
1226 */
1227 function menu_list_system_menus() {
1228 return array('navigation', 'primary-links', 'secondary-links');
1229 }
1230
1231 /**
1232 * Return an array of links to be rendered as the Primary links.
1233 */
1234 function menu_primary_links() {
1235 return menu_navigation_links(variable_get('menu_primary_links_source', 'primary-links'));
1236 }
1237
1238 /**
1239 * Return an array of links to be rendered as the Secondary links.
1240 */
1241 function menu_secondary_links() {
1242
1243 // If the secondary menu source is set as the primary menu, we display the
1244 // second level of the primary menu.
1245 if (variable_get('menu_secondary_links_source', 'secondary-links') == variable_get('menu_primary_links_source', 'primary-links')) {
1246 return menu_navigation_links(variable_get('menu_primary_links_source', 'primary-links'), 1);
1247 }
1248 else {
1249 return menu_navigation_links(variable_get('menu_secondary_links_source', 'secondary-links'), 0);
1250 }
1251 }
1252
1253 /**
1254 * Return an array of links for a navigation menu.
1255 *
1256 * @param $menu_name
1257 * The name of the menu.
1258 * @param $level
1259 * Optional, the depth of the menu to be returned.
1260 * @return
1261 * An array of links of the specified menu and level.
1262 */
1263 function menu_navigation_links($menu_name, $level = 0) {
1264 // Don't even bother querying the menu table if no menu is specified.
1265 if (empty($menu_name)) {
1266 return array();
1267 }
1268
1269 // Get the menu hierarchy for the current page.
1270 $tree = menu_tree_page_data($menu_name);
1271
1272 // Go down the active trail until the right level is reached.
1273 while ($level-- > 0 && $tree) {
1274 // Loop through the current level's items until we find one that is in trail.
1275 while ($item = array_shift($tree)) {
1276 if ($item['link']['in_active_trail']) {
1277 // If the item is in the active trail, we continue in the subtree.
1278 $tree = empty($item['below']) ? array() : $item['below'];
1279 break;
1280 }
1281 }
1282 }
1283
1284 // Create a single level of links.
1285 $links = array();
1286 foreach ($tree as $item) {
1287 if (!$item['link']['hidden']) {
1288 $class = '';
1289 $l = $item['link']['localized_options'];
1290 $l['href'] = $item['link']['href'];
1291 $l['title'] = $item['link']['title'];
1292 if ($item['link']['in_active_trail']) {
1293 $class = ' active-trail';
1294 }
1295 // Keyed with the unique mlid to generate classes in theme_links().
1296 $links['menu-'. $item['link']['mlid'] . $class] = $l;
1297 }
1298 }
1299 return $links;
1300 }
1301
1302 /**
1303 * Collects the local tasks (tabs) for a given level.
1304 *
1305 * @param $level
1306 * The level of tasks you ask for. Primary tasks are 0, secondary are 1.
1307 * @param $return_root
1308 * Whether to return the root path for the current page.
1309 * @return
1310 * Themed output corresponding to the tabs of the requested level, or
1311 * router path if $return_root == TRUE. This router path corresponds to
1312 * a parent tab, if the current page is a default local task.
1313 */
1314 function menu_local_tasks($level = 0, $return_root = FALSE) {
1315 static $tabs;
1316 static $root_path;
1317
1318 if (!isset($tabs)) {
1319 $tabs = array();
1320
1321 $router_item = menu_get_item();
1322 if (!$router_item || !$router_item['access']) {
1323 return '';
1324 }
1325 // Get all tabs and the root page.
1326 $result = db_query("SELECT * FROM {menu_router} WHERE tab_root = '%s' ORDER BY weight, title", $router_item['tab_root']);
1327 $map = arg();
1328 $children = array();
1329 $tasks = array();
1330 $root_path = $router_item['path'];
1331
1332 while ($item = db_fetch_array($result)) {
1333 _menu_translate($item, $map, TRUE);
1334 if ($item['tab_parent']) {
1335 // All tabs, but not the root page.
1336 $children[$item['tab_parent']][$item['path']] = $item;
1337 }
1338 // Store the translated item for later use.
1339 $tasks[$item['path']] = $item;
1340 }
1341
1342 // Find all tabs below the current path.
1343 $path = $router_item['path'];
1344 // Tab parenting may skip levels, so the number of parts in the path may not
1345 // equal the depth. Thus we use the $depth counter (offset by 1000 for ksort).
1346 $depth = 1001;
1347 while (isset($children[$path])) {
1348 $tabs_current = '';
1349 $next_path = '';
1350 $count = 0;
1351 foreach ($children[$path] as $item) {
1352 if ($item['access']) {
1353 $count++;
1354 // The default task is always active.
1355 if ($item['type'] == MENU_DEFAULT_LOCAL_TASK) {
1356 // Find the first parent which is not a default local task.
1357 for ($p = $item['tab_parent']; $tasks[$p]['type'] == MENU_DEFAULT_LOCAL_TASK; $p = $tasks[$p]['tab_parent']);
1358 $link = theme('menu_item_link', array('href' => $tasks[$p]['href']) + $item);
1359 $tabs_current .= theme('menu_local_task', $link, TRUE);
1360 $next_path = $item['path'];
1361 }
1362 else {
1363 $link = theme('menu_item_link', $item);
1364 $tabs_current .= theme('menu_local_task', $link);
1365 }
1366 }
1367 }
1368 $path = $next_path;
1369 $tabs[$depth]['count'] = $count;
1370 $tabs[$depth]['output'] = $tabs_current;
1371 $depth++;
1372 }
1373
1374 // Find all tabs at the same level or above the current one.
1375 $parent = $router_item['tab_parent'];
1376 $path = $router_item['path'];
1377 $current = $router_item;
1378 $depth = 1000;
1379 while (isset($children[$parent])) {
1380 $tabs_current = '';
1381 $next_path = '';
1382 $next_parent = '';
1383 $count = 0;
1384 foreach ($children[$parent] as $item) {
1385 if ($item['access']) {
1386 $count++;
1387 if ($item['type'] == MENU_DEFAULT_LOCAL_TASK) {
1388 // Find the first parent which is not a default local task.
1389 for ($p = $item['tab_parent']; $tasks[$p]['type'] == MENU_DEFAULT_LOCAL_TASK; $p = $tasks[$p]['tab_parent']);
1390 $link = theme('menu_item_link', array('href' => $tasks[$p]['href']) + $item);
1391 if ($item['path'] == $router_item['path']) {
1392 $root_path = $tasks[$p]['path'];
1393 }
1394 }
1395 else {
1396 $link = theme('menu_item_link', $item);
1397 }
1398 // We check for the active tab.
1399 if ($item['path'] == $path) {
1400 $tabs_current .= theme('menu_local_task', $link, TRUE);
1401 $next_path = $item['tab_parent'];
1402 if (isset($tasks[$next_path])) {
1403 $next_parent = $tasks[$next_path]['tab_parent'];
1404 }
1405 }
1406 else {
1407 $tabs_current .= theme('menu_local_task', $link);
1408 }
1409 }
1410 }
1411 $path = $next_path;
1412 $parent = $next_parent;
1413 $tabs[$depth]['count'] = $count;
1414 $tabs[$depth]['output'] = $tabs_current;
1415 $depth--;
1416 }
1417 // Sort by depth.
1418 ksort($tabs);
1419 // Remove the depth, we are interested only in their relative placement.
1420 $tabs = array_values($tabs);
1421 }
1422
1423 if ($return_root) {
1424 return $root_path;
1425 }
1426 else {
1427 // We do not display single tabs.
1428 return (isset($tabs[$level]) && $tabs[$level]['count'] > 1) ? $tabs[$level]['output'] : '';
1429 }
1430 }
1431
1432 /**
1433 * Returns the rendered local tasks at the top level.
1434 */
1435 function menu_primary_local_tasks() {
1436 return menu_local_tasks(0);
1437 }
1438
1439 /**
1440 * Returns the rendered local tasks at the second level.
1441 */
1442 function menu_secondary_local_tasks() {
1443 return menu_local_tasks(1);
1444 }
1445
1446 /**
1447 * Returns the router path, or the path of the parent tab of a default local task.
1448 */
1449 function menu_tab_root_path() {
1450 return menu_local_tasks(0, TRUE);
1451 }
1452
1453 /**
1454 * Returns the rendered local tasks. The default implementation renders them as tabs.
1455 *
1456 * @ingroup themeable
1457 */
1458 function theme_menu_local_tasks() {
1459 $output = '';
1460
1461 if ($primary = menu_primary_local_tasks()) {
1462 $output .= "<ul class=\"tabs primary\">\n". $primary ."</ul>\n";
1463 }
1464 if ($secondary = menu_secondary_local_tasks()) {
1465 $output .= "<ul class=\"tabs secondary\">\n". $secondary ."</ul>\n";
1466 }
1467
1468 return $output;
1469 }
1470
1471 /**
1472 * Set (or get) the active menu for the current page - determines the active trail.
1473 */
1474 function menu_set_active_menu_name($menu_name = NULL) {
1475 static $active;
1476
1477 if (isset($menu_name)) {
1478 $active = $menu_name;
1479 }
1480 elseif (!isset($active)) {
1481 $active = 'navigation';
1482 }
1483 return $active;
1484 }
1485
1486 /**
1487 * Get the active menu for the current page - determines the active trail.
1488 */
1489 function menu_get_active_menu_name() {
1490 return menu_set_active_menu_name();
1491 }
1492
1493 /**
1494 * Set the active path, which determines which page is loaded.
1495 *
1496 * @param $path
1497 * A Drupal path - not a path alias.
1498 *
1499 * Note that this may not have the desired effect unless invoked very early
1500 * in the page load, such as during hook_boot, or unless you call
1501 * menu_execute_active_handler() to generate your page output.
1502 */
1503 function menu_set_active_item($path) {
1504 $_GET['q'] = $path;
1505 }
1506
1507 /**
1508 * Sets or gets the active trail (path to root menu root) of the current page.
1509 *
1510 * @param $new_trail
1511 * Menu trail to set, or NULL to use previously-set or calculated trail. If
1512 * supplying a trail, use the same format as the return value (see below).
1513 *
1514 * @return
1515 * Path to menu root of the current page, as an array of menu link items,
1516 * starting with the site's home page. Each link item is an associative array
1517 * with the following components:
1518 * - title: Title of the item.
1519 * - href: Drupal path of the item.
1520 * - localized_options: Options for passing into the l() function.
1521 * - type: A menu type constant, such as MENU_DEFAULT_LOCAL_TASK, or 0 to
1522 * indicate it's not really in the menu (used for the home page item).
1523 * If $new_trail is supplied, the value is saved in a static variable and
1524 * returned. If $new_trail is not supplied, and there is a saved value from
1525 * a previous call, the saved value is returned. If $new_trail is not supplied
1526 * and there is no saved value, the path to the current page is calculated,
1527 * saved as the static value, and returned.
1528 */
1529 function menu_set_active_trail($new_trail = NULL) {
1530 static $trail;
1531
1532 if (isset($new_trail)) {
1533 $trail = $new_trail;
1534 }
1535 elseif (!isset($trail)) {
1536 $trail = array();
1537 $trail[] = array('title' => t('Home'), 'href' => '<front>', 'localized_options' => array(), 'type' => 0);
1538 $item = menu_get_item();
1539
1540 // Check whether the current item is a local task (displayed as a tab).
1541 if ($item['tab_parent']) {
1542 // The title of a local task is used for the tab, never the page title.
1543 // Thus, replace it with the item corresponding to the root path to get
1544 // the relevant href and title. For example, the menu item corresponding
1545 // to 'admin' is used when on the 'By module' tab at 'admin/by-module'.
1546 $parts = explode('/', $item['tab_root']);
1547 $args = arg();
1548 // Replace wildcards in the root path using the current path.
1549 foreach ($parts as $index => $part) {
1550 if ($part == '%') {
1551 $parts[$index] = $args[$index];
1552 }
1553 }
1554 // Retrieve the menu item using the root path after wildcard replacement.
1555 $root_item = menu_get_item(implode('/', $parts));
1556 if ($root_item && $root_item['access']) {
1557 $item = $root_item;
1558 }
1559 }
1560
1561 $tree = menu_tree_page_data(menu_get_active_menu_name());
1562 list($key, $curr) = each($tree);
1563
1564 while ($curr) {
1565 // Terminate the loop when we find the current path in the active trail.
1566 if ($curr['link']['href'] == $item['href']) {
1567 $trail[] = $curr['link'];
1568 $curr = FALSE;
1569 }
1570 else {
1571 // Add the link if it's in the active trail, then move to the link below.
1572 if ($curr['link']['in_active_trail']) {
1573 $trail[] = $curr['link'];
1574 $tree = $curr['below'] ? $curr['below'] : array();
1575 }
1576 list($key, $curr) = each($tree);
1577 }
1578 }
1579 // Make sure the current page is in the trail (needed for the page title),
1580 // but exclude tabs and the front page.
1581 $last = count($trail) - 1;
1582 if ($trail[$last]['href'] != $item['href'] && !(bool)($item['type'] & MENU_IS_LOCAL_TASK) && !drupal_is_front_page()) {
1583 $trail[] = $item;
1584 }
1585 }
1586 return $trail;
1587 }
1588
1589 /**
1590 * Gets the active trail (path to root menu root) of the current page.
1591 *
1592 * See menu_set_active_trail() for details of return value.
1593 */
1594 function menu_get_active_trail() {
1595 return menu_set_active_trail();
1596 }
1597
1598 /**
1599 * Get the breadcrumb for the current page, as determined by the active trail.
1600 */
1601 function menu_get_active_breadcrumb() {
1602 $breadcrumb = array();
1603
1604 // No breadcrumb for the front page.
1605 if (drupal_is_front_page()) {
1606 return $breadcrumb;
1607 }
1608
1609 $item = menu_get_item();
1610 if ($item && $item['access']) {
1611 $active_trail = menu_get_active_trail();
1612
1613 foreach ($active_trail as $parent) {
1614 $breadcrumb[] = l($parent['title'], $parent['href'], $parent['localized_options']);
1615 }
1616 $end = end($active_trail);
1617
1618 // Don't show a link to the current page in the breadcrumb trail.
1619 if ($item['href'] == $end['href'] || ($item['type'] == MENU_DEFAULT_LOCAL_TASK && $end['href'] != '<front>')) {
1620 array_pop($breadcrumb);
1621 }
1622 }
1623 return $breadcrumb;
1624 }
1625
1626 /**
1627 * Get the title of the current page, as determined by the active trail.
1628 */
1629 function menu_get_active_title() {
1630 $active_trail = menu_get_active_trail();
1631
1632 foreach (array_reverse($active_trail) as $item) {
1633 if (!(bool)($item['type'] & MENU_IS_LOCAL_TASK)) {
1634 return $item['title'];
1635 }
1636 }
1637 }
1638
1639 /**
1640 * Get a menu link by its mlid, access checked and link translated for rendering.
1641 *
1642 * This function should never be called from within node_load() or any other
1643 * function used as a menu object load function since an infinite recursion may
1644 * occur.
1645 *
1646 * @param $mlid
1647 * The mlid of the menu item.
1648 * @return
1649 * A menu link, with $item['access'] filled and link translated for
1650 * rendering.
1651 */
1652 function menu_link_load($mlid) {
1653 if (is_numeric($mlid) && $item = db_fetch_array(db_query("SELECT m.*, ml.* FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path WHERE ml.mlid = %d", $mlid))) {
1654 _menu_link_translate($item);
1655 return $item;
1656 }
1657 return FALSE;
1658 }
1659
1660 /**
1661 * Clears the cached cached data for a single named menu.
1662 */
1663 function menu_cache_clear($menu_name = 'navigation') {
1664 static $cache_cleared = array();
1665
1666 if (empty($cache_cleared[$menu_name])) {
1667 cache_clear_all('links:'. $menu_name .':', 'cache_menu', TRUE);
1668 $cache_cleared[$menu_name] = 1;
1669 }
1670 elseif ($cache_cleared[$menu_name] == 1) {
1671 register_shutdown_function('cache_clear_all', 'links:'. $menu_name .':', 'cache_menu', TRUE);
1672 $cache_cleared[$menu_name] = 2;
1673 }
1674 }
1675
1676 /**
1677 * Clears all cached menu data. This should be called any time broad changes
1678 * might have been made to the router items or menu links.
1679 */
1680 function menu_cache_clear_all() {
1681 cache_clear_all('*', 'cache_menu', TRUE);
1682 }
1683
1684 /**
1685 * (Re)populate the database tables used by various menu functions.
1686 *
1687 * This function will clear and populate the {menu_router} table, add entries
1688 * to {menu_links} for new router items, then remove stale items from
1689 * {menu_links}. If called from update.php or install.php, it will also
1690 * schedule a call to itself on the first real page load from
1691 * menu_execute_active_handler(), because the maintenance page environment
1692 * is different and leaves stale data in the menu tables.
1693 */
1694 function menu_rebuild() {
1695 if (!lock_acquire('menu_rebuild')) {
1696 // Wait for another request that is already doing this work.
1697 // We choose to block here since otherwise the router item may not
1698 // be avaiable in menu_execute_active_handler() resulting in a 404.
1699 lock_wait('menu_rebuild');
1700 return FALSE;
1701 }
1702
1703 $menu = menu_router_build(TRUE);
1704 _menu_navigation_links_rebuild($menu);
1705 // Clear the menu, page and block caches.
1706 menu_cache_clear_all();
1707 _menu_clear_page_cache();
1708
1709 if (defined('MAINTENANCE_MODE')) {
1710 variable_set('menu_rebuild_needed', TRUE);
1711 }
1712 else {
1713 variable_del('menu_rebuild_needed');
1714 }
1715 lock_release('menu_rebuild');
1716 return TRUE;
1717 }
1718
1719 /**
1720 * Collect, alter and store the menu definitions.
1721 */
1722 function menu_router_build($reset = FALSE) {
1723 static $menu;
1724
1725 if (!isset($menu) || $reset) {
1726 // We need to manually call each module so that we can know which module
1727 // a given item came from.
1728 $callbacks = array();
1729 foreach (module_implements('menu') as $module) {
1730 $router_items = call_user_func($module .'_menu');
1731 if (isset($router_items) && is_array($router_items)) {
1732 foreach (array_keys($router_items) as $path) {
1733 $router_items[$path]['module'] = $module;
1734 }
1735 $callbacks = array_merge($callbacks, $router_items);
1736 }
1737 }
1738 // Alter the menu as defined in modules, keys are like user/%user.
1739 drupal_alter('menu', $callbacks);
1740 $menu = _menu_router_build($callbacks);
1741 _menu_router_cache($menu);
1742 }
1743 return $menu;
1744 }
1745
1746 /**
1747 * Helper function to store the menu router if we have it in memory.
1748 */
1749 function _menu_router_cache($new_menu = NULL) {
1750 static $menu = NULL;
1751
1752 if (isset($new_menu)) {
1753 $menu = $new_menu;
1754 }
1755 return $menu;
1756 }
1757
1758 /**
1759 * Builds a link from a router item.
1760 */
1761 function _menu_link_build($item) {
1762 if ($item['type'] == MENU_CALLBACK) {
1763 $item['hidden'] = -1;
1764 }
1765 elseif ($item['type'] == MENU_SUGGESTED_ITEM) {
1766 $item['hidden'] = 1;
1767 }
1768 // Note, we set this as 'system', so that we can be sure to distinguish all
1769 // the menu links generated automatically from entries in {menu_router}.
1770 $item['module'] = 'system';
1771 $item += array(
1772 'menu_name' => 'navigation',
1773 'link_title' => $item['title'],
1774 'link_path' => $item['path'],
1775 'hidden' => 0,
1776 'options' => empty($item['description']) ? array() : array('attributes' => array('title' => $item['description'])),
1777 );
1778 return $item;
1779 }
1780
1781 /**
1782 * Helper function to build menu links for the items in the menu router.
1783 */
1784 function _menu_navigation_links_rebuild($menu) {
1785 // Add normal and suggested items as links.
1786 $menu_links = array();
1787 foreach ($menu as $path => $item) {
1788 if ($item['_visible']) {
1789 $item = _menu_link_build($item);
1790 $menu_links[$path] = $item;
1791 $sort[$path] = $item['_number_parts'];
1792 }
1793 }
1794 if ($menu_links) {
1795 // Make sure no child comes before its parent.
1796 array_multisort($sort, SORT_NUMERIC, $menu_links);
1797
1798 foreach ($menu_links as $item) {
1799 $existing_item = db_fetch_array(db_query("SELECT mlid, menu_name, plid, customized, has_children, updated FROM {menu_links} WHERE link_path = '%s' AND module = '%s'", $item['link_path'], 'system'));
1800 if ($existing_item) {
1801 $item['mlid'] = $existing_item['mlid'];
1802 // A change in hook_menu may move the link to a different menu
1803 if (empty($item['menu_name']) || ($item['menu_name'] == $existing_item['menu_name'])) {
1804 $item['menu_name'] = $existing_item['menu_name'];
1805 $item['plid'] = $existing_item['plid'];
1806 }
1807 $item['has_children'] = $existing_item['has_children'];
1808 $item['updated'] = $existing_item['updated'];
1809 }
1810 if (!$existing_item || !$existing_item['customized']) {
1811 menu_link_save($item);
1812 }
1813 }
1814 }
1815 $placeholders = db_placeholders($menu, 'varchar');
1816 $paths = array_keys($menu);
1817 // Updated and customized items whose router paths are gone need new ones.
1818 $result = db_query("SELECT ml.link_path, ml.mlid, ml.router_path, ml.updated FROM {menu_links} ml WHERE ml.updated = 1 OR (router_path NOT IN ($placeholders) AND external = 0 AND customized = 1)", $paths);
1819 while ($item = db_fetch_array($result)) {
1820 $router_path = _menu_find_router_path($item['link_path']);
1821 if (!empty($router_path) && ($router_path != $item['router_path'] || $item['updated'])) {
1822 // If the router path and the link path matches, it's surely a working
1823 // item, so we clear the updated flag.
1824 $updated = $item['updated'] && $router_path != $item['link_path'];
1825 db_query("UPDATE {menu_links} SET router_path = '%s', updated = %d WHERE mlid = %d", $router_path, $updated, $item['mlid']);
1826 }
1827 }
1828 // Find any item whose router path does not exist any more.
1829 $result = db_query("SELECT * FROM {menu_links} WHERE router_path NOT IN ($placeholders) AND external = 0 AND updated = 0 AND customized = 0 ORDER BY depth DESC", $paths);
1830 // Remove all such items. Starting from those with the greatest depth will
1831 // minimize the amount of re-parenting done by menu_link_delete().
1832 while ($item = db_fetch_array($result)) {
1833 _menu_delete_item($item, TRUE);
1834 }
1835 }
1836
1837 /**
1838 * Delete one or several menu links.
1839 *
1840 * @param $mlid
1841 * A valid menu link mlid or NULL. If NULL, $path is used.
1842 * @param $path
1843 * The path to the menu items to be deleted. $mlid must be NULL.
1844 */
1845 function menu_link_delete($mlid, $path = NULL) {
1846 if (isset($mlid)) {
1847 _menu_delete_item(db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d", $mlid)));
1848 }
1849 else {
1850 $result = db_query("SELECT * FROM {menu_links} WHERE link_path = '%s'", $path);
1851 while ($link = db_fetch_array($result)) {
1852 _menu_delete_item($link);
1853 }
1854 }
1855 }
1856
1857 /**
1858 * Helper function for menu_link_delete; deletes a single menu link.
1859 *
1860 * @param $item
1861 * Item to be deleted.
1862 * @param $force
1863 * Forces deletion. Internal use only, setting to TRUE is discouraged.
1864 */
1865 function _menu_delete_item($item, $force = FALSE) {
1866 if ($item && ($item['module'] != 'system' || $item['updated'] || $force)) {
1867 // Children get re-attached to the item's parent.
1868 if ($item['has_children']) {
1869 $result = db_query("SELECT mlid FROM {menu_links} WHERE plid = %d", $item['mlid']);
1870 while ($m = db_fetch_array($result)) {
1871 $child = menu_link_load($m['mlid']);
1872 $child['plid'] = $item['plid'];
1873 menu_link_save($child);
1874 }
1875 }
1876 db_query('DELETE FROM {menu_links} WHERE mlid = %d', $item['mlid']);
1877
1878 // Update the has_children status of the parent.
1879 _menu_update_parental_status($item);
1880 menu_cache_clear($item['menu_name']);
1881 _menu_clear_page_cache();
1882 }
1883 }
1884
1885 /**
1886 * Save a menu link.
1887 *
1888 * @param $item
1889 * An array representing a menu link item. The only mandatory keys are
1890 * link_path and link_title. Possible keys are:
1891 * - menu_name: Default is navigation.
1892 * - weight: Default is 0.
1893 * - expanded: Whether the item is expanded.
1894 * - options: An array of options, see l() for more.
1895 * - mlid: Set to an existing value, or 0 or NULL to insert a new link.
1896 * - plid: The mlid of the parent.
1897 * - router_path: The path of the relevant router item.
1898 *
1899 * @return
1900 * The mlid of the saved menu link, or FALSE if the menu link could not be
1901 * saved.
1902 */
1903 function menu_link_save(&$item) {
1904
1905 // Get the router if it's already in memory. $menu will be NULL, unless this
1906 // is during a menu rebuild
1907 $menu = _menu_router_cache();
1908 drupal_alter('menu_link', $item, $menu);
1909
1910 // This is the easiest way to handle the unique internal path '<front>',
1911 // since a path marked as external does not need to match a router path.
1912 $item['_external'] = menu_path_is_external($item['link_path']) || $item['link_path'] == '<front>';
1913 // Load defaults.
1914 $item += array(
1915 'menu_name' => 'navigation',
1916 'weight' => 0,
1917 'link_title' => '',
1918 'hidden' => 0,
1919 'has_children' => 0,
1920 'expanded' => 0,
1921 'options' => array(),
1922 'module' => 'menu',
1923 'customized' => 0,
1924 'updated' => 0,
1925 );
1926 $existing_item = FALSE;
1927 if (isset($item['mlid'])) {
1928 $existing_item = db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d", $item['mlid']));
1929 }
1930
1931 if (isset($item['plid'])) {
1932 $parent = db_fetch_array(db_query("SELECT * FROM {menu_links} WHERE mlid = %d", $item['plid']));
1933 }
1934 else {
1935 // Find the parent - it must be unique.
1936 $parent_path = $item['link_path'];
1937 $where = "WHERE link_path = '%s'";
1938 // Only links derived from router items should have module == 'system', and
1939 // we want to find the parent even if it's in a different menu.
1940 if ($item['module'] == 'system') {
1941 $where .= " AND module = '%s'";
1942 $arg2 = 'system';
1943 }
1944 else {
1945 // If not derived from a router item, we respect the specified menu name.
1946 $where .= " AND menu_name = '%s'";
1947 $arg2 = $item['menu_name'];
1948 }
1949 do {
1950 $parent = FALSE;
1951 $parent_path = substr($parent_path, 0, strrpos($parent_path, '/'));
1952 $result = db_query("SELECT COUNT(*) FROM {menu_links} ". $where, $parent_path, $arg2);
1953 // Only valid if we get a unique result.
1954 if (db_result($result) == 1) {
1955 $parent = db_fetch_array(db_query("SELECT * FROM {menu_links} ". $where, $parent_path, $arg2));
1956 }
1957 } while ($parent === FALSE && $parent_path);
1958 }
1959 if ($parent !== FALSE) {
1960 $item['menu_name'] = $parent['menu_name'];
1961 }
1962 $menu_name = $item['menu_name'];
1963 // Menu callbacks need to be in the links table for breadcrumbs, but can't
1964 // be parents if they are generated directly from a router item.
1965 if (empty($parent['mlid']) || $parent['hidden'] < 0) {
1966 $item['plid'] = 0;
1967 }
1968 else {
1969 $item['plid'] = $parent['mlid'];
1970 }
1971
1972 if (!$existing_item) {
1973 db_query("INSERT INTO {menu_links} (
1974 menu_name, plid, link_path,
1975 hidden, external, has_children,
1976 expanded, weight,
1977 module, link_title, options,
1978 customized, updated) VALUES (
1979 '%s', %d, '%s',
1980 %d, %d, %d,
1981 %d, %d,
1982 '%s', '%s', '%s', %d, %d)",
1983 $item['menu_name'], $item['plid'], $item['link_path'],
1984 $item['hidden'], $item['_external'], $item['has_children'],
1985 $item['expanded'], $item['weight'],
1986 $item['module'], $item['link_title'], serialize($item['options']),
1987 $item['customized'], $item['updated']);
1988 $item['mlid'] = db_last_insert_id('menu_links', 'mlid');
1989 }
1990
1991 if (!$item['plid']) {
1992 $item['p1'] = $item['mlid'];
1993 for ($i = 2; $i <= MENU_MAX_DEPTH; $i++) {
1994 $item["p$i"] = 0;
1995 }
1996 $item['depth'] = 1;
1997 }
1998 else {
1999 // Cannot add beyond the maximum depth.
2000 if ($item['has_children'] && $existing_item) {
2001 $limit = MENU_MAX_DEPTH - menu_link_children_relative_depth($existing_item) - 1;
2002 }
2003 else {
2004 $limit = MENU_MAX_DEPTH - 1;
2005 }
2006 if ($parent['depth'] > $limit) {
2007 return FALSE;
2008 }
2009 $item['depth'] = $parent['depth'] + 1;
2010 _menu_link_parents_set($item, $parent);
2011 }
2012 // Need to check both plid and menu_name, since plid can be 0 in any menu.
2013 if ($existing_item && ($item['plid'] != $existing_item['plid'] || $menu_name != $existing_item['menu_name'])) {
2014 _menu_link_move_children($item, $existing_item);
2015 }
2016 // Find the callback. During the menu update we store empty paths to be
2017 // fixed later, so we skip this.
2018 if (!isset($_SESSION['system_update_6021']) && (empty($item['router_path']) || !$existing_item || ($existing_item['link_path'] != $item['link_path']))) {
2019 if ($item['_external']) {
2020 $item['router_path'] = '';
2021 }
2022 else {
2023 // Find the router path which will serve this path.
2024 $item['parts'] = explode('/', $item['link_path'], MENU_MAX_PARTS);
2025 $item['router_path'] = _menu_find_router_path($item['link_path']);
2026 }
2027 }
2028 db_query("UPDATE {menu_links} SET menu_name = '%s', plid = %d, link_path = '%s',
2029 router_path = '%s', hidden = %d, external = %d, has_children = %d,
2030 expanded = %d, weight = %d, depth = %d,
2031 p1 = %d, p2 = %d, p3 = %d, p4 = %d, p5 = %d, p6 = %d, p7 = %d, p8 = %d, p9 = %d,
2032 module = '%s', link_title = '%s', options = '%s', customized = %d WHERE mlid = %d",
2033 $item['menu_name'], $item['plid'], $item['link_path'],
2034 $item['router_path'], $item['hidden'], $item['_external'], $item['has_children'],
2035 $item['expanded'], $item['weight'], $item['depth'],
2036 $item['p1'], $item['p2'], $item['p3'], $item['p4'], $item['p5'], $item['p6'], $item['p7'], $item['p8'], $item['p9'],
2037 $item['module'], $item['link_title'], serialize($item['options']), $item['customized'], $item['mlid']);
2038 // Check the has_children status of the parent.
2039 _menu_update_parental_status($item);
2040 menu_cache_clear($menu_name);
2041 if ($existing_item && $menu_name != $existing_item['menu_name']) {
2042 menu_cache_clear($existing_item['menu_name']);
2043 }
2044
2045 _menu_clear_page_cache();
2046 return $item['mlid'];
2047 }
2048
2049 /**
2050 * Helper function to clear the page and block caches at most twice per page load.
2051 */
2052 function _menu_clear_page_cache() {
2053 static $cache_cleared = 0;
2054
2055 // Clear the page and block caches, but at most twice, including at
2056 // the end of the page load when there are multple links saved or deleted.
2057 if (empty($cache_cleared)) {
2058 cache_clear_all();
2059 // Keep track of which menus have expanded items.
2060 _menu_set_expanded_menus();
2061 $cache_cleared = 1;
2062 }
2063 elseif ($cache_cleared == 1) {
2064 register_shutdown_function('cache_clear_all');
2065 // Keep track of which menus have expanded items.
2066 register_shutdown_function('_menu_set_expanded_menus');
2067 $cache_cleared = 2;
2068 }
2069 }
2070
2071 /**
2072 * Helper function to update a list of menus with expanded items
2073 */
2074 function _menu_set_expanded_menus() {
2075 $names = array();
2076 $result = db_query("SELECT menu_name FROM {menu_links} WHERE expanded != 0 GROUP BY menu_name");
2077 while ($n = db_fetch_array($result)) {
2078 $names[] = $n['menu_name'];
2079 }
2080 variable_set('menu_expanded', $names);
2081 }
2082
2083 /**
2084 * Find the router path which will serve this path.
2085 *
2086 * @param $link_path
2087 * The path for we are looking up its router path.
2088 * @return
2089 * A path from $menu keys or empty if $link_path points to a nonexisting
2090 * place.
2091 */
2092 function _menu_find_router_path($link_path) {
2093 // $menu will only have data during a menu rebuild.
2094 $menu = _menu_router_cache();
2095
2096 $router_path = $link_path;
2097 $parts = explode('/', $link_path, MENU_MAX_PARTS);
2098 list($ancestors, $placeholders) = menu_get_ancestors($parts);
2099
2100 if (empty($menu)) {
2101 // Not during a menu rebuild, so look up in the database.
2102 $router_path = (string)db_result(db_query_range('SELECT path FROM {menu_router} WHERE path IN ('. implode (',', $placeholders) .') ORDER BY fit DESC', $ancestors, 0, 1));
2103 }
2104 elseif (!isset($menu[$router_path])) {
2105 // Add an empty path as a fallback.
2106 $ancestors[] = '';
2107 foreach ($ancestors as $key => $router_path) {
2108 if (isset($menu[$router_path])) {
2109 // Exit the loop leaving $router_path as the first match.
2110 break;
2111 }
2112 }
2113 // If we did not find the path, $router_path will be the empty string
2114 // at the end of $ancestors.
2115 }
2116 return $router_path;
2117 }
2118
2119 /**
2120 * Insert, update or delete an uncustomized menu link related to a module.
2121 *
2122 * @param $module
2123 * The name of the module.
2124 * @param $op
2125 * Operation to perform: insert, update or delete.
2126 * @param $link_path
2127 * The path this link points to.
2128 * @param $link_title
2129 * Title of the link to insert or new title to update the link to.
2130 * Unused for delete.
2131 * @return
2132 * The insert op returns the mlid of the new item. Others op return NULL.
2133 */
2134 function menu_link_maintain($module, $op, $link_path, $link_title) {
2135 switch ($op) {
2136 case 'insert':
2137 $menu_link = array(
2138 'link_title' => $link_title,
2139 'link_path' => $link_path,
2140 'module' => $module,
2141 );
2142 return menu_link_save($menu_link);
2143 break;
2144 case 'update':
2145 db_query("UPDATE {menu_links} SET link_title = '%s' WHERE link_path = '%s' AND customized = 0 AND module = '%s'", $link_title, $link_path, $module);
2146 $result = db_query("SELECT menu_name FROM {menu_links} WHERE link_path = '%s' AND customized = 0 AND module = '%s'", $link_path, $module);
2147 while ($item = db_fetch_array($result)) {
2148 menu_cache_clear($item['menu_name']);
2149 }
2150 break;
2151 case 'delete':
2152 menu_link_delete(NULL, $link_path);
2153 break;
2154 }
2155 }
2156
2157 /**
2158 * Find the depth of an item's children relative to its depth.
2159 *
2160 * For example, if the item has a depth of 2, and the maximum of any child in
2161 * the menu link tree is 5, the relative depth is 3.
2162 *
2163 * @param $item
2164 * An array representing a menu link item.
2165 * @return
2166 * The relative depth, or zero.
2167 *
2168 */
2169 function menu_link_children_relative_depth($item) {
2170 $i = 1;
2171 $match = '';
2172 $args[] = $item['menu_name'];
2173 $p = 'p1';
2174 while ($i <= MENU_MAX_DEPTH && $item[$p]) {
2175 $match .= " AND $p = %d";
2176 $args[] = $item[$p];
2177 $p = 'p'. ++$i;
2178 }
2179
2180 $max_depth = db_result(db_query_range("SELECT depth FROM {menu_links} WHERE menu_name = '%s'". $match ." ORDER BY depth DESC", $args, 0, 1));
2181
2182 return ($max_depth > $item['depth']) ? $max_depth - $item['depth'] : 0;
2183 }
2184
2185 /**
2186 * Update the children of a menu link that's being moved.
2187 *
2188 * The menu name, parents (p1 - p6), and depth are updated for all children of
2189 * the link, and the has_children status of the previous parent is updated.
2190 */
2191 function _menu_link_move_children($item, $existing_item) {
2192
2193 $args[] = $item['menu_name'];
2194 $set[] = "menu_name = '%s'";
2195
2196 $i = 1;
2197 while ($i <= $item['depth']) {
2198 $p = 'p'. $i++;
2199 $set[] = "$p = %d";
2200 $args[] = $item[$p];
2201 }
2202 $j = $existing_item['depth'] + 1;
2203 while ($i <= MENU_MAX_DEPTH && $j <= MENU_MAX_DEPTH) {
2204 $set[] = 'p'. $i++ .' = p'. $j++;
2205 }
2206 while ($i <= MENU_MAX_DEPTH) {
2207 $set[] = 'p'. $i++ .' = 0';
2208 }
2209
2210 $shift = $item['depth'] - $existing_item['depth'];
2211 if ($shift < 0) {
2212 $args[] = -$shift;
2213 $set[] = 'depth = depth - %d';
2214 }
2215 elseif ($shift > 0) {
2216 // The order of $set must be reversed so the new values don't overwrite the
2217 // old ones before they can be used because "Single-table UPDATE
2218 // assignments are generally evaluated from left to right"
2219 // see: http://dev.mysql.com/doc/refman/5.0/en/update.html
2220 $set = array_reverse($set);
2221 $args = array_reverse($args);
2222
2223 $args[] = $shift;
2224 $set[] = 'depth = depth + %d';
2225 }
2226 $where[] = "menu_name = '%s'";
2227 $args[] = $existing_item['menu_name'];
2228 $p = 'p1';
2229 for ($i = 1; $i <= MENU_MAX_DEPTH && $existing_item[$p]; $p = 'p'. ++$i) {
2230 $where[] = "$p = %d";
2231 $args[] = $existing_item[$p];
2232 }
2233
2234 db_query("UPDATE {menu_links} SET ". implode(', ', $set) ." WHERE ". implode(' AND ', $where), $args);
2235 // Check the has_children status of the parent, while excluding this item.
2236 _menu_update_parental_status($existing_item, TRUE);
2237 }
2238
2239 /**
2240 * Check and update the has_children status for the parent of a link.
2241 */
2242 function _menu_update_parental_status($item, $exclude = FALSE) {
2243 // If plid == 0, there is nothing to update.
2244 if ($item['plid']) {
2245 // We may want to exclude the passed link as a possible child.
2246 $where = $exclude ? " AND mlid != %d" : '';
2247 // Check if at least one visible child exists in the table.
2248 $parent_has_children = (bool)db_result(db_query_range("SELECT mlid FROM {menu_links} WHERE menu_name = '%s' AND plid = %d AND hidden = 0". $where, $item['menu_name'], $item['plid'], $item['mlid'], 0, 1));
2249 db_query("UPDATE {menu_links} SET has_children = %d WHERE mlid = %d", $parent_has_children, $item['plid']);
2250 }
2251 }
2252
2253 /**
2254 * Helper function that sets the p1..p9 values for a menu link being saved.
2255 */
2256 function _menu_link_parents_set(&$item, $parent) {
2257 $i = 1;
2258 while ($i < $item['depth']) {
2259 $p = 'p'. $i++;
2260 $item[$p] = $parent[$p];
2261 }
2262 $p = 'p'. $i++;
2263 // The parent (p1 - p9) corresponding to the depth always equals the mlid.
2264 $item[$p] = $item['mlid'];
2265 while ($i <= MENU_MAX_DEPTH) {
2266 $p = 'p'. $i++;
2267 $item[$p] = 0;
2268 }
2269 }
2270
2271 /**
2272 * Helper function to build the router table based on the data from hook_menu.
2273 */
2274 function _menu_router_build($callbacks) {
2275 // First pass: separate callbacks from paths, making paths ready for
2276 // matching. Calculate fitness, and fill some default values.
2277 $menu = array();
2278 foreach ($callbacks as $path => $item) {
2279 $load_functions = array();
2280 $to_arg_functions = array();
2281 $fit = 0;
2282 $move = FALSE;
2283
2284 $parts = explode('/', $path, MENU_MAX_PARTS);
2285 $number_parts = count($parts);
2286 // We store the highest index of parts here to save some work in the fit
2287 // calculation loop.
2288 $slashes = $number_parts - 1;
2289 // Extract load and to_arg functions.
2290 foreach ($parts as $k => $part) {
2291 $match = FALSE;
2292 // Look for wildcards in the form allowed to be used in PHP functions,
2293 // because we are using these to construct the load function names.
2294 // See http://php.net/manual/en/language.functions.php for reference.
2295 if (preg_match('/^%(|[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$/', $part, $matches)) {
2296 if (empty($matches[1])) {
2297 $match = TRUE;
2298 $load_functions[$k] = NULL;
2299 }
2300 else {
2301 if (function_exists($matches[1] .'_to_arg')) {
2302 $to_arg_functions[$k] = $matches[1] .'_to_arg';
2303 $load_functions[$k] = NULL;
2304 $match = TRUE;
2305 }
2306 if (function_exists($matches[1] .'_load')) {
2307 $function = $matches[1] .'_load';
2308 // Create an array of arguments that will be passed to the _load
2309 // function when this menu path is checked, if 'load arguments'
2310 // exists.
2311 $load_functions[$k] = isset($item['load arguments']) ? array($function => $item['load arguments']) : $function;
2312 $match = TRUE;
2313 }
2314 }
2315 }
2316 if ($match) {
2317 $parts[$k] = '%';
2318 }
2319 else {
2320 $fit |= 1 << ($slashes - $k);
2321 }
2322 }
2323 if ($fit) {
2324 $move = TRUE;
2325 }
2326 else {
2327 // If there is no %, it fits maximally.
2328 $fit = (1 << $number_parts) - 1;
2329 }
2330 $masks[$fit] = 1;
2331 $item['load_functions'] = empty($load_functions) ? '' : serialize($load_functions);
2332 $item['to_arg_functions'] = empty($to_arg_functions) ? '' : serialize($to_arg_functions);
2333 $item += array(
2334 'title' => '',
2335 'weight' => 0,
2336 'type' => MENU_NORMAL_ITEM,
2337 '_number_parts' => $number_parts,
2338 '_parts' => $parts,
2339 '_fit' => $fit,
2340 );
2341 $item += array(
2342 '_visible' => (bool)($item['type'] & MENU_VISIBLE_IN_BREADCRUMB),
2343 '_tab' => (bool)($item['type'] & MENU_IS_LOCAL_TASK),
2344 );
2345 if ($move) {
2346 $new_path = implode('/', $item['_parts']);
2347 $menu[$new_path] = $item;
2348 $sort[$new_path] = $number_parts;
2349 }
2350 else {
2351 $menu[$path] = $item;
2352 $sort[$path] = $number_parts;
2353 }
2354 }
2355 array_multisort($sort, SORT_NUMERIC, $menu);
2356
2357 if (!$menu) {
2358 // We must have a serious error - there is no data to save.
2359 watchdog('php', 'Menu router rebuild failed - some paths may not work correctly.', array(), WATCHDOG_ERROR);
2360 return array();
2361 }
2362 // Delete the existing router since we have some data to replace it.
2363 db_query('DELETE FROM {menu_router}');
2364 // Apply inheritance rules.
2365 foreach ($menu as $path => $v) {
2366 $item = &$menu[$path];
2367 if (!$item['_tab']) {
2368 // Non-tab items.
2369 $item['tab_parent'] = '';
2370 $item['tab_root'] = $path;
2371 }
2372 for ($i = $item['_number_parts'] - 1; $i; $i--) {
2373 $parent_path = implode('/', array_slice($item['_parts'], 0, $i));
2374 if (isset($menu[$parent_path])) {
2375
2376 $parent = $menu[$parent_path];
2377
2378 if (!isset($item['tab_parent'])) {
2379 // Parent stores the parent of the path.
2380 $item['tab_parent'] = $parent_path;
2381 }
2382 if (!isset($item['tab_root']) && !$parent['_tab']) {
2383 $item['tab_root'] = $parent_path;
2384 }
2385 // If an access callback is not found for a default local task we use
2386 // the callback from the parent, since we expect them to be identical.
2387 // In all other cases, the access parameters must be specified.
2388 if (($item['type'] == MENU_DEFAULT_LOCAL_TASK) && !isset($item['access callback']) && isset($parent['access callback'])) {
2389 $item['access callback'] = $parent['access callback'];
2390 if (!isset($item['access arguments']) && isset($parent['access arguments'])) {
2391 $item['access arguments'] = $parent['access arguments'];
2392 }
2393 }
2394 // Same for page callbacks.
2395 if (!isset($item['page callback']) && isset($parent['page callback'])) {
2396 $item['page callback'] = $parent['page callback'];
2397 if (!isset($item['page arguments']) && isset($parent['page arguments'])) {
2398 $item['page arguments'] = $parent['page arguments'];
2399 }
2400 if (!isset($item['file']) && isset($parent['file'])) {
2401 $item['file'] = $parent['file'];
2402 }
2403 if (!isset($item['file path']) && isset($parent['file path'])) {
2404 $item['file path'] = $parent['file path'];
2405 }
2406 }
2407 }
2408 }
2409 if (!isset($item['access callback']) && isset($item['access arguments'])) {
2410 // Default callback.
2411 $item['access callback'] = 'user_access';
2412 }
2413 if (!isset($item['access callback']) || empty($item['page callback'])) {
2414 $item['access callback'] = 0;
2415 }
2416 if (is_bool($item['access callback'])) {
2417 $item['access callback'] = intval($item['access callback']);
2418 }
2419
2420 $item += array(
2421 'access arguments' => array(),
2422 'access callback' => '',
2423 'page arguments' => array(),
2424 'page callback' => '',
2425 'block callback' => '',
2426 'title arguments' => array(),
2427 'title callback' => 't',
2428 'description' => '',
2429 'position' => '',
2430 'tab_parent' => '',
2431 'tab_root' => $path,
2432 'path' => $path,
2433 'file' => '',
2434 'file path' => '',
2435 'include file' => '',
2436 'module' => '',
2437 );
2438
2439 // Calculate out the file to be included for each callback, if any.
2440 if ($item['file']) {
2441 $file_path = $item['file path'] ? $item['file path'] : drupal_get_path('module', $item['module']);
2442 $item['include file'] = $file_path .'/'. $item['file'];
2443 }
2444
2445 $title_arguments = $item['title arguments'] ? serialize($item['title arguments']) : '';
2446 db_query("INSERT INTO {menu_router}
2447 (path, load_functions, to_arg_functions, access_callback,
2448 access_arguments, page_callback, page_arguments, fit,
2449 number_parts, tab_parent, tab_root,
2450 title, title_callback, title_arguments,
2451 type, block_callback, description, position, weight, file)
2452 VALUES ('%s', '%s', '%s', '%s',
2453 '%s', '%s', '%s', %d,
2454 %d, '%s', '%s',
2455 '%s', '%s', '%s',
2456 %d, '%s', '%s', '%s', %d, '%s')",
2457 $path, $item['load_functions'], $item['to_arg_functions'], $item['access callback'],
2458 serialize($item['access arguments']), $item['page callback'], serialize($item['page arguments']), $item['_fit'],
2459 $item['_number_parts'], $item['tab_parent'], $item['tab_root'],
2460 $item['title'], $item['title callback'], $title_arguments,
2461 $item['type'], $item['block callback'], $item['description'], $item['position'], $item['weight'], $item['include file']);
2462 }
2463 // Sort the masks so they are in order of descending fit, and store them.
2464 $masks = array_keys($masks);
2465 rsort($masks);
2466 variable_set('menu_masks', $masks);
2467
2468 return $menu;
2469 }
2470
2471 /**
2472 * Returns TRUE if a path is external (e.g. http://example.com).
2473 */
2474 function menu_path_is_external($path) {
2475 $colonpos = strpos($path, ':');
2476 return $colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path);
2477 }
2478
2479 /**
2480 * Checks whether the site is off-line for maintenance.
2481 *
2482 * This function will log the current user out and redirect to front page
2483 * if the current user has no 'administer site configuration' permission.
2484 *
2485 * @return
2486 * FALSE if the site is not off-line or its the login page or the user has
2487 * 'administer site configuration' permission.
2488 * TRUE for anonymous users not on the login page if the site is off-line.
2489 */
2490 function _menu_site_is_offline() {
2491 // Check if site is set to off-line mode.
2492 if (variable_get('site_offline', 0)) {
2493 // Check if the user has administration privileges.
2494 if (user_access('administer site configuration')) {
2495 // Ensure that the off-line message is displayed only once [allowing for
2496 // page redirects], and specifically suppress its display on the site
2497 // maintenance page.
2498 if (drupal_get_normal_path($_GET['q']) != 'admin/settings/site-maintenance') {
2499 drupal_set_message(l(t('Operating in off-line mode.'), 'admin/settings/site-maintenance'), 'status', FALSE);
2500 }
2501 }
2502 else {
2503 // Anonymous users get a FALSE at the login prompt, TRUE otherwise.
2504 if (user_is_anonymous()) {
2505 return $_GET['q'] != 'user' && $_GET['q'] != 'user/login';
2506 }
2507 // Logged in users are unprivileged here, so they are logged out.
2508 require_once drupal_get_path('module', 'user') .'/user.pages.inc';
2509 user_logout();
2510 }
2511 }
2512 return FALSE;
2513 }
2514
2515 /**
2516 * Validates the path of a menu link being created or edited.
2517 *
2518 * @return
2519 * TRUE if it is a valid path AND the current user has access permission,
2520 * FALSE otherwise.
2521 */
2522 function menu_valid_path($form_item) {
2523 global $menu_admin;
2524 $item = array();
2525 $path = $form_item['link_path'];
2526 // We indicate that a menu administrator is running the menu access check.
2527 $menu_admin = TRUE;
2528 if ($path == '<front>' || menu_path_is_external($path)) {
2529 $item = array('access' => TRUE);
2530 }
2531 elseif (preg_match('/\/\%/', $path)) {
2532 // Path is dynamic (ie 'user/%'), so check directly against menu_router table.
2533 if ($item = db_fetch_array(db_query("SELECT * FROM {menu_router} where path = '%s' ", $path))) {
2534 $item['link_path'] = $form_item['link_path'];
2535 $item['link_title'] = $form_item['link_title'];
2536 $item['external'] = FALSE;
2537 $item['options'] = '';
2538 _menu_link_translate($item);
2539 }
2540 }
2541 else {
2542 $item = menu_get_item($path);
2543 }
2544 $menu_admin = FALSE;
2545 return $item && $item['access'];
2546 }
2547
2548 /**
2549 * @} End of "defgroup menu".
2550 */