cb1e85307f5cda7d31388c211d5407fca85c3428
[yaffs-website] / web / core / modules / menu_ui / menu_ui.module
1 <?php
2
3 /**
4  * @file
5  * Allows administrators to customize the site's navigation menus.
6  *
7  * A menu (in this context) is a hierarchical collection of links, generally
8  * used for navigation.
9  */
10
11 use Drupal\Core\Breadcrumb\Breadcrumb;
12 use Drupal\Core\Cache\CacheableMetadata;
13 use Drupal\Core\Block\BlockPluginInterface;
14 use Drupal\Core\Link;
15 use Drupal\Core\Menu\MenuLinkInterface;
16 use Drupal\Core\Form\FormStateInterface;
17 use Drupal\Core\Routing\RouteMatchInterface;
18 use Drupal\menu_link_content\Entity\MenuLinkContent;
19 use Drupal\node\NodeTypeInterface;
20 use Drupal\system\Entity\Menu;
21 use Drupal\node\NodeInterface;
22
23 /**
24  * Maximum length of menu name as entered by the user.
25  *
26  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. Use
27  *   \Drupal\Core\Config\Entity\ConfigEntityStorage::MAX_ID_LENGTH because the
28  *   menu name is a configuration entity ID.
29  *
30  * @see https://www.drupal.org/node/2831620
31  */
32 const MENU_MAX_MENU_NAME_LENGTH_UI = 27;
33
34 /**
35  * Implements hook_help().
36  */
37 function menu_ui_help($route_name, RouteMatchInterface $route_match) {
38   switch ($route_name) {
39     case 'help.page.menu_ui':
40       $output = '';
41       $output .= '<h3>' . t('About') . '</h3>';
42       $output .= '<p>' . t('The Menu UI module provides an interface for managing menus. A menu is a hierarchical collection of links, which can be within or external to the site, generally used for navigation. For more information, see the <a href=":menu">online documentation for the Menu UI module</a>.', [':menu' => 'https://www.drupal.org/documentation/modules/menu/']) . '</p>';
43       $output .= '<h3>' . t('Uses') . '</h3>';
44       $output .= '<dl>';
45       $output .= '<dt>' . t('Managing menus') . '</dt>';
46       $output .= '<dd>' . t('Users with the <em>Administer menus and menu items</em> permission can add, edit, and delete custom menus on the <a href=":menu">Menus page</a>. Custom menus can be special site menus, menus of external links, or any combination of internal and external links. You may create an unlimited number of additional menus, each of which will automatically have an associated block (if you have the <a href=":block_help">Block module</a> installed). By selecting <em>Edit menu</em>, you can add, edit, or delete links for a given menu. The links listing page provides a drag-and-drop interface for controlling the order of links, and creating a hierarchy within the menu.', [':block_help' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('help.page', ['name' => 'block']) : '#', ':menu' => \Drupal::url('entity.menu.collection')]) . '</dd>';
47       $output .= '<dt>' . t('Displaying menus') . '</dt>';
48       $output .= '<dd>' . t('If you have the Block module enabled, then each menu that you create is rendered in a block that you enable and position on the <a href=":blocks">Block layout page</a>. In some <a href=":themes">themes</a>, the main menu and possibly the secondary menu will be output automatically; you may be able to disable this behavior on the <a href=":themes">theme\'s settings page</a>.', [':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#', ':themes' => \Drupal::url('system.themes_page'), ':theme_settings' => \Drupal::url('system.theme_settings')]) . '</dd>';
49       $output .= '</dl>';
50       return $output;
51   }
52   if ($route_name == 'entity.menu.add_form' && \Drupal::moduleHandler()->moduleExists('block') && \Drupal::currentUser()->hasPermission('administer blocks')) {
53     return '<p>' . t('You can enable the newly-created block for this menu on the <a href=":blocks">Block layout page</a>.', [':blocks' => \Drupal::url('block.admin_display')]) . '</p>';
54   }
55   elseif ($route_name == 'entity.menu.collection' && \Drupal::moduleHandler()->moduleExists('block') && \Drupal::currentUser()->hasPermission('administer blocks')) {
56     return '<p>' . t('Each menu has a corresponding block that is managed on the <a href=":blocks">Block layout page</a>.', [':blocks' => \Drupal::url('block.admin_display')]) . '</p>';
57   }
58 }
59
60 /**
61  * Implements hook_entity_type_build().
62  */
63 function menu_ui_entity_type_build(array &$entity_types) {
64   /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
65   $entity_types['menu']
66     ->setFormClass('add', 'Drupal\menu_ui\MenuForm')
67     ->setFormClass('edit', 'Drupal\menu_ui\MenuForm')
68     ->setFormClass('delete', 'Drupal\menu_ui\Form\MenuDeleteForm')
69     ->setListBuilderClass('Drupal\menu_ui\MenuListBuilder')
70     ->setLinkTemplate('add-form', '/admin/structure/menu/add')
71     ->setLinkTemplate('delete-form', '/admin/structure/menu/manage/{menu}/delete')
72     ->setLinkTemplate('edit-form', '/admin/structure/menu/manage/{menu}')
73     ->setLinkTemplate('add-link-form', '/admin/structure/menu/manage/{menu}/add')
74     ->setLinkTemplate('collection', '/admin/structure/menu');
75
76   if (isset($entity_types['node'])) {
77     $entity_types['node']->addConstraint('MenuSettings', []);
78   }
79 }
80
81 /**
82  * Implements hook_ENTITY_TYPE_insert( for menu entities.
83  */
84 function menu_ui_menu_insert(Menu $menu) {
85   menu_cache_clear_all();
86   // Invalidate the block cache to update menu-based derivatives.
87   if (\Drupal::moduleHandler()->moduleExists('block')) {
88     \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
89   }
90 }
91
92 /**
93  * Implements hook_ENTITY_TYPE_update() for menu entities.
94  */
95 function menu_ui_menu_update(Menu $menu) {
96   menu_cache_clear_all();
97   // Invalidate the block cache to update menu-based derivatives.
98   if (\Drupal::moduleHandler()->moduleExists('block')) {
99     \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
100   }
101 }
102
103 /**
104  * Implements hook_ENTITY_TYPE_predelete() for menu entities.
105  */
106 function menu_ui_menu_predelete(Menu $menu) {
107   // Delete all links from the menu.
108   /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
109   $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
110   $menu_link_manager->deleteLinksInMenu($menu->id());
111 }
112
113 /**
114  * Implements hook_ENTITY_TYPE_delete() for menu entities.
115  */
116 function menu_ui_menu_delete(Menu $menu) {
117   menu_cache_clear_all();
118
119   // Invalidate the block cache to update menu-based derivatives.
120   if (\Drupal::moduleHandler()->moduleExists('block')) {
121     \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
122   }
123 }
124
125 /**
126  * Implements hook_block_view_BASE_BLOCK_ID_alter() for 'system_menu_block'.
127  */
128 function menu_ui_block_view_system_menu_block_alter(array &$build, BlockPluginInterface $block) {
129   if ($block->getBaseId() == 'system_menu_block') {
130     $menu_name = $block->getDerivativeId();
131     $build['#contextual_links']['menu'] = [
132       'route_parameters' => ['menu' => $menu_name],
133     ];
134   }
135 }
136
137 /**
138  * Helper function to create or update a menu link for a node.
139  *
140  * @param \Drupal\node\NodeInterface $node
141  *   Node entity.
142  * @param array $values
143  *   Values for the menu link.
144  */
145 function _menu_ui_node_save(NodeInterface $node, array $values) {
146   /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
147   if (!empty($values['entity_id'])) {
148     $entity = MenuLinkContent::load($values['entity_id']);
149     if ($entity->isTranslatable()) {
150       if (!$entity->hasTranslation($node->language()->getId())) {
151         $entity = $entity->addTranslation($node->language()->getId(), $entity->toArray());
152       }
153       else {
154         $entity = $entity->getTranslation($node->language()->getId());
155       }
156     }
157   }
158   else {
159     // Create a new menu_link_content entity.
160     $entity = MenuLinkContent::create([
161       'link' => ['uri' => 'entity:node/' . $node->id()],
162       'langcode' => $node->language()->getId(),
163     ]);
164     $entity->enabled->value = 1;
165   }
166   $entity->title->value = trim($values['title']);
167   $entity->description->value = trim($values['description']);
168   $entity->menu_name->value = $values['menu_name'];
169   $entity->parent->value = $values['parent'];
170   $entity->weight->value = isset($values['weight']) ? $values['weight'] : 0;
171   $entity->save();
172 }
173
174 /**
175  * Returns the definition for a menu link for the given node.
176  *
177  * @param \Drupal\node\NodeInterface $node
178  *   The node entity.
179  *
180  * @return array
181  *   An array that contains default values for the menu link form.
182  */
183 function menu_ui_get_menu_link_defaults(NodeInterface $node) {
184   // Prepare the definition for the edit form.
185   /** @var \Drupal\node\NodeTypeInterface $node_type */
186   $node_type = $node->type->entity;
187   $menu_name = strtok($node_type->getThirdPartySetting('menu_ui', 'parent', 'main:'), ':');
188   $defaults = FALSE;
189   if ($node->id()) {
190     $id = FALSE;
191     // Give priority to the default menu
192     $type_menus = $node_type->getThirdPartySetting('menu_ui', 'available_menus', ['main']);
193     if (in_array($menu_name, $type_menus)) {
194       $query = \Drupal::entityQuery('menu_link_content')
195         ->condition('link.uri', 'node/' . $node->id())
196         ->condition('menu_name', $menu_name)
197         ->sort('id', 'ASC')
198         ->range(0, 1);
199       $result = $query->execute();
200
201       $id = (!empty($result)) ? reset($result) : FALSE;
202     }
203     // Check all allowed menus if a link does not exist in the default menu.
204     if (!$id && !empty($type_menus)) {
205       $query = \Drupal::entityQuery('menu_link_content')
206         ->condition('link.uri', 'entity:node/' . $node->id())
207         ->condition('menu_name', array_values($type_menus), 'IN')
208         ->sort('id', 'ASC')
209         ->range(0, 1);
210       $result = $query->execute();
211
212       $id = (!empty($result)) ? reset($result) : FALSE;
213     }
214     if ($id) {
215       $menu_link = MenuLinkContent::load($id);
216       $menu_link = \Drupal::service('entity.repository')->getTranslationFromContext($menu_link);
217       $defaults = [
218         'entity_id' => $menu_link->id(),
219         'id' => $menu_link->getPluginId(),
220         'title' => $menu_link->getTitle(),
221         'title_max_length' => $menu_link->getFieldDefinitions()['title']->getSetting('max_length'),
222         'description' => $menu_link->getDescription(),
223         'menu_name' => $menu_link->getMenuName(),
224         'parent' => $menu_link->getParentId(),
225         'weight' => $menu_link->getWeight(),
226       ];
227     }
228   }
229
230   if (!$defaults) {
231     // Get the default max_length of a menu link title from the base field
232     // definition.
233     $field_definitions = \Drupal::entityManager()->getBaseFieldDefinitions('menu_link_content');
234     $max_length = $field_definitions['title']->getSetting('max_length');
235     $defaults = [
236       'entity_id' => 0,
237       'id' => '',
238       'title' => '',
239       'title_max_length' => $max_length,
240       'description' => '',
241       'menu_name' => $menu_name,
242       'parent' => '',
243       'weight' => 0,
244     ];
245   }
246   return $defaults;
247 }
248
249 /**
250  * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
251  *
252  * Adds menu item fields to the node form.
253  *
254  * @see menu_ui_form_node_form_submit()
255  */
256 function menu_ui_form_node_form_alter(&$form, FormStateInterface $form_state) {
257   // Generate a list of possible parents (not including this link or descendants).
258   // @todo This must be handled in a #process handler.
259   $node = $form_state->getFormObject()->getEntity();
260   $defaults = menu_ui_get_menu_link_defaults($node);
261   /** @var \Drupal\node\NodeTypeInterface $node_type */
262   $node_type = $node->type->entity;
263   /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
264   $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
265   $menu_names = menu_ui_get_menus();
266   $type_menus = $node_type->getThirdPartySetting('menu_ui', 'available_menus', ['main']);
267   $available_menus = [];
268   foreach ($type_menus as $menu) {
269     $available_menus[$menu] = $menu_names[$menu];
270   }
271   if ($defaults['id']) {
272     $default = $defaults['menu_name'] . ':' . $defaults['parent'];
273   }
274   else {
275     $default = $node_type->getThirdPartySetting('menu_ui', 'parent', 'main:');
276   }
277   $parent_element = $menu_parent_selector->parentSelectElement($default, $defaults['id'], $available_menus);
278   // If no possible parent menu items were found, there is nothing to display.
279   if (empty($parent_element)) {
280     return;
281   }
282
283   $form['menu'] = [
284     '#type' => 'details',
285     '#title' => t('Menu settings'),
286     '#access' => \Drupal::currentUser()->hasPermission('administer menu'),
287     '#open' => (bool) $defaults['id'],
288     '#group' => 'advanced',
289     '#attached' => [
290       'library' => ['menu_ui/drupal.menu_ui'],
291     ],
292     '#tree' => TRUE,
293     '#weight' => -2,
294     '#attributes' => ['class' => ['menu-link-form']],
295   ];
296   $form['menu']['enabled'] = [
297     '#type' => 'checkbox',
298     '#title' => t('Provide a menu link'),
299     '#default_value' => (int) (bool) $defaults['id'],
300   ];
301   $form['menu']['link'] = [
302     '#type' => 'container',
303     '#parents' => ['menu'],
304     '#states' => [
305       'invisible' => [
306         'input[name="menu[enabled]"]' => ['checked' => FALSE],
307       ],
308     ],
309   ];
310
311   // Populate the element with the link data.
312   foreach (['id', 'entity_id'] as $key) {
313     $form['menu']['link'][$key] = ['#type' => 'value', '#value' => $defaults[$key]];
314   }
315
316   $form['menu']['link']['title'] = [
317     '#type' => 'textfield',
318     '#title' => t('Menu link title'),
319     '#default_value' => $defaults['title'],
320     '#maxlength' => $defaults['title_max_length'],
321   ];
322
323   $form['menu']['link']['description'] = [
324     '#type' => 'textarea',
325     '#title' => t('Description'),
326     '#default_value' => $defaults['description'],
327     '#rows' => 1,
328     '#description' => t('Shown when hovering over the menu link.'),
329   ];
330
331   $form['menu']['link']['menu_parent'] = $parent_element;
332   $form['menu']['link']['menu_parent']['#title'] = t('Parent item');
333   $form['menu']['link']['menu_parent']['#attributes']['class'][] = 'menu-parent-select';
334
335   $form['menu']['link']['weight'] = [
336     '#type' => 'number',
337     '#title' => t('Weight'),
338     '#default_value' => $defaults['weight'],
339     '#description' => t('Menu links with lower weights are displayed before links with higher weights.'),
340   ];
341
342   foreach (array_keys($form['actions']) as $action) {
343     if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
344       $form['actions'][$action]['#submit'][] = 'menu_ui_form_node_form_submit';
345     }
346   }
347
348   $form['#entity_builders'][] = 'menu_ui_node_builder';
349 }
350
351 /**
352  * Entity form builder to add the menu information to the node.
353  */
354 function menu_ui_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
355   $entity->menu = $form_state->getValue('menu');
356 }
357
358 /**
359  * Form submission handler for menu item field on the node form.
360  *
361  * @see menu_ui_form_node_form_alter()
362  */
363 function menu_ui_form_node_form_submit($form, FormStateInterface $form_state) {
364   $node = $form_state->getFormObject()->getEntity();
365   if (!$form_state->isValueEmpty('menu')) {
366     $values = $form_state->getValue('menu');
367     if (empty($values['enabled'])) {
368       if ($values['entity_id']) {
369         $entity = MenuLinkContent::load($values['entity_id']);
370         $entity->delete();
371       }
372     }
373     elseif (trim($values['title'])) {
374       // Decompose the selected menu parent option into 'menu_name' and 'parent',
375       // if the form used the default parent selection widget.
376       if (!empty($values['menu_parent'])) {
377         list($menu_name, $parent) = explode(':', $values['menu_parent'], 2);
378         $values['menu_name'] = $menu_name;
379         $values['parent'] = $parent;
380       }
381       _menu_ui_node_save($node, $values);
382     }
383   }
384 }
385
386 /**
387  * Implements hook_form_FORM_ID_alter() for \Drupal\node\NodeTypeForm.
388  *
389  * Adds menu options to the node type form.
390  *
391  * @see NodeTypeForm::form()
392  * @see menu_ui_form_node_type_form_submit()
393  */
394 function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
395   /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
396   $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
397   $menu_options = menu_ui_get_menus();
398   /** @var \Drupal\node\NodeTypeInterface $type */
399   $type = $form_state->getFormObject()->getEntity();
400   $form['menu'] = [
401     '#type' => 'details',
402     '#title' => t('Menu settings'),
403     '#attached' => [
404       'library' => ['menu_ui/drupal.menu_ui.admin'],
405     ],
406     '#group' => 'additional_settings',
407   ];
408   $form['menu']['menu_options'] = [
409     '#type' => 'checkboxes',
410     '#title' => t('Available menus'),
411     '#default_value' => $type->getThirdPartySetting('menu_ui', 'available_menus', ['main']),
412     '#options' => $menu_options,
413     '#description' => t('The menus available to place links in for this content type.'),
414   ];
415   // @todo See if we can avoid pre-loading all options by changing the form or
416   //   using a #process callback. https://www.drupal.org/node/2310319
417   //   To avoid an 'illegal option' error after saving the form we have to load
418   //   all available menu parents. Otherwise, it is not possible to dynamically
419   //   add options to the list using ajax.
420   $options_cacheability = new CacheableMetadata();
421   $options = $menu_parent_selector->getParentSelectOptions('', NULL, $options_cacheability);
422   $form['menu']['menu_parent'] = [
423     '#type' => 'select',
424     '#title' => t('Default parent item'),
425     '#default_value' => $type->getThirdPartySetting('menu_ui', 'parent', 'main:'),
426     '#options' => $options,
427     '#description' => t('Choose the menu item to be the default parent for a new link in the content authoring form.'),
428     '#attributes' => ['class' => ['menu-title-select']],
429   ];
430   $options_cacheability->applyTo($form['menu']['menu_parent']);
431
432   $form['#validate'][] = 'menu_ui_form_node_type_form_validate';
433   $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder';
434 }
435
436 /**
437  * Validate handler for forms with menu options.
438  *
439  * @see menu_ui_form_node_type_form_alter()
440  */
441 function menu_ui_form_node_type_form_validate(&$form, FormStateInterface $form_state) {
442   $available_menus = array_filter($form_state->getValue('menu_options'));
443   // If there is at least one menu allowed, the selected item should be in
444   // one of them.
445   if (count($available_menus)) {
446     $menu_item_id_parts = explode(':', $form_state->getValue('menu_parent'));
447     if (!in_array($menu_item_id_parts[0], $available_menus)) {
448       $form_state->setErrorByName('menu_parent', t('The selected menu item is not under one of the selected menus.'));
449     }
450   }
451   else {
452     $form_state->setValue('menu_parent', '');
453   }
454 }
455
456 /**
457  * Entity builder for the node type form with menu options.
458  *
459  * @see menu_ui_form_node_type_form_alter()
460  */
461 function menu_ui_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
462   $type->setThirdPartySetting('menu_ui', 'available_menus', array_values(array_filter($form_state->getValue('menu_options'))));
463   $type->setThirdPartySetting('menu_ui', 'parent', $form_state->getValue('menu_parent'));
464 }
465
466 /**
467  * Return an associative array of the custom menus names.
468  *
469  * @param bool $all
470  *   (optional) If FALSE return only user-added menus, or if TRUE also include
471  *   the menus defined by the system. Defaults to TRUE.
472  *
473  * @return array
474  *   An array with the machine-readable names as the keys, and human-readable
475  *   titles as the values.
476  */
477 function menu_ui_get_menus($all = TRUE) {
478   if ($custom_menus = Menu::loadMultiple()) {
479     if (!$all) {
480       $custom_menus = array_diff_key($custom_menus, menu_list_system_menus());
481     }
482     foreach ($custom_menus as $menu_name => $menu) {
483       $custom_menus[$menu_name] = $menu->label();
484     }
485     asort($custom_menus);
486   }
487   return $custom_menus;
488 }
489
490 /**
491  * Implements hook_preprocess_HOOK() for block templates.
492  */
493 function menu_ui_preprocess_block(&$variables) {
494   if ($variables['configuration']['provider'] == 'menu_ui') {
495     $variables['attributes']['role'] = 'navigation';
496   }
497 }
498
499
500 /**
501  * Implements hook_system_breadcrumb_alter().
502  */
503 function menu_ui_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
504   // Custom breadcrumb behavior for editing menu links, we append a link to
505   // the menu in which the link is found.
506   if (($route_match->getRouteName() == 'menu_ui.link_edit') && $menu_link = $route_match->getParameter('menu_link_plugin')) {
507     if (($menu_link instanceof MenuLinkInterface)) {
508       // Add a link to the menu admin screen.
509       $menu = Menu::load($menu_link->getMenuName());
510       $breadcrumb->addLink(Link::createFromRoute($menu->label(), 'entity.menu.edit_form', ['menu' => $menu->id()]));
511     }
512   }
513 }