summaryrefslogtreecommitdiffstats
path: root/core/modules/book/book.module
blob: c8a43c7c692d061675316ebc0920e46f3da0e5de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
<?php

/**
 * @file
 * Allows users to create and organize related content in an outline.
 */

use Drupal\book\BookManager;
use Drupal\book\BookManagerInterface;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\node\NodeInterface;
use Drupal\node\NodeTypeInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Extension\Extension;

/**
 * Implements hook_help().
 */
function book_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.book':
      $output = '<h3>' . t('About') . '</h3>';
      $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>.', array('!book' => 'https://www.drupal.org/documentation/modules/book')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Adding and managing book content') . '</dt>';
      $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>';
      $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>.', array('!admin-book' => \Drupal::url('book.admin'))) . '</dd>';
      $output .= '<dt>' . t('Configuring content types for books') . '</dt>';
      $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.', array('!admin-settings' => \Drupal::url('book.settings'))) . '</dd>';
      $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.', array('!admin-settings' => \Drupal::url('book.settings'))) . '</dd>';
      $output .= '<dt>' . t('Book navigation') . '</dt>';
      $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.", array('!admin-block' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#')) . '</dd>';
      $output .= '<dt>' . t('Collaboration') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Printing books') . '</dt>';
      $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>';
      $output .= '</dl>';
      return $output;

    case 'book.admin':
      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>';

    case 'entity.node.book_outline_form':
      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>.', array('!book' => \Drupal::url('book.render'), '!book-admin' => \Drupal::url('book.admin'))) . '</p>';
  }
}

/**
 * Implements hook_theme().
 */
function book_theme() {
  return array(
    'book_navigation' => array(
      'variables' => array('book_link' => NULL),
    ),
    'book_tree' => array(
      'render element' => 'tree',
    ),
    'book_link' => array(
      'render element' => 'element',
      'function' => 'theme_book_link',
    ),
    'book_export_html' => array(
      'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
    ),
    'book_all_books_block' => array(
      'render element' => 'book_menus',
    ),
    'book_node_export_html' => array(
      'variables' => array('node' => NULL, 'children' => NULL),
    ),
  );
}

/**
 * Implements hook_entity_type_build().
 */
function book_entity_type_build(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['node']
    ->setFormClass('book_outline', 'Drupal\book\Form\BookOutlineForm')
    ->setLinkTemplate('book-outline-form', '/node/{node}/outline')
    ->setLinkTemplate('book-remove-form', '/node/{node}/outline/remove');
}

/**
 * Implements hook_node_links_alter().
 */
function book_node_links_alter(array &$node_links, NodeInterface $node, array &$context) {
  if ($context['view_mode'] != 'rss') {
    $account = \Drupal::currentUser();

    if (isset($node->book['depth'])) {
      if ($context['view_mode'] == 'full' && node_is_page($node)) {
        $child_type = \Drupal::config('book.settings')->get('child_type');
        $access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node');
        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) {
          $links['book_add_child'] = array(
            'title' => t('Add child page'),
            'url' => Url::fromRoute('node.add', ['node_type' => $child_type], ['query' => ['parent' => $node->id()]]),
          );
        }

        if ($account->hasPermission('access printer-friendly version')) {
          $links['book_printer'] = array(
            'title' => t('Printer-friendly version'),
            'url' => Url::fromRoute('book.export', [
              'type' => 'html',
              'node' => $node->id(),
            ]),
            'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
          );
        }
      }
    }

    if (!empty($links)) {
      $node_links['book'] = array(
        '#theme' => 'links__node__book',
        '#links' => $links,
        '#attributes' => array('class' => array('links', 'inline')),
      );
    }
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 *
 * Adds the book form element to the node form.
 *
 * @see book_pick_book_nojs_submit()
 */
function book_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $node = $form_state->getFormObject()->getEntity();
  $account = \Drupal::currentUser();
  $access = $account->hasPermission('administer book outlines');
  if (!$access) {
    if ($account->hasPermission('add content to books') && ((!empty($node->book['bid']) && !$node->isNew()) || book_type_is_allowed($node->getType()))) {
      // Already in the book hierarchy, or this node type is allowed.
      $access = TRUE;
    }
  }

  if ($access) {
    $collapsed = !($node->isNew() && !empty($node->book['pid']));
    $form = \Drupal::service('book.manager')->addFormElements($form, $form_state, $node, $account, $collapsed);
    // The "js-hide" class hides submit button when Javascript is enabled.
    $form['book']['pick-book'] = array(
      '#type' => 'submit',
      '#value' => t('Change book (update list of parents)'),
      '#submit' => array('book_pick_book_nojs_submit'),
      '#weight' => 20,
      '#attributes' => array(
        'class' => array(
          'js-hide',
        ),
      ),
    );
    $form['#entity_builders'][] = 'book_node_builder';
  }
}

