Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / book / book.module
1 <?php
2
3 /**
4  * @file
5  * Allows users to create and organize related content in an outline.
6  */
7
8 use Drupal\book\BookManager;
9 use Drupal\Core\Entity\EntityInterface;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\Element;
12 use Drupal\Core\Routing\RouteMatchInterface;
13 use Drupal\Core\Url;
14 use Drupal\node\NodeInterface;
15 use Drupal\node\NodeTypeInterface;
16 use Drupal\node\Entity\Node;
17 use Drupal\Core\Language\LanguageInterface;
18 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
19 use Drupal\Core\Template\Attribute;
20
21 /**
22  * Implements hook_help().
23  */
24 function book_help($route_name, RouteMatchInterface $route_match) {
25   switch ($route_name) {
26     case 'help.page.book':
27       $output = '<h3>' . t('About') . '</h3>';
28       $output .= '<p>' . t('The Book module is used for creating structured, multi-page content, such as site resource guides, manuals, and wikis. It allows you to create content that has chapters, sections, subsections, or any similarly-tiered structure. Enabling the module creates a new content type <em>Book page</em>. For more information, see the <a href=":book">online documentation for the Book module</a>.', [':book' => 'https://www.drupal.org/documentation/modules/book']) . '</p>';
29       $output .= '<h3>' . t('Uses') . '</h3>';
30       $output .= '<dl>';
31       $output .= '<dt>' . t('Adding and managing book content') . '</dt>';
32       $output .= '<dd>' . t('Books have a hierarchical structure, called a <em>book outline</em>. Each book outline can have nested pages up to nine levels deep. Multiple content types can be configured to behave as a book outline. From the content edit form, it is possible to add a page to a book outline or create a new book.') . '</dd>';
33       $output .= '<dd>' . t('You can assign separate permissions for <em>creating new books</em> as well as <em>creating</em>, <em>editing</em> and <em>deleting</em> book content. Users with the <em>Administer book outlines</em> permission can add <em>any</em> type of content to a book by selecting the appropriate book outline while editing the content. They can also view a list of all books, and edit and rearrange section titles on the <a href=":admin-book">Book list page</a>.', [':admin-book' => \Drupal::url('book.admin')]) . '</dd>';
34       $output .= '<dt>' . t('Configuring content types for books') . '</dt>';
35       $output .= '<dd>' . t('The <em>Book page</em> content type is the initial content type enabled for book outlines. On the <a href=":admin-settings">Book settings page</a> you can configure content types that can used in book outlines.', [':admin-settings' => \Drupal::url('book.settings')]) . '</dd>';
36       $output .= '<dd>' . t('Users with the <em>Add content and child pages to books</em> permission will see a link to <em>Add child page</em> when viewing a content item that is part of a book outline. This link will allow users to create a new content item of the content type you select on the <a href=":admin-settings">Book settings page</a>. By default this is the <em>Book page</em> content type.', [':admin-settings' => \Drupal::url('book.settings')]) . '</dd>';
37       $output .= '<dt>' . t('Book navigation') . '</dt>';
38       $output .= '<dd>' . t("Book pages have a default book-specific navigation block. This navigation block contains links that lead to the previous and next pages in the book, and to the level above the current page in the book's structure. This block can be enabled on the <a href=':admin-block'>Blocks layout page</a>. For book pages to show up in the book navigation, they must be added to a book outline.", [':admin-block' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#']) . '</dd>';
39       $output .= '<dt>' . t('Collaboration') . '</dt>';
40       $output .= '<dd>' . t('Books can be created collaboratively, as they allow users with appropriate permissions to add pages into existing books, and add those pages to a custom table of contents.') . '</dd>';
41       $output .= '<dt>' . t('Printing books') . '</dt>';
42       $output .= '<dd>' . t("Users with the <em>View printer-friendly books</em> permission can select the <em>printer-friendly version</em> link visible at the bottom of a book page's content to generate a printer-friendly display of the page and all of its subsections.") . '</dd>';
43       $output .= '</dl>';
44       return $output;
45
46     case 'book.admin':
47       return '<p>' . t('The book module offers a means to organize a collection of related content pages, collectively known as a book. When viewed, this content automatically displays links to adjacent book pages, providing a simple navigation system for creating and reviewing structured content.') . '</p>';
48
49     case 'entity.node.book_outline_form':
50       return '<p>' . t('The outline feature allows you to include pages in the <a href=":book">Book hierarchy</a>, as well as move them within the hierarchy or to <a href=":book-admin">reorder an entire book</a>.', [':book' => \Drupal::url('book.render'), ':book-admin' => \Drupal::url('book.admin')]) . '</p>';
51   }
52 }
53
54 /**
55  * Implements hook_theme().
56  */
57 function book_theme() {
58   return [
59     'book_navigation' => [
60       'variables' => ['book_link' => NULL],
61     ],
62     'book_tree' => [
63       'variables' => ['items' => [], 'attributes' => []],
64     ],
65     'book_export_html' => [
66       'variables' => ['title' => NULL, 'contents' => NULL, 'depth' => NULL],
67     ],
68     'book_all_books_block' => [
69       'render element' => 'book_menus',
70     ],
71     'book_node_export_html' => [
72       'variables' => ['node' => NULL, 'content' => NULL, 'children' => NULL],
73     ],
74   ];
75 }
76
77 /**
78  * Implements hook_entity_type_build().
79  */
80 function book_entity_type_build(array &$entity_types) {
81   /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
82   $entity_types['node']
83     ->setFormClass('book_outline', 'Drupal\book\Form\BookOutlineForm')
84     ->setLinkTemplate('book-outline-form', '/node/{node}/outline')
85     ->setLinkTemplate('book-remove-form', '/node/{node}/outline/remove')
86     ->addConstraint('BookOutline', []);
87 }
88
89 /**
90  * Implements hook_node_links_alter().
91  */
92 function book_node_links_alter(array &$links, NodeInterface $node, array &$context) {
93   if ($context['view_mode'] != 'rss') {
94     $account = \Drupal::currentUser();
95
96     if (isset($node->book['depth'])) {
97       if ($context['view_mode'] == 'full' && node_is_page($node)) {
98         $child_type = \Drupal::config('book.settings')->get('child_type');
99         $access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node');
100         if (($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines')) && $access_control_handler->createAccess($child_type) && $node->isPublished() && $node->book['depth'] < BookManager::BOOK_MAX_DEPTH) {
101           $book_links['book_add_child'] = [
102             'title' => t('Add child page'),
103             'url' => Url::fromRoute('node.add', ['node_type' => $child_type], ['query' => ['parent' => $node->id()]]),
104           ];
105         }
106
107         if ($account->hasPermission('access printer-friendly version')) {
108           $book_links['book_printer'] = [
109             'title' => t('Printer-friendly version'),
110             'url' => Url::fromRoute('book.export', [
111               'type' => 'html',
112               'node' => $node->id(),
113             ]),
114             'attributes' => ['title' => t('Show a printer-friendly version of this book page and its sub-pages.')]
115           ];
116         }
117       }
118     }
119
120     if (!empty($book_links)) {
121       $links['book'] = [
122         '#theme' => 'links__node__book',
123         '#links' => $book_links,
124         '#attributes' => ['class' => ['links', 'inline']],
125       ];
126     }
127   }
128 }
129
130 /**
131  * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
132  *
133  * Adds the book form element to the node form.
134  *
135  * @see book_pick_book_nojs_submit()
136  */
137 function book_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
138   $node = $form_state->getFormObject()->getEntity();
139   $account = \Drupal::currentUser();
140   $access = $account->hasPermission('administer book outlines');
141   if (!$access) {
142     if ($account->hasPermission('add content to books') && ((!empty($node->book['bid']) && !$node->isNew()) || book_type_is_allowed($node->getType()))) {
143       // Already in the book hierarchy, or this node type is allowed.
144       $access = TRUE;
145     }
146   }
147
148   if ($access) {
149     $collapsed = !($node->isNew() && !empty($node->book['pid']));
150     $form = \Drupal::service('book.manager')->addFormElements($form, $form_state, $node, $account, $collapsed);
151     // The "js-hide" class hides submit button when Javascript is enabled.
152     $form['book']['pick-book'] = [
153       '#type' => 'submit',
154       '#value' => t('Change book (update list of parents)'),
155       '#submit' => ['book_pick_book_nojs_submit'],
156       '#weight' => 20,
157       '#attributes' => [
158         'class' => [
159           'js-hide',
160         ],
161       ],
162     ];
163     $form['#entity_builders'][] = 'book_node_builder';
164   }
165 }
166
167 /**
168  * Entity form builder to add the book information to the node.
169  *
170  * @todo: Remove this in favor of an entity field.
171  */
172 function book_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
173   $entity->book = $form_state->getValue('book');
174
175   // Always save a revision for non-administrators.
176   if (!empty($entity->book['bid']) && !\Drupal::currentUser()->hasPermission('administer nodes')) {
177     $entity->setNewRevision();
178   }
179 }
180
181 /**
182  * Form submission handler for node_form().
183  *
184  * This handler is run when JavaScript is disabled. It triggers the form to
185  * rebuild so that the "Parent item" options are changed to reflect the newly
186  * selected book. When JavaScript is enabled, the submit button that triggers
187  * this handler is hidden, and the "Book" dropdown directly triggers the
188  * book_form_update() Ajax callback instead.
189  *
190  * @see book_form_update()
191  * @see book_form_node_form_alter()
192  */
193 function book_pick_book_nojs_submit($form, FormStateInterface $form_state) {
194   $node = $form_state->getFormObject()->getEntity();
195   $node->book = $form_state->getValue('book');
196   $form_state->setRebuild();
197 }
198
199 /**
200  * Renders a new parent page select element when the book selection changes.
201  *
202  * This function is called via Ajax when the selected book is changed on a node
203  * or book outline form.
204  *
205  * @return
206  *   The rendered parent page select element.
207  */
208 function book_form_update($form, FormStateInterface $form_state) {
209   return $form['book']['pid'];
210 }
211
212 /**
213  * Implements hook_ENTITY_TYPE_load() for node entities.
214  */
215 function book_node_load($nodes) {
216   /** @var \Drupal\book\BookManagerInterface $book_manager */
217   $book_manager = \Drupal::service('book.manager');
218   $links = $book_manager->loadBookLinks(array_keys($nodes), FALSE);
219   foreach ($links as $record) {
220     $nodes[$record['nid']]->book = $record;
221     $nodes[$record['nid']]->book['link_path'] = 'node/' . $record['nid'];
222     $nodes[$record['nid']]->book['link_title'] = $nodes[$record['nid']]->label();
223   }
224 }
225
226 /**
227  * Implements hook_ENTITY_TYPE_view() for node entities.
228  */
229 function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
230   if ($view_mode == 'full') {
231     if (!empty($node->book['bid']) && empty($node->in_preview)) {
232       $book_node = Node::load($node->book['bid']);
233       if (!$book_node->access()) {
234         return;
235       }
236       $build['book_navigation'] = [
237         '#theme' => 'book_navigation',
238         '#book_link' => $node->book,
239         '#weight' => 100,
240         // The book navigation is a listing of Node entities, so associate its
241         // list cache tag for correct invalidation.
242         '#cache' => [
243           'tags' => $node->getEntityType()->getListCacheTags(),
244         ],
245       ];
246     }
247   }
248 }
249
250 /**
251  * Implements hook_ENTITY_TYPE_presave() for node entities.
252  */
253 function book_node_presave(EntityInterface $node) {
254   // Make sure a new node gets a new menu link.
255   if ($node->isNew()) {
256     $node->book['nid'] = NULL;
257   }
258 }
259
260 /**
261  * Implements hook_ENTITY_TYPE_insert() for node entities.
262  */
263 function book_node_insert(EntityInterface $node) {
264   /** @var \Drupal\book\BookManagerInterface $book_manager */
265   $book_manager = \Drupal::service('book.manager');
266   $book_manager->updateOutline($node);
267 }
268
269 /**
270  * Implements hook_ENTITY_TYPE_update() for node entities.
271  */
272 function book_node_update(EntityInterface $node) {
273   /** @var \Drupal\book\BookManagerInterface $book_manager */
274   $book_manager = \Drupal::service('book.manager');
275   $book_manager->updateOutline($node);
276 }
277
278 /**
279  * Implements hook_ENTITY_TYPE_predelete() for node entities.
280  */
281 function book_node_predelete(EntityInterface $node) {
282   if (!empty($node->book['bid'])) {
283     /** @var \Drupal\book\BookManagerInterface $book_manager */
284     $book_manager = \Drupal::service('book.manager');
285     $book_manager->deleteFromBook($node->book['nid']);
286   }
287 }
288
289 /**
290  * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
291  */
292 function book_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
293   /** @var \Drupal\book\BookManagerInterface $book_manager */
294   $book_manager = \Drupal::service('book.manager');
295
296   // Prepare defaults for the add/edit form.
297   $account = \Drupal::currentUser();
298   if (empty($node->book) && ($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines'))) {
299     $node->book = [];
300
301     $query = \Drupal::request()->query;
302     if ($node->isNew() && !is_null($query->get('parent')) && is_numeric($query->get('parent'))) {
303       // Handle "Add child page" links:
304       $parent = $book_manager->loadBookLink($query->get('parent'), TRUE);
305
306       if ($parent && $parent['access']) {
307         $node->book['bid'] = $parent['bid'];
308         $node->book['pid'] = $parent['nid'];
309       }
310     }
311     // Set defaults.
312     $node_ref = !$node->isNew() ? $node->id() : 'new';
313     $node->book += $book_manager->getLinkDefaults($node_ref);
314   }
315   else {
316     if (isset($node->book['bid']) && !isset($node->book['original_bid'])) {
317       $node->book['original_bid'] = $node->book['bid'];
318     }
319   }
320   // Find the depth limit for the parent select.
321   if (isset($node->book['bid']) && !isset($node->book['parent_depth_limit'])) {
322     $node->book['parent_depth_limit'] = $book_manager->getParentDepthLimit($node->book);
323   }
324 }
325
326 /**
327  * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\Form\NodeDeleteForm.
328  *
329  * Alters the confirm form for a single node deletion.
330  */
331 function book_form_node_confirm_form_alter(&$form, FormStateInterface $form_state) {
332   // Only need to alter the delete operation form.
333   if ($form_state->getFormObject()->getOperation() !== 'delete') {
334     return;
335   }
336
337   /** @var \Drupal\node\NodeInterface $node */
338   $node = $form_state->getFormObject()->getEntity();
339   if (!book_type_is_allowed($node->getType())) {
340     // Not a book node.
341     return;
342   }
343
344   if (isset($node->book) && $node->book['has_children']) {
345     $form['book_warning'] = [
346       '#markup' => '<p>' . t('%title is part of a book outline, and has associated child pages. If you proceed with deletion, the child pages will be relocated automatically.', ['%title' => $node->label()]) . '</p>',
347       '#weight' => -10,
348     ];
349   }
350 }
351
352 /**
353  * Prepares variables for book listing block templates.
354  *
355  * Default template: book-all-books-block.html.twig.
356  *
357  * All non-renderable elements are removed so that the template has full access
358  * to the structured data but can also simply iterate over all elements and
359  * render them (as in the default template).
360  *
361  * @param array $variables
362  *   An associative array containing the following key:
363  *   - book_menus: An associative array containing renderable menu links for all
364  *     book menus.
365  */
366 function template_preprocess_book_all_books_block(&$variables) {
367   // Remove all non-renderable elements.
368   $elements = $variables['book_menus'];
369   $variables['book_menus'] = [];
370   foreach (Element::children($elements) as $index) {
371     $variables['book_menus'][] = [
372       'id' => $index,
373       'menu' => $elements[$index],
374       'title' => $elements[$index]['#book_title'],
375     ];
376   }
377 }
378
379 /**
380  * Prepares variables for book navigation templates.
381  *
382  * Default template: book-navigation.html.twig.
383  *
384  * @param array $variables
385  *   An associative array containing the following key:
386  *   - book_link: An associative array of book link properties.
387  *     Properties used: bid, link_title, depth, pid, nid.
388  */
389 function template_preprocess_book_navigation(&$variables) {
390   $book_link = $variables['book_link'];
391
392   // Provide extra variables for themers. Not needed by default.
393   $variables['book_id'] = $book_link['bid'];
394   $variables['book_title'] = $book_link['link_title'];
395   $variables['book_url'] = \Drupal::url('entity.node.canonical', ['node' => $book_link['bid']]);
396   $variables['current_depth'] = $book_link['depth'];
397   $variables['tree'] = '';
398
399   /** @var \Drupal\book\BookOutline $book_outline */
400   $book_outline = \Drupal::service('book.outline');
401
402   if ($book_link['nid']) {
403     $variables['tree'] = $book_outline->childrenLinks($book_link);
404
405     $build = [];
406
407     if ($prev = $book_outline->prevLink($book_link)) {
408       $prev_href = \Drupal::url('entity.node.canonical', ['node' => $prev['nid']]);
409       $build['#attached']['html_head_link'][][] = [
410         'rel' => 'prev',
411         'href' => $prev_href,
412       ];
413       $variables['prev_url'] = $prev_href;
414       $variables['prev_title'] = $prev['title'];
415     }
416
417     /** @var \Drupal\book\BookManagerInterface $book_manager */
418     $book_manager = \Drupal::service('book.manager');
419     if ($book_link['pid'] && $parent = $book_manager->loadBookLink($book_link['pid'])) {
420       $parent_href = \Drupal::url('entity.node.canonical', ['node' => $book_link['pid']]);
421       $build['#attached']['html_head_link'][][] = [
422         'rel' => 'up',
423         'href' => $parent_href,
424       ];
425       $variables['parent_url'] = $parent_href;
426       $variables['parent_title'] = $parent['title'];
427     }
428
429     if ($next = $book_outline->nextLink($book_link)) {
430       $next_href = \Drupal::url('entity.node.canonical', ['node' => $next['nid']]);
431       $build['#attached']['html_head_link'][][] = [
432         'rel' => 'next',
433         'href' => $next_href,
434       ];
435       $variables['next_url'] = $next_href;
436       $variables['next_title'] = $next['title'];
437     }
438   }
439
440   if (!empty($build)) {
441     \Drupal::service('renderer')->render($build);
442   }
443
444   $variables['has_links'] = FALSE;
445   // Link variables to filter for values and set state of the flag variable.
446   $links = ['prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title'];
447   foreach ($links as $link) {
448     if (isset($variables[$link])) {
449       // Flag when there is a value.
450       $variables['has_links'] = TRUE;
451     }
452     else {
453       // Set empty to prevent notices.
454       $variables[$link] = '';
455     }
456   }
457 }
458
459 /**
460  * Prepares variables for book export templates.
461  *
462  * Default template: book-export-html.html.twig.
463  *
464  * @param array $variables
465  *   An associative array containing:
466  *   - title: The title of the book.
467  *   - contents: Output of each book page.
468  *   - depth: The max depth of the book.
469  */
470 function template_preprocess_book_export_html(&$variables) {
471   global $base_url;
472   $language_interface = \Drupal::languageManager()->getCurrentLanguage();
473
474   $variables['base_url'] = $base_url;
475   $variables['language'] = $language_interface;
476   $variables['language_rtl'] = ($language_interface->getDirection() == LanguageInterface::DIRECTION_RTL);
477
478   // HTML element attributes.
479   $attributes = [];
480   $attributes['lang'] = $language_interface->getId();
481   $attributes['dir'] = $language_interface->getDirection();
482   $variables['html_attributes'] = new Attribute($attributes);
483 }
484
485 /**
486  * Prepares variables for single node export templates.
487  *
488  * Default template: book-node-export-html.html.twig.
489  *
490  * @param array $variables
491  *   An associative array containing the following keys:
492  *   - node: The node that will be output.
493  *   - children: All the rendered child nodes within the current node. Defaults
494  *     to an empty string.
495  */
496 function template_preprocess_book_node_export_html(&$variables) {
497   $variables['depth'] = $variables['node']->book['depth'];
498   $variables['title'] = $variables['node']->label();
499 }
500
501 /**
502  * Determines if a given node type is in the list of types allowed for books.
503  *
504  * @param string $type
505  *   A node type.
506  *
507  * @return bool
508  *   A Boolean TRUE if the node type can be included in books; otherwise, FALSE.
509  */
510 function book_type_is_allowed($type) {
511   return in_array($type, \Drupal::config('book.settings')->get('allowed_types'));
512 }
513
514 /**
515  * Implements hook_ENTITY_TYPE_update() for node_type entities.
516  *
517  * Updates book.settings configuration object if the machine-readable name of a
518  * node type is changed.
519  */
520 function book_node_type_update(NodeTypeInterface $type) {
521   if ($type->getOriginalId() != $type->id()) {
522     $config = \Drupal::configFactory()->getEditable('book.settings');
523     // Update the list of node types that are allowed to be added to books.
524     $allowed_types = $config->get('allowed_types');
525     $old_key = array_search($type->getOriginalId(), $allowed_types);
526
527     if ($old_key !== FALSE) {
528       $allowed_types[$old_key] = $type->id();
529       // Ensure that the allowed_types array is sorted consistently.
530       // @see BookSettingsForm::submitForm()
531       sort($allowed_types);
532       $config->set('allowed_types', $allowed_types);
533     }
534
535     // Update the setting for the "Add child page" link.
536     if ($config->get('child_type') == $type->getOriginalId()) {
537       $config->set('child_type', $type->id());
538     }
539     $config->save();
540   }
541 }