Spike PHPCoverage Details: menu.module

Line #FrequencySource Line
1 <?php
2 // $Id: menu.module,v 1.159 2008/02/20 13:46:40 dries Exp $
3 
4 /**
5  * @file
6  * Allows administrators to customize the site navigation menu.
7  */
8 
9 /**
10  * Maximum length of menu name as entered by the user. Database length is 32
11  * and we add a menu- prefix.
12  */
13 define('MENU_MAX_MENU_NAME_LENGTH_UI', 27);
14 
15 /**
16  * Implementation of hook_help().
17  */
18 function menu_help($path, $arg) {
19   switch ($path) {
20     case 'admin/help#menu':
21       $output = '<p>'. t("The menu module provides an interface to control and customize Drupal's powerful menu system. Menus are a hierarchical collection of links, or menu items, used to navigate a website, and are positioned and displayed using Drupal's flexible block system. By default, three menus are created during installation: <em>Navigation</em>, <em>Primary links</em>, and <em>Secondary links</em>. The <em>Navigation</em> menu contains most links necessary for working with and navigating your site, and is often displayed in either the left or right sidebar. Most Drupal themes also provide support for <em>Primary links</em> and <em>Secondary links</em>, by displaying them in either the header or footer of each page. By default, <em>Primary links</em> and <em>Secondary links</em> contain no menu items but may be configured to contain custom menu items specific to your site.") .'</p>';
22       $output .= '<p>'. t('The <a href="@menu">menus page</a> displays all menus currently available on your site. Select a menu from this list to add or edit a menu item, or to rearrange items within the menu. Create new menus using the <a href="@add-menu">add menu page</a> (the block containing a new menu must also be enabled on the <a href="@blocks">blocks administration page</a>).', array('@menu' => url('admin/build/menu'), '@add-menu' => url('build/menu/add'), '@blocks' => url('admin/build/block'))) .'</p>';
23       $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@menu">Menu module</a>.', array('@menu' => 'http://drupal.org/handbook/modules/menu/')) .'</p>';
24       return $output;
25     case 'admin/build/menu':
26       return '<p>'. t('Menus are a collection of links (menu items) used to navigate a website. The menus currently available on your site are displayed below. Select a menu from this list to manage its menu items.') .'</p>';
27     case 'build/menu/add':
28       return '<p>'. t('Enter the name for your new menu. Remember to enable the newly created block in the <a href="@blocks">blocks administration page</a>.', array('@blocks' => url('admin/build/block'))) .'</p>';
29     case 'admin/build/menu-customize/%':
30       return '<p>'. t('To rearrange menu items, grab a drag-and-drop handle under the <em>Menu item</em> column and drag the items (or group of items) to a new location in the list. (Grab a handle by clicking and holding the mouse while hovering over a handle icon.) Remember that your changes will not be saved until you click the <em>Save configuration</em> button at the bottom of the page.') .'<p>';
31     case 'admin/build/menu/item/add':
32       return '<p>'. t('Enter the title and path for your new menu item.') .'</p>';
33   }
34 }
35 
36 /**
37  * Implementation of hook_perm().
38  */
39 function menu_perm() {
40   return array(
41     'administer menu' => t('Manage menus and menu items.'),
42   );
43 }
44 
45 /**
46  * Implementation of hook_menu().
47  */
48 function menu_menu() {
49   $items['admin/build/menu'] = array(
501    'title' => 'Menus',
51     'description' => "Control your site's navigation menu, primary links and secondary links. as well as rename and reorganize menu items.",
52     'page callback' => 'menu_overview_page',
53     'access callback' => 'user_access',
54     'access arguments' => array('administer menu'),
55     'file' => 'menu.admin.inc',
56   );
57 
58   $items['admin/build/menu/list'] = array(
591    'title' => 'List menus',
60     'type' => MENU_DEFAULT_LOCAL_TASK,
61     'weight' => -10,
62     'file' => 'menu.admin.inc',
63   );
64   $items['build/menu/add'] = array(
651    'title' => 'Add menu',
66     'page callback' => 'drupal_get_form',
67     'page arguments' => array('menu_edit_menu', 'add'),
68     'type' => MENU_LOCAL_TASK,
69     'file' => 'menu.admin.inc',
70   );
71   $items['admin/build/menu/settings'] = array(
721    'title' => 'Settings',
73     'page callback' => 'drupal_get_form',
74     'page arguments' => array('menu_configure'),
75     'type' => MENU_LOCAL_TASK,
76     'weight' => 5,
77     'file' => 'menu.admin.inc',
78   );
79   $items['admin/build/menu-customize/%menu'] = array(
801    'title' => 'Customize menu',
81     'page callback' => 'drupal_get_form',
82     'page arguments' => array('menu_overview_form', 3),
83     'title callback' => 'menu_overview_title',
84     'title arguments' => array(3),
85     'access arguments' => array('administer menu'),
86     'type' => MENU_CALLBACK,
87     'file' => 'menu.admin.inc',
88   );
89   $items['admin/build/menu-customize/%menu/list'] = array(
901    'title' => 'List items',
91     'weight' => -10,
92     'type' => MENU_DEFAULT_LOCAL_TASK,
93     'file' => 'menu.admin.inc',
94   );
95   $items['admin/build/menu-customize/%menu/add'] = array(
961    'title' => 'Add item',
97     'page callback' => 'drupal_get_form',
98     'page arguments' => array('menu_edit_item', 'add', NULL, 3),
99     'type' => MENU_LOCAL_TASK,
100     'file' => 'menu.admin.inc',
101   );
102   $items['admin/build/menu-customize/%menu/edit'] = array(
1031    'title' => 'Edit menu',
104     'page callback' => 'drupal_get_form',
105     'page arguments' => array('menu_edit_menu', 'edit', 3),
106     'type' => MENU_LOCAL_TASK,
107     'file' => 'menu.admin.inc',
108   );
109   $items['admin/build/menu-customize/%menu/delete'] = array(
1101    'title' => 'Delete menu',
111     'page callback' => 'menu_delete_menu_page',
112     'page arguments' => array(3),
113     'type' => MENU_CALLBACK,
114     'file' => 'menu.admin.inc',
115   );
116   $items['admin/build/menu/item/%menu_link/edit'] = array(
1171    'title' => 'Edit menu item',
118     'page callback' => 'drupal_get_form',
119     'page arguments' => array('menu_edit_item', 'edit', 4, NULL),
120     'type' => MENU_CALLBACK,
121     'file' => 'menu.admin.inc',
122   );
123   $items['admin/build/menu/item/%menu_link/reset'] = array(
1241    'title' => 'Reset menu item',
125     'page callback' => 'drupal_get_form',
126     'page arguments' => array('menu_reset_item_confirm', 4),
127     'type' => MENU_CALLBACK,
128     'file' => 'menu.admin.inc',
129   );
130   $items['admin/build/menu/item/%menu_link/delete'] = array(
1311    'title' => 'Delete menu item',
132     'page callback' => 'menu_item_delete_page',
133     'page arguments' => array(4),
134     'type' => MENU_CALLBACK,
135     'file' => 'menu.admin.inc',
136   );
137 
1381  return $items;
139 }
140 
141 /**
142  * Implemenation of hook_theme().
143  */
144 function menu_theme() {
145   return array(
146     'menu_overview_form' => array(
147       'file' => 'menu.admin.inc',
148       'arguments' => array('form' => NULL),
149     ),
150   );
151 }
152 
153 /**
154  * Implementation of hook_enable()
155  *
156  *  Add a link for each custom menu.
157  */
158 function menu_enable() {
1591  menu_rebuild();
1601  $link = db_fetch_array(db_query("SELECT mlid AS plid, menu_name from {menu_links} WHERE link_path = 'admin/build/menu' AND module = 'system'"));
1611  $link['router_path'] = 'admin/build/menu-customize/%';
1621  $link['module'] = 'menu';
1631  $result = db_query("SELECT * FROM {menu_custom}");
1641  while ($menu = db_fetch_array($result)) {
1651    $link['mlid'] = 0;
1661    $link['link_title'] = $menu['title'];
1671    $link['link_path'] = 'admin/build/menu-customize/'. $menu['menu_name'];
1681    if (!db_result(db_query("SELECT mlid FROM {menu_links} WHERE link_path = '%s' AND plid = %d", $link['link_path'], $link['plid']))) {
1691      menu_link_save($link);
170     }
171   }
1721  menu_cache_clear_all();
173 }
174 
175 /**
176  * Title callback for the menu overview page and links.
177  */
178 function menu_overview_title($menu) {
179   return $menu['title'];
180 }
181 
182 /**
183  * Load the data for a single custom menu.
184  */
185 function menu_load($menu_name) {
186   return db_fetch_array(db_query("SELECT * FROM {menu_custom} WHERE menu_name = '%s'", $menu_name));
187 }
188 
189 /**
190  * Return a list of menu items that are valid possible parents for the given menu item.
191  *
192  * @param $menus
193  *   An array of menu names and titles, such as from menu_get_menus().
194  * @param $item
195  *   The menu item for which to generate a list of parents.
196  *   If $item['mlid'] == 0 then the complete tree is returned.
197  * @return
198  *   An array of menu link titles keyed on the a string containing the menu name
199  *   and mlid. The list excludes the given item and its children.
200  */
201 function menu_parent_options($menus, $item) {
202   // The menu_links table can be practically any size and we need a way to
203   // allow contrib modules to provide more scalable pattern choosers.
204   // hook_form_alter is too late in itself because all the possible parents are
205   // retrieved here, unless menu_override_parent_selector is set to TRUE.
206   if (variable_get('menu_override_parent_selector', FALSE)) {
207     return array();
208   }
209   // If the item has children, there is an added limit to the depth of valid parents.
210   if (isset($item['parent_depth_limit'])) {
211     $limit = $item['parent_depth_limit'];
212   }
213   else {
214     $limit = _menu_parent_depth_limit($item);
215   }
216 
217   foreach ($menus as $menu_name => $title) {
218     $tree = menu_tree_all_data($menu_name, NULL);
219     $options[$menu_name .':0'] = '<'. $title .'>';
220     _menu_parents_recurse($tree, $menu_name, '--', $options, $item['mlid'], $limit);
221   }
222   return $options;
223 }
224 
225 /**
226  * Recursive helper function for menu_parent_options().
227  */
228 function _menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude, $depth_limit) {
229   foreach ($tree as $data) {
230     if ($data['link']['depth'] > $depth_limit) {
231       // Don't iterate through any links on this level.
232       break;
233     }
234     if ($data['link']['mlid'] != $exclude && $data['link']['hidden'] >= 0) {
235       $title = $indent .' '. truncate_utf8($data['link']['title'], 30, TRUE, FALSE);
236       if ($data['link']['hidden']) {
237         $title .= ' ('. t('disabled') .')';
238       }
239       $options[$menu_name .':'. $data['link']['mlid']] = $title;
240       if ($data['below']) {
241         _menu_parents_recurse($data['below'], $menu_name, $indent .'--', $options, $exclude, $depth_limit);
242       }
243     }
244   }
245 }
246 
247 /**
248  * Reset a system-defined menu item.
249  */
250 function menu_reset_item($item) {
251   $router = menu_router_build();
252   $new_item = _menu_link_build($router[$item['router_path']]);
253   foreach (array('mlid', 'has_children') as $key) {
254     $new_item[$key] = $item[$key];
255   }
256   menu_link_save($new_item);
257   return $new_item;
258 }
259 
260 /**
261  * Implementation of hook_block().
262  */
263 function menu_block($op = 'list', $delta = 0) {
264   $menus = menu_get_menus();
265   // The Navigation menu is handled by the user module.
266   unset($menus['navigation']);
267   if ($op == 'list') {
268     $blocks = array();
269     foreach ($menus as $name => $title) {
270       // Default "Navigation" block is handled by user.module.
271       $blocks[$name]['info'] = check_plain($title);
272       // Menu blocks can't be cached because each menu item can have
273       // a custom access callback. menu.inc manages its own caching.
274       $blocks[$name]['cache'] = BLOCK_NO_CACHE;
275     }
276     return $blocks;
277   }
278   else if ($op == 'view') {
279     $data['subject'] = check_plain($menus[$delta]);
280     $data['content'] = menu_tree($delta);
281     return $data;
282   }
283 }
284 
285 /**
286  * Implementation of hook_nodeapi().
287  */
288 function menu_nodeapi(&$node, $op) {
289   switch ($op) {
290     case 'insert':
291     case 'update':
292       if (isset($node->menu)) {
293         $item = $node->menu;
294         if (!empty($item['delete'])) {
295           menu_link_delete($item['mlid']);
296         }
297         elseif (trim($item['link_title'])) {
298           $item['link_title'] = trim($item['link_title']);
299           $item['link_path'] = "node/$node->nid";
300           if (!$item['customized']) {
301             $item['options']['attributes']['title'] = trim($node->title);
302           }
303           if (!menu_link_save($item)) {
304             drupal_set_message(t('There was an error saving the menu link.'), 'error');
305           }
306         }
307       }
308       break;
309     case 'delete':
310       // Delete all menu module links that point to this node.
311       $result = db_query("SELECT mlid FROM {menu_links} WHERE link_path = 'node/%d' AND module = 'menu'", $node->nid);
312       while ($m = db_fetch_array($result)) {
313         menu_link_delete($m['mlid']);
314       }
315       break;
316     case 'prepare':
317       if (empty($node->menu)) {
318         // Prepare the node for the edit form so that $node->menu always exists.
319         $menu_name = variable_get('menu_default_node_menu', 'primary-links');
320         $item = array();
321         if (isset($node->nid)) {
322           // Give priority to the default menu
323           $mlid = db_result(db_query_range("SELECT mlid FROM {menu_links} WHERE link_path = 'node/%d' AND menu_name = '%s' AND module = 'menu' ORDER BY mlid ASC", $node->nid, $menu_name, 0, 1));
324           // Check all menus if a link does not exist in the default menu.
325           if (!$mlid) {
326             $mlid = db_result(db_query_range("SELECT mlid FROM {menu_links} WHERE link_path = 'node/%d' AND module = 'menu' ORDER BY mlid ASC", $node->nid, 0, 1));
327           }
328           if ($mlid) {
329             $item = menu_link_load($mlid);
330           }
331         }
332         // Set default values.
333         $node->menu = $item + array('link_title' => '', 'mlid' => 0, 'plid' => 0, 'menu_name' => $menu_name, 'weight' => 0, 'options' => array(), 'module' => 'menu', 'expanded' => 0, 'hidden' => 0, 'has_children' => 0, 'customized' => 0);
334       }
335       // Find the depth limit for the parent select.
336       if (!isset($node->menu['parent_depth_limit'])) {
337         $node->menu['parent_depth_limit'] = _menu_parent_depth_limit($node->menu);
338       }
339       break;
340   }
341 }
342 
343 /**
344  * Find the depth limit for items in the parent select.
345  */
346 function _menu_parent_depth_limit($item) {
347   return MENU_MAX_DEPTH - 1 - (($item['mlid'] && $item['has_children']) ? menu_link_children_relative_depth($item) : 0);
348 }
349 
350 /**
351  * Implementation of hook_form_alter(). Adds menu item fields to the node form.
352  */
353 function menu_form_alter(&$form, $form_state, $form_id) {
354   if (isset($form['#node']) && $form['#node']->type .'_node_form' == $form_id) {
355     // Note - doing this to make sure the delete checkbox stays in the form.
356     $form['#cache'] = TRUE;
357 
358     $form['menu'] = array(
359       '#type' => 'fieldset',
360       '#title' => t('Menu settings'),
361       '#access' => user_access('administer menu'),
362       '#collapsible' => TRUE,
363       '#collapsed' => FALSE,
364       '#tree' => TRUE,
365       '#weight' => -2,
366       '#attributes' => array('class' => 'menu-item-form'),
367     );
368     $item = $form['#node']->menu;
369 
370     if ($item['mlid']) {
371       // There is an existing link.
372       $form['menu']['delete'] = array(
373         '#type' => 'checkbox',
374         '#title' => t('Delete this menu item.'),
375       );
376     }
377     if (!$item['link_title']) {
378       $form['menu']['#collapsed'] = TRUE;
379     }
380 
381     foreach (array('mlid', 'module', 'hidden', 'has_children', 'customized', 'options', 'expanded', 'hidden', 'parent_depth_limit') as $key) {
382       $form['menu'][$key] = array('#type' => 'value', '#value' => $item[$key]);
383     }
384     $form['menu']['#item'] = $item;
385 
386     $form['menu']['link_title'] = array('#type' => 'textfield',
387       '#title' => t('Menu link title'),
388       '#default_value' => $item['link_title'],
389       '#description' => t('The link text corresponding to this item that should appear in the menu. Leave blank if you do not wish to add this post to the menu.'),
390       '#required' => FALSE,
391     );
392     // Generate a list of possible parents (not including this item or descendants).
393     $options = menu_parent_options(menu_get_menus(), $item);
394     $default = $item['menu_name'] .':'. $item['plid'];
395     if (!isset($options[$default])) {
396       $default = 'primary-links:0';
397     }
398     $form['menu']['parent'] = array(
399       '#type' => 'select',
400       '#title' => t('Parent item'),
401       '#default_value' => $default,
402       '#options' => $options,
403       '#description' => t('The maximum depth for an item and all its children is fixed at !maxdepth. Some menu items may not be available as parents if selecting them would exceed this limit.', array('!maxdepth' => MENU_MAX_DEPTH)),
404       '#attributes' => array('class' => 'menu-title-select'),
405     );
406     $form['#submit'][] = 'menu_node_form_submit';
407 
408     $form['menu']['weight'] = array(
409       '#type' => 'weight',
410       '#title' => t('Weight'),
411       '#delta' => 50,
412       '#default_value' => $item['weight'],
413       '#description' => t('Optional. In the menu, the heavier items will sink and the lighter items will be positioned nearer the top.'),
414     );
415   }
416 }
417 
418 /**
419  * Decompose the selected menu parent option into the menu_name and plid.
420  */
421 function menu_node_form_submit($form, &$form_state) {
422   list($form_state['values']['menu']['menu_name'], $form_state['values']['menu']['plid']) = explode(':', $form_state['values']['menu']['parent']);
423 }
424 
425 /**
426  * Return an associative array of the custom menus names.
427  *
428  * @param $all
429  *   If FALSE return only user-added menus, or if TRUE also include
430  *   the menus defined by the system.
431  * @return
432  *   An array with the machine-readable names as the keys, and human-readable
433  *   titles as the values.
434  */
435 function menu_get_menus($all = TRUE) {
436   $system_menus = menu_list_system_menus();
437   $sql = 'SELECT * FROM {menu_custom}';
438   if (!$all) {
439     $sql .= ' WHERE menu_name NOT IN ('. implode(',', array_fill(0, count($system_menus), "'%s'")) .')';
440   }
441   $sql .= ' ORDER BY title';
442   $result = db_query($sql, $system_menus);
443   $rows = array();
444   while ($r = db_fetch_array($result)) {
445     $rows[$r['menu_name']] = $r['title'];
446   }
447   return $rows;
448 }