/**
 * Entity form builder to add the book information to the node.
 *
 * @todo: Remove this in favor of an entity field.
 */
function book_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->book = $form_state->getValue('book');

  // Always save a revision for non-administrators.
  if (!empty($entity->book['bid']) && !\Drupal::currentUser()->hasPermission('administer nodes')) {
    $entity->setNewRevision();
  }
}

/**
 * Form submission handler for node_form().
 *
 * This handler is run when JavaScript is disabled. It triggers the form to
 * rebuild so that the "Parent item" options are changed to reflect the newly
 * selected book. When JavaScript is enabled, the submit button that triggers
 * this handler is hidden, and the "Book" dropdown directly triggers the
 * book_form_update() Ajax callback instead.
 *
 * @see book_form_update()
 * @see book_form_node_form_alter()
 */
function book_pick_book_nojs_submit($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  $node->book = $form_state->getValue('book');
  $form_state->setRebuild();
}

/**
 * Renders a new parent page select element when the book selection changes.
 *
 * This function is called via Ajax when the selected book is changed on a node
 * or book outline form.
 *
 * @return
 *   The rendered parent page select element.
 */
function book_form_update($form, FormStateInterface $form_state) {
  return $form['book']['pid'];
}

/**
 * Implements hook_ENTITY_TYPE_load() for node entities.
 */
function book_node_load($nodes) {
  /** @var \Drupal\book\BookManagerInterface $book_manager */
  $book_manager = \Drupal::service('book.manager');
  $links = $book_manager->loadBookLinks(array_keys($nodes), FALSE);
  foreach ($links as $record) {
    $nodes[$record['nid']]->book = $record;
    $nodes[$record['nid']]->book['link_path'] = 'node/' . $record['nid'];
    $nodes[$record['nid']]->book['link_title'] = $nodes[$record['nid']]->label();
  }
}

/**
 * Implements hook_ENTITY_TYPE_view() for node entities.
 */
function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $book_node = Node::load($node->book['bid']);
      if (!$book_node->access()) {
        return;
      }
      $book_navigation = array( '#theme' => 'book_navigation', '#book_link' => $node->book);
      $build['book_navigation'] = array(
        '#markup' => drupal_render($book_navigation),
        '#weight' => 100,
        // The book navigation is a listing of Node entities, so associate its
        // list cache tag for correct invalidation.
        '#cache' => [
          'tags' => $node->getEntityType()->getListCacheTags(),
        ],
      );
    }
  }
}

/**
 * Implements hook_ENTITY_TYPE_presave() for node entities.
 */
function book_node_presave(EntityInterface $node) {
  // Make sure a new node gets a new menu link.
  if ($node->isNew()) {
    $node->book['nid'] = NULL;
  }
}

/**
 * Implements hook_ENTITY_TYPE_insert() for node entities.
 */
function book_node_insert(EntityInterface $node) {
  /** @var \Drupal\book\BookManagerInterface $book_manager */
  $book_manager = \Drupal::service('book.manager');
  $book_manager->updateOutline($node);
}

/**
 * Implements hook_ENTITY_TYPE_update() for node entities.
 */
function book_node_update(EntityInterface $node) {
  /** @var \Drupal\book\BookManagerInterface $book_manager */
  $book_manager = \Drupal::service('book.manager');
  $book_manager->updateOutline($node);
}

/**
 * Implements hook_ENTITY_TYPE_predelete() for node entities.
 */
function book_node_predelete(EntityInterface $node) {
  if (!empty($node->book['bid'])) {
    /** @var \Drupal\book\BookManagerInterface $book_manager */
    $book_manager = \Drupal::service('book.manager');
    $book_manager->deleteFromBook($node->book['nid']);
  }
}

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
 */
function book_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
  /** @var \Drupal\book\BookManagerInterface $book_manager */
  $book_manager = \Drupal::service('book.manager');

  // Prepare defaults for the add/edit form.
  $account = \Drupal::currentUser();
  if (empty($node->book) && ($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines'))) {
    $node->book = array();

    $query = \Drupal::request()->query;
    if ($node->isNew() && !is_null($query->get('parent')) && is_numeric($query->get('parent'))) {
      // Handle "Add child page" links:
      $parent = $book_manager->loadBookLink($query->get('parent'), TRUE);

      if ($parent && $parent['access']) {
        $node->book['bid'] = $parent['bid'];
        $node->book['pid'] = $parent['nid'];
      }
    }
    // Set defaults.
    $node_ref = !$node->isNew() ? $node->id() : 'new';
    $node->book += $book_manager->getLinkDefaults($node_ref);
  }
  else {
    if (isset($node->book['bid']) && !isset($node->book['original_bid'])) {
      $node->book['original_bid'] = $node->book['bid'];
    }
  }
  // Find the depth limit for the parent select.
  if (isset($node->book['bid']) && !isset($node->book['parent_depth_limit'])) {
    $node->book['parent_depth_limit'] = $book_manager->getParentDepthLimit($node->book);
  }
}

