Backup of db before drupal security update
[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 }
87
88 /**
89  * Implements hook_node_links_alter().
90  */
91 function book_node_links_alter(array &$links, NodeInterface $node, array &$context) {
92   if ($context['view_mode'] != 'rss') {
93     $account = \Drupal::currentUser();
94
95     if (isset($node->book['depth'])) {
96       if ($context['view_mode'] == 'full' && node_is_page($node)) {
97         $child_type = \Drupal::config('book.settings')->get('child_type');
98         $access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node');
99         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) {
100           $book_links['book_add_child'] = [
101             'title' => t('Add child page'),
102             'url' => Url::fromRoute('node.add', ['node_type' => $child_type], ['query' => ['parent' => $node->id()]]),
103           ];
104         }
105
106         if ($account->hasPermission('access printer-friendly version')) {
107           $book_links['book_printer'] = [
108             'title' => t('Printer-friendly version'),
109             'url' => Url::fromRoute('book.export', [
110               'type' => 'html',
111               'node' => $node->id(),
112             ]),
113             'attributes' => ['title' => t('Show a printer-friendly version of this book page and its sub-pages.')]
114           ];
115         }
116       }
117     }
118
119     if (!empty($book_links)) {
120       $links['book'] = [
121         '#theme' => 'links__node__book',
122         '#links' => $book_links,
123         '#attributes' => ['class' => ['links', 'inline']],
124       ];
125     }
126   }
127 }
128
129 /**
130  * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
131  *
132  * Adds the book form element to the node form.
133  *
134  * @see book_pick_book_nojs_submit()
135  */
136 function book_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
137   $node = $form_state->getFormObject()->getEntity();
138   $account = \Drupal::currentUser();
139   $access = $account->hasPermission('administer book outlines');
140   if (!$access) {
141     if ($account->hasPermission('add content to books') && ((!empty($node->book['bid']) && !$node->isNew()) || book_type_is_allowed($node->getType()))) {
142       // Already in the book hierarchy, or this node type is allowed.
143       $access = TRUE;
144     }
145   }
146
147   if ($access) {
148     $collapsed = !($node->isNew() && !empty($node->book['pid']));
149     $form = \Drupal::service('book.manager')->addFormElements($form, $form_state, $node, $account, $collapsed);
150     // The "js-hide" class hides submit button when Javascript is enabled.
151     $form['book']['pick-book'] = [
152       '#type' => 'submit',
153       '#value' => t('Change book (update list of parents)'),
154       '#submit' => ['book_pick_book_nojs_submit'],
155       '#weight' => 20,
156       '#attributes' => [
157         'class' => [
158           'js-hide',
159         ],
160       ],
161     ];
162     $form['#entity_builders'][] = 'book_node_builder';
163   }
164 }
165
166 /**
167  * Entity form builder to add the book information to the node.
168  *
169  * @todo: Remove this in favor of an entity field.
170  */
171 function book_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
172   $entity->book = $form_state->getValue('book');
173
174   // Always save a revision for non-administrators.
175   if (!empty($entity->book['bid']) && !\Drupal::currentUser()->hasPermission('administer nodes')) {
176     $entity->setNewRevision();
177   }
178 }
179
180 /**
181  * Form submission handler for node_form().
182  *
183  * This handler is run when JavaScript is disabled. It triggers the form to
184  * rebuild so that the "Parent item" options are changed to reflect the newly
185  * selected book. When JavaScript is enabled, the submit button that triggers
186  * this handler is hidden, and the "Book" dropdown directly triggers the
187  * book_form_update() Ajax callback instead.
188  *
189  * @see book_form_update()
190  * @see book_form_node_form_alter()
191  */
192 function book_pick_book_nojs_submit($form, FormStateInterface $form_state) {
193   $node = $form_state->getFormObject()->getEntity();
194   $node->book = $form_state->getValue('book');
195   $form_state->setRebuild();
196 }
197
198 /**
199  * Renders a new parent page select element when the book selection changes.
200  *
201  * This function is called via Ajax when the selected book is changed on a node
202  * or book outline form.
203  *
204  * @return
205  *   The rendered parent page select element.
206  */
207 function book_form_update($form, FormStateInterface $form_state) {
208   return $form['book']['pid'];
209 }
210
211 /**
212  * Implements hook_ENTITY_TYPE_load() for node entities.
213  */
214 function book_node_load($nodes) {
215   /** @var \Drupal\book\BookManagerInterface $book_manager */
216   $book_manager = \Drupal::service('book.manager');
217   $links = $book_manager->loadBookLinks(array_keys($nodes), FALSE);
218   foreach ($links as $record) {
219     $nodes[$record['nid']]->book = $record;
220     $nodes[$record['nid']]->book['link_path'] = 'node/' . $record['nid'];
221     $nodes[$record['nid']]->book['link_title'] = $nodes[$record['nid']]->label();
222   }
223 }
224
225 /**
226  * Implements hook_ENTITY_TYPE_view() for node entities.
227  */
228 function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
229   if ($view_mode == 'full') {
230     if (!empty($node->book['bid']) && empty($node->in_preview)) {
231       $book_node = Node::load($node->book['bid']);
232       if (!$book_node->access()) {
233         return;
234       }
235       $build['book_navigation'] = [
236         '#theme' => 'book_navigation',
237         '#book_link' => $node->book,
238         '#weight' => 100,
239         // The book navigation is a listing of Node entities, so associate its
240         // list cache tag for correct invalidation.
241         '#cache' => [
242           'tags' => $node->getEntityType()->getListCacheTags(),
243         ],
244       ];
245     }
246   }
247 }
248
249 /**
250  * Implements hook_ENTITY_TYPE_presave() for node entities.
251  */
252 function book_node_presave(EntityInterface $node) {
253   // Make sure a new node gets a new menu link.
254   if ($node->isNew()) {
255     $node->book['nid'] = NULL;
256   }
257 }
258
259 /**
260  * Implements hook_ENTITY_TYPE_insert() for node entities.
261  */
262 function book_node_insert(EntityInterface $node) {
263   /** @var \Drupal\book\BookManagerInterface $book_manager */
264   $book_manager = \Drupal::service('book.manager');
265   $book_manager->updateOutline($node);
266 }
267
268 /**
269  * Implements hook_ENTITY_TYPE_update() for node entities.
270  */
271 function book_node_update(EntityInterface $node) {
272   /** @var \Drupal\book\BookManagerInterface $book_manager */
273   $book_manager = \Drupal::service('book.manager');
274   $book_manager->updateOutline($node);
275 }
276
277 /**
278  * Implements hook_ENTITY_TYPE_predelete() for node entities.
279  */
280 function book_node_predelete(EntityInterface $node) {
281   if (!empty($node->book['bid'])) {
282     /** @var \Drupal\book\BookManagerInterface $book_manager */
283     $book_manager = \Drupal::service('book.manager');
284     $book_manager->deleteFromBook($node->book['nid']);
285   }
286 }
287
288 /**
289  * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
290  */
291 function book_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
292   /** @var \Drupal\book\BookManagerInterface $book_manager */
293   $book_manager = \Drupal::service('book.manager');
294
295   // Prepare defaults for the add/edit form.
296   $account = \Drupal::currentUser();
297   if (empty($node->book) && ($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines'))) {
298     $node->book = [];
299
300     $query = \Drupal::request()->query;
301     if ($node->isNew() && !is_null($query->get('parent')) && is_numeric($query->get('parent'))) {
302       // Handle "Add child page" links:
303       $parent = $book_manager->loadBookLink($query->get('parent'), TRUE);
304
305       if ($parent && $parent['access']) {
306         $node->book['bid'] = $parent['bid'];
307         $node->book['pid'] = $parent['nid'];
308       }
309     }
310     // Set defaults.
311     $node_ref = !$node->isNew() ? $node->id() : 'new';
312     $node->book += $book_manager->getLinkDefaults($node_ref);
313   }
314   else {
315     if (isset($node->book['bid']) && !isset($node->book['original_bid'])) {
316       $node->book['original_bid'] = $node->book['bid'];
317     }
318   }
319   // Find the depth limit for the parent select.
320   if (isset($node->book['bid']) && !isset($node->book['parent_depth_limit'])) {
321     $node->book['parent_depth_limit'] = $book_manager->getParentDepthLimit($node->book);
322   }
323 }
324
325 /**
326  * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\Form\NodeDeleteForm.
327  *
328  * Alters the confirm form for a single node deletion.
329  */
330 function book_form_node_confirm_form_alter(&$form, FormStateInterface $form_state) {
331   // Only need to alter the delete operation form.
332   if ($form_state->getFormObject()->getOperation() !== 'delete') {
333     return;
334   }
335
336   /** @var \Drupal\node\NodeInterface $node */
337   $node = $form_state->getFormObject()->getEntity();
338   if (!book_type_is_allowed($node->getType())) {
339     // Not a book node.
340     return;
341   }
342
343   if (isset($node->book) && $node->book['has_children']) {
344     $form['book_warning'] = [
345       '#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>',
346       '#weight' => -10,
347     ];
348   }
349 }
350
351 /**
352  * Prepares variables for book listing block templates.
353  *
354  * Default template: book-all-books-block.html.twig.
355  *
356  * All non-renderable elements are removed so that the template has full access
357  * to the structured data but can also simply iterate over all elements and
358  * render them (as in the default template).
359  *
360  * @param array $variables
361  *   An associative array containing the following key:
362  *   - book_menus: An associative array containing renderable menu links for all
363  *     book menus.
364  */
365 function template_preprocess_book_all_books_block(&$variables) {
366   // Remove all non-renderable elements.
367   $elements = $variables['book_menus'];
368   $variables['book_menus'] = [];
369   foreach (Element::children($elements) as $index) {
370     $variables['book_menus'][] = [
371       'id' => $index,
372       'menu' => $elements[$index],
373       'title' => $elements[$index]['#book_title'],
374     ];
375   }
376 }
377
378 /**
379  * Prepares variables for book navigation templates.
380  *
381  * Default template: book-navigation.html.twig.
382  *
383  * @param array $variables
384  *   An associative array containing the following key:
385  *   - book_link: An associative array of book link properties.
386  *     Properties used: bid, link_title, depth, pid, nid.
387  */
388 function template_preprocess_book_navigation(&$variables) {
389   $book_link = $variables['book_link'];
390
391   // Provide extra variables for themers. Not needed by default.
392   $variables['book_id'] = $book_link['bid'];
393   $variables['book_title'] = $book_link['link_title'];
394   $variables['book_url'] = \Drupal::url('entity.node.canonical', ['node' => $book_link['bid']]);
395   $variables['current_depth'] = $book_link['depth'];
396   $variables['tree'] = '';
397
398   /** @var \Drupal\book\BookOutline $book_outline */
399   $book_outline = \Drupal::service('book.outline');
400
401   if ($book_link['nid']) {
402     $variables['tree'] = $book_outline->childrenLinks($book_link);
403
404     $build = [];
405
406     if ($prev = $book_outline->prevLink($book_link)) {
407       $prev_href = \Drupal::url('entity.node.canonical', ['node' => $prev['nid']]);
408       $build['#attached']['html_head_link'][][] = [
409         'rel' => 'prev',
410         'href' => $prev_href,
411       ];
412       $variables['prev_url'] = $prev_href;
413       $variables['prev_title'] = $prev['title'];
414     }
415
416     /** @var \Drupal\book\BookManagerInterface $book_manager */
417     $book_manager = \Drupal::service('book.manager');
418     if ($book_link['pid'] && $parent = $book_manager->loadBookLink($book_link['pid'])) {
419       $parent_href = \Drupal::url('entity.node.canonical', ['node' => $book_link['pid']]);
420       $build['#attached']['html_head_link'][][] = [
421         'rel' => 'up',
422         'href' => $parent_href,
423       ];
424       $variables['parent_url'] = $parent_href;
425       $variables['parent_title'] = $parent['title'];
426     }
427
428     if ($next = $book_outline->nextLink($book_link)) {
429       $next_href = \Drupal::url('entity.node.canonical', ['node' => $next['nid']]);
430       $build['#attached']['html_head_link'][][] = [
431         'rel' => 'next',
432         'href' => $next_href,
433       ];
434       $variables['next_url'] = $next_href;
435       $variables['next_title'] = $next['title'];
436     }
437   }
438
439   if (!empty($build)) {
440     drupal_render($build);
441   }
442
443   $variables['has_links'] = FALSE;
444   // Link variables to filter for values and set state of the flag variable.
445   $links = ['prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title'];
446   foreach ($links as $link) {
447     if (isset($variables[$link])) {
448       // Flag when there is a value.
449       $variables['has_links'] = TRUE;
450     }
451     else {
452       // Set empty to prevent notices.
453       $variables[$link] = '';
454     }
455   }
456 }
457
458 /**
459  * Prepares variables for book export templates.
460  *
461  * Default template: book-export-html.html.twig.
462  *
463  * @param array $variables
464  *   An associative array containing:
465  *   - title: The title of the book.
466  *   - contents: Output of each book page.
467  *   - depth: The max depth of the book.
468  */
469 function template_preprocess_book_export_html(&$variables) {
470   global $base_url;
471   $language_interface = \Drupal::languageManager()->getCurrentLanguage();
472
473   $variables['base_url'] = $base_url;
474   $variables['language'] = $language_interface;
475   $variables['language_rtl'] = ($language_interface->getDirection() == LanguageInterface::DIRECTION_RTL);
476
477   // HTML element attributes.
478   $attributes = [];
479   $attributes['lang'] = $language_interface->getId();
480   $attributes['dir'] = $language_interface->getDirection();
481   $variables['html_attributes'] = new Attribute($attributes);
482 }
483
484 /**
485  * Prepares variables for single node export templates.
486  *
487  * Default template: book-node-export-html.html.twig.
488  *
489  * @param array $variables
490  *   An associative array containing the following keys:
491  *   - node: The node that will be output.
492  *   - children: All the rendered child nodes within the current node. Defaults
493  *     to an empty string.
494  */
495 function template_preprocess_book_node_export_html(&$variables) {
496   $variables['depth'] = $variables['node']->book['depth'];
497   $variables['title'] = $variables['node']->label();
498 }
499
500 /**
501  * Determines if a given node type is in the list of types allowed for books.
502  *
503  * @param string $type
504  *   A node type.
505  *
506  * @return bool
507  *   A Boolean TRUE if the node type can be included in books; otherwise, FALSE.
508  */
509 function book_type_is_allowed($type) {
510   return in_array($type, \Drupal::config('book.settings')->get('allowed_types'));
511 }
512
513 /**
514  * Implements hook_ENTITY_TYPE_update() for node_type entities.
515  *
516  * Updates book.settings configuration object if the machine-readable name of a
517  * node type is changed.
518  */
519 function book_node_type_update(NodeTypeInterface $type) {
520   if ($type->getOriginalId() != $type->id()) {
521     $config = \Drupal::configFactory()->getEditable('book.settings');
522     // Update the list of node types that are allowed to be added to books.
523     $allowed_types = $config->get('allowed_types');
524     $old_key = array_search($type->getOriginalId(), $allowed_types);
525
526     if ($old_key !== FALSE) {
527       $allowed_types[$old_key] = $type->id();
528       // Ensure that the allowed_types array is sorted consistently.
529       // @see BookSettingsForm::submitForm()
530       sort($allowed_types);
531       $config->set('allowed_types', $allowed_types);
532     }
533
534     // Update the setting for the "Add child page" link.
535     if ($config->get('child_type') == $type->getOriginalId()) {
536       $config->set('child_type', $type->id());
537     }
538     $config->save();
539   }
540 }