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