/**
 * Implements hook_form_FORM_ID_alter() for node_delete_confirm().
 *
 * Alters the confirm form for a single node deletion.
 *
 * @see node_delete_confirm()
 */
function book_form_node_delete_confirm_alter(&$form, FormStateInterface $form_state) {
  $node = Node::load($form['nid']['#value']);

  if (isset($node->book) && $node->book['has_children']) {
    $form['book_warning'] = array(
      '#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.', array('%title' => $node->label())) . '</p>',
      '#weight' => -10,
    );
  }
}

/**
 * Prepares variables for book listing block templates.
 *
 * Default template: book-all-books-block.html.twig.
 *
 * All non-renderable elements are removed so that the template has full access
 * to the structured data but can also simply iterate over all elements and
 * render them (as in the default template).
 *
 * @param array $variables
 *   An associative array containing the following key:
 *   - book_menus: An associative array containing renderable menu links for all
 *     book menus.
 */
function template_preprocess_book_all_books_block(&$variables) {
  // Remove all non-renderable elements.
  $elements = $variables['book_menus'];
  $variables['book_menus'] = array();
  foreach (Element::children($elements) as $index) {
    $variables['book_menus'][] = array(
      'id' => $index,
      'menu' => $elements[$index],
      'title' => $elements[$index]['#book_title'],
    );
  }
}

/**
 * Prepares variables for book navigation templates.
 *
 * Default template: book-navigation.html.twig.
 *
 * @param array $variables
 *   An associative array containing the following key:
 *   - book_link: An associative array of book link properties.
 *     Properties used: bid, link_title, depth, pid, nid.
 */
function template_preprocess_book_navigation(&$variables) {
  $book_link = $variables['book_link'];

  // Provide extra variables for themers. Not needed by default.
  $variables['book_id'] = $book_link['bid'];
  $variables['book_title'] = SafeMarkup::checkPlain($book_link['link_title']);
  $variables['book_url'] = \Drupal::url('entity.node.canonical', array('node' => $book_link['bid']));
  $variables['current_depth'] = $book_link['depth'];
  $variables['tree'] = '';

  /** @var \Drupal\book\BookOutline $book_outline */
  $book_outline = \Drupal::service('book.outline');

  if ($book_link['nid']) {
    $variables['tree'] = $book_outline->childrenLinks($book_link);

    $build = array();

    if ($prev = $book_outline->prevLink($book_link)) {
      $prev_href = \Drupal::url('entity.node.canonical', array('node' => $prev['nid']));
      $build['#attached']['html_head_link'][][] = array(
        'rel' => 'prev',
        'href' => $prev_href,
      );
      $variables['prev_url'] = $prev_href;
      $variables['prev_title'] = SafeMarkup::checkPlain($prev['title']);
    }

    /** @var \Drupal\book\BookManagerInterface $book_manager */
    $book_manager = \Drupal::service('book.manager');
    if ($book_link['pid'] && $parent = $book_manager->loadBookLink($book_link['pid'])) {
      $parent_href = \Drupal::url('entity.node.canonical', array('node' => $book_link['pid']));
      $build['#attached']['html_head_link'][][] = array(
        'rel' => 'up',
        'href' => $parent_href,
      );
      $variables['parent_url'] = $parent_href;
      $variables['parent_title'] = SafeMarkup::checkPlain($parent['title']);
    }

    if ($next = $book_outline->nextLink($book_link)) {
      $next_href = \Drupal::url('entity.node.canonical', array('node' => $next['nid']));
      $build['#attached']['html_head_link'][][] = array(
        'rel' => 'next',
        'href' => $next_href,
      );
      $variables['next_url'] = $next_href;
      $variables['next_title'] = SafeMarkup::checkPlain($next['title']);
    }
  }

  if (!empty($build)) {
    drupal_render($build);
  }

  $variables['has_links'] = FALSE;
  // Link variables to filter for values and set state of the flag variable.
  $links = array('prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title');
  foreach ($links as $link) {
    if (isset($variables[$link])) {
      // Flag when there is a value.
      $variables['has_links'] = TRUE;
    }
    else {
      // Set empty to prevent notices.
      $variables[$link] = '';
    }
  }
}

/**
 * Prepares variables for book export templates.
 *
 * Default template: book-export-html.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - title: The title of the book.
 *   - contents: Output of each book page.
 *   - depth: The max depth of the book.
 */
function template_preprocess_book_export_html(&$variables) {
  global $base_url;
  $language_interface = \Drupal::languageManager()->getCurrentLanguage();

  $variables['title'] = SafeMarkup::checkPlain($variables['title']);
  $variables['base_url'] = $base_url;
  $variables['language'] = $language_interface;
  $variables['language_rtl'] = ($language_interface->getDirection() == LanguageInterface::DIRECTION_RTL);
  $variables['head'] = drupal_get_html_head();

  // HTML element attributes.
  $attributes = array();
  $attributes['lang'] = $language_interface->getId();
  $attributes['dir'] = $language_interface->getDirection();
  $variables['html_attributes'] = new Attribute($attributes);
}

/**
 * Prepares variables for single node export templates.
 *
 * Default template: book-node-export-html.html.twig.
 *
 * @param array $variables
 *   An associative array containing the following keys:
 *   - node: The node that will be output.
 *   - children: All the rendered child nodes within the current node. Defaults
 *     to an empty string.
 */
function template_preprocess_book_node_export_html(&$variables) {
  $variables['depth'] = $variables['node']->book['depth'];
  $variables['title'] = SafeMarkup::checkPlain($variables['node']->label());
  $variables['content'] = $variables['node']->rendered;
}

/**
 * Implements template_preprocess_HOOK() for book-tree.html.twig.
 */
function template_preprocess_book_tree(&$variables) {
  $variables['tree'] = $variables['tree']['#children'];
}

/**
 * Returns HTML for a book link and subtree.
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: Structured array data for a book link.
 *
 * @ingroup themeable
 */
function theme_book_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $element['#localized_options']['set_active_class'] = TRUE;
  /** @var \Drupal\Core\Url $url */
  $url = $element['#url'];
  $url->setOptions($element['#localized_options'] + $url->getOptions());
  $output = \Drupal::l($element['#title'], $url);
  return '<li' . new Attribute($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

/**
 * Determines if a given node type is in the list of types allowed for books.
 *
 * @param string $type
 *   A node type.
 *
 * @return bool
 *   A Boolean TRUE if the node type can be included in books; otherwise, FALSE.
 */
function book_type_is_allowed($type) {
  return in_array($type, \Drupal::config('book.settings')->get('allowed_types'));
}

/**
 * Implements hook_ENTITY_TYPE_update() for node_type entities.
 *
 * Updates book.settings configuration object if the machine-readable name of a
 * node type is changed.
 */
function book_node_type_update(NodeTypeInterface $type) {
  if ($type->getOriginalId() != $type->id()) {
    $config = \Drupal::configFactory()->getEditable('book.settings');
    // Update the list of node types that are allowed to be added to books.
    $allowed_types = $config->get('allowed_types');
    $old_key = array_search($type->getOriginalId(), $allowed_types);

    if ($old_key !== FALSE) {
      $allowed_types[$old_key] = $type->id();
      // Ensure that the allowed_types array is sorted consistently.
      // @see BookSettingsForm::submitForm()
      sort($allowed_types);
      $config->set('allowed_types', $allowed_types);
    }

    // Update the setting for the "Add child page" link.
    if ($config->get('child_type') == $type->getOriginalId()) {
      $config->set('child_type', $type->id());
    }
    $config->save();
  }
}

/**
 * Implements hook_system_info_alter().
 *
 * Prevents book module from being uninstalled whilst any book nodes exist or
 * there are any book outline stored.
 */
function book_system_info_alter(&$info, Extension $file, $type) {
  // It is not safe use the entity query service during maintenance mode.
  if ($type == 'module' && !defined('MAINTENANCE_MODE') && $file->getName() == 'book') {
    if (\Drupal::service('book.outline_storage')->hasBooks()) {
      $info['required'] = TRUE;
      $info['explanation'] = t('To uninstall Book, delete all content that is part of a book.');
    }
    else {
      // The book node type is provided by the Book module. Prevent uninstall if
      // there are any nodes of that type.
      $factory = \Drupal::service('entity.query');
      $nodes = $factory->get('node')
        ->condition('type', 'book')
        ->accessCheck(FALSE)
        ->range(0, 1)
        ->execute();
      if (!empty($nodes)) {
        $info['required'] = TRUE;
        $info['explanation'] = t('To uninstall Book, delete all content that has the Book content type.');
      }
    }
  }
}