book.module 23.6 KB
Newer Older
Dries's avatar
Dries committed
1 2
<?php

Dries's avatar
Dries committed
3 4
/**
 * @file
5
 * Allows users to create and organize related content in an outline.
Dries's avatar
Dries committed
6 7
 */

8
use Drupal\book\BookManager;
9
use Drupal\book\BookManagerInterface;
10
use Drupal\Component\Utility\SafeMarkup;
11
use Drupal\Core\Entity\EntityInterface;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\Core\Render\Element;
14
use Drupal\Core\Routing\RouteMatchInterface;
15
use Drupal\Core\Url;
16
use Drupal\node\NodeInterface;
17
use Drupal\node\NodeTypeInterface;
18
use Drupal\node\Entity\Node;
19
use Drupal\Core\Language\LanguageInterface;
20
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
21
use Drupal\Core\Template\Attribute;
22
use Drupal\Core\Extension\Extension;
23

24
/**
25
 * Implements hook_help().
26
 */
27
function book_help($route_name, RouteMatchInterface $route_match) {
28 29
  switch ($route_name) {
    case 'help.page.book':
30
      $output = '<h3>' . t('About') . '</h3>';
31
      $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>';
32 33 34
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Adding and managing book content') . '</dt>';
35 36 37 38 39
      $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>';
40
      $output .= '<dt>' . t('Book navigation') . '</dt>';
41
      $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>';
42
      $output .= '<dt>' . t('Collaboration') . '</dt>';
43
      $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>';
44
      $output .= '<dt>' . t('Printing books') . '</dt>';
45
      $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>';
46 47
      $output .= '</dl>';
      return $output;
48 49

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

52
    case 'entity.node.book_outline_form':
53
      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>';
54 55 56
  }
}

57
/**
58
 * Implements hook_theme().
59 60 61 62
 */
function book_theme() {
  return array(
    'book_navigation' => array(
63
      'variables' => array('book_link' => NULL),
64
    ),
65 66 67
    'book_tree' => array(
      'render element' => 'tree',
    ),
68 69
    'book_link' => array(
      'render element' => 'element',
70
      'function' => 'theme_book_link',
71
    ),
72
    'book_export_html' => array(
73
      'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
74
    ),
75
    'book_all_books_block' => array(
76
      'render element' => 'book_menus',
77 78
    ),
    'book_node_export_html' => array(
79
      'variables' => array('node' => NULL, 'children' => NULL),
80
    ),
81 82 83
  );
}

84
/**
85
 * Implements hook_entity_type_build().
86
 */
87 88 89
function book_entity_type_build(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['node']
90
    ->setFormClass('book_outline', 'Drupal\book\Form\BookOutlineForm')
91 92
    ->setLinkTemplate('book-outline-form', '/node/{node}/outline')
    ->setLinkTemplate('book-remove-form', '/node/{node}/outline/remove');
93 94
}

Dries's avatar
Dries committed
95
/**
96
 * Implements hook_node_links_alter().
Dries's avatar
Dries committed
97
 */
98 99 100 101 102 103 104
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');
105 106
        $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) {
107 108
          $links['book_add_child'] = array(
            'title' => t('Add child page'),
109
            'url' => Url::fromRoute('node.add', ['node_type' => $child_type], ['query' => ['parent' => $node->id()]]),
110 111 112 113 114 115
          );
        }

        if ($account->hasPermission('access printer-friendly version')) {
          $links['book_printer'] = array(
            'title' => t('Printer-friendly version'),
116 117 118 119
            'url' => Url::fromRoute('book.export', [
              'type' => 'html',
              'node' => $node->id(),
            ]),
120 121 122
            'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
          );
        }
123
      }
Dries's avatar
Dries committed
124
    }
125

126 127 128 129 130 131 132
    if (!empty($links)) {
      $node_links['book'] = array(
        '#theme' => 'links__node__book',
        '#links' => $links,
        '#attributes' => array('class' => array('links', 'inline')),
      );
    }
133
  }
Dries's avatar
Dries committed
134 135
}

136
/**
137
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
138
 *
139
 * Adds the book form element to the node form.
140 141
 *
 * @see book_pick_book_nojs_submit()
142
 */
143
function book_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
144
  $node = $form_state->getFormObject()->getEntity();
145
  $account = \Drupal::currentUser();
146
  $access = $account->hasPermission('administer book outlines');
147
  if (!$access) {
148
    if ($account->hasPermission('add content to books') && ((!empty($node->book['bid']) && !$node->isNew()) || book_type_is_allowed($node->getType()))) {
149 150
      // Already in the book hierarchy, or this node type is allowed.
      $access = TRUE;
151
    }
152
  }
153

154
  if ($access) {
155 156
    $collapsed = !($node->isNew() && !empty($node->book['pid']));
    $form = \Drupal::service('book.manager')->addFormElements($form, $form_state, $node, $account, $collapsed);
157
    // The "js-hide" class hides submit button when Javascript is enabled.
158 159 160 161 162
    $form['book']['pick-book'] = array(
      '#type' => 'submit',
      '#value' => t('Change book (update list of parents)'),
      '#submit' => array('book_pick_book_nojs_submit'),
      '#weight' => 20,
163 164 165 166 167
      '#attributes' => array(
        'class' => array(
          'js-hide',
        ),
      ),
168
    );
169
    $form['#entity_builders'][] = 'book_node_builder';
170
  }
171
}
172

173 174 175 176 177
/**
 * Entity form builder to add the book information to the node.
 *
 * @todo: Remove this in favor of an entity field.
 */
178
function book_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
179
  $entity->book = $form_state->getValue('book');
180 181 182 183 184

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

187
/**
188
 * Form submission handler for node_form().
189 190 191 192 193
 *
 * 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
194
 * book_form_update() Ajax callback instead.
195 196
 *
 * @see book_form_update()
197
 * @see book_form_node_form_alter()
198
 */
199
function book_pick_book_nojs_submit($form, FormStateInterface $form_state) {
200
  $node = $form_state->getFormObject()->getEntity();
201
  $node->book = $form_state->getValue('book');
202
  $form_state->setRebuild();
203 204
}

205 206 207
/**
 * Renders a new parent page select element when the book selection changes.
 *
208
 * This function is called via Ajax when the selected book is changed on a node
209 210 211 212 213
 * or book outline form.
 *
 * @return
 *   The rendered parent page select element.
 */
214
function book_form_update($form, FormStateInterface $form_state) {
215
  return $form['book']['pid'];
216 217
}

218
/**
219
 * Implements hook_ENTITY_TYPE_load() for node entities.
220
 */
221
function book_node_load($nodes) {
222 223 224 225
  /** @var \Drupal\book\BookManagerInterface $book_manager */
  $book_manager = \Drupal::service('book.manager');
  $links = $book_manager->loadBookLinks(array_keys($nodes), FALSE);
  foreach ($links as $record) {
226
    $nodes[$record['nid']]->book = $record;
227 228
    $nodes[$record['nid']]->book['link_path'] = 'node/' . $record['nid'];
    $nodes[$record['nid']]->book['link_title'] = $nodes[$record['nid']]->label();
229 230
  }
}
231

232
/**
233
 * Implements hook_ENTITY_TYPE_view() for node entities.
234
 */
235
function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
236
  if ($view_mode == 'full') {
237
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
238 239 240 241
      $book_node = Node::load($node->book['bid']);
      if (!$book_node->access()) {
        return;
      }
242
      $book_navigation = array( '#theme' => 'book_navigation', '#book_link' => $node->book);
243
      $build['book_navigation'] = array(
244
        '#markup' => drupal_render($book_navigation),
245
        '#weight' => 100,
246 247 248 249 250
        // The book navigation is a listing of Node entities, so associate its
        // list cache tag for correct invalidation.
        '#cache' => [
          'tags' => $node->getEntityType()->getListCacheTags(),
        ],
251 252 253
      );
    }
  }
254 255
}

256
/**
257
 * Implements hook_ENTITY_TYPE_presave() for node entities.
258
 */
259
function book_node_presave(EntityInterface $node) {
260
  // Make sure a new node gets a new menu link.
261
  if ($node->isNew()) {
262
    $node->book['nid'] = NULL;
263 264
  }
}
265

266
/**
267
 * Implements hook_ENTITY_TYPE_insert() for node entities.
268
 */
269
function book_node_insert(EntityInterface $node) {
270
  /** @var \Drupal\book\BookManagerInterface $book_manager */
271
  $book_manager = \Drupal::service('book.manager');
272
  $book_manager->updateOutline($node);
273
}
274

275
/**
276
 * Implements hook_ENTITY_TYPE_update() for node entities.
277
 */
278
function book_node_update(EntityInterface $node) {
279
  /** @var \Drupal\book\BookManagerInterface $book_manager */
280
  $book_manager = \Drupal::service('book.manager');
281
  $book_manager->updateOutline($node);
282
}
283

284
/**
285
 * Implements hook_ENTITY_TYPE_predelete() for node entities.
286
 */
287
function book_node_predelete(EntityInterface $node) {
288
  if (!empty($node->book['bid'])) {
289 290 291
    /** @var \Drupal\book\BookManagerInterface $book_manager */
    $book_manager = \Drupal::service('book.manager');
    $book_manager->deleteFromBook($node->book['nid']);
292 293 294 295
  }
}

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

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

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

      if ($parent && $parent['access']) {
        $node->book['bid'] = $parent['bid'];
314
        $node->book['pid'] = $parent['nid'];
315
      }
316 317
    }
    // Set defaults.
318 319
    $node_ref = !$node->isNew() ? $node->id() : 'new';
    $node->book += $book_manager->getLinkDefaults($node_ref);
320 321 322 323 324 325 326 327
  }
  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'])) {
328
    $node->book['parent_depth_limit'] = $book_manager->getParentDepthLimit($node->book);
329 330 331 332
  }
}

/**
333
 * Implements hook_form_FORM_ID_alter() for node_delete_confirm().
334 335 336 337
 *
 * Alters the confirm form for a single node deletion.
 *
 * @see node_delete_confirm()
338
 */
339
function book_form_node_delete_confirm_alter(&$form, FormStateInterface $form_state) {
340
  $node = Node::load($form['nid']['#value']);
341 342 343

  if (isset($node->book) && $node->book['has_children']) {
    $form['book_warning'] = array(
344
      '#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>',
345 346
      '#weight' => -10,
    );
Dries's avatar
Dries committed
347
  }
Dries's avatar
Dries committed
348
}
Dries's avatar
Dries committed
349

350
/**
351 352 353
 * Prepares variables for book listing block templates.
 *
 * Default template: book-all-books-block.html.twig.
354
 *
355 356 357
 * 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).
358
 *
359 360
 * @param array $variables
 *   An associative array containing the following key:
361 362
 *   - book_menus: An associative array containing renderable menu links for all
 *     book menus.
363 364 365 366 367
 */
function template_preprocess_book_all_books_block(&$variables) {
  // Remove all non-renderable elements.
  $elements = $variables['book_menus'];
  $variables['book_menus'] = array();
368
  foreach (Element::children($elements) as $index) {
369 370 371 372 373
    $variables['book_menus'][] = array(
      'id' => $index,
      'menu' => $elements[$index],
      'title' => $elements[$index]['#book_title'],
    );
374 375 376
  }
}

377
/**
378 379 380
 * Prepares variables for book navigation templates.
 *
 * Default template: book-navigation.html.twig.
381
 *
382 383
 * @param array $variables
 *   An associative array containing the following key:
384
 *   - book_link: An associative array of book link properties.
385
 *     Properties used: bid, link_title, depth, pid, nid.
386
 */
387 388 389 390 391
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'];
392
  $variables['book_title'] = SafeMarkup::checkPlain($book_link['link_title']);
393
  $variables['book_url'] = \Drupal::url('entity.node.canonical', array('node' => $book_link['bid']));
394 395
  $variables['current_depth'] = $book_link['depth'];
  $variables['tree'] = '';
396

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

400
  if ($book_link['nid']) {
401
    $variables['tree'] = $book_outline->childrenLinks($book_link);
Dries's avatar
Dries committed
402

403 404
    $build = array();

405
    if ($prev = $book_outline->prevLink($book_link)) {
406
      $prev_href = \Drupal::url('entity.node.canonical', array('node' => $prev['nid']));
407
      $build['#attached']['html_head_link'][][] = array(
408 409 410
        'rel' => 'prev',
        'href' => $prev_href,
      );
411
      $variables['prev_url'] = $prev_href;
412
      $variables['prev_title'] = SafeMarkup::checkPlain($prev['title']);
Dries's avatar
Dries committed
413
    }
414

415 416 417
    /** @var \Drupal\book\BookManagerInterface $book_manager */
    $book_manager = \Drupal::service('book.manager');
    if ($book_link['pid'] && $parent = $book_manager->loadBookLink($book_link['pid'])) {
418
      $parent_href = \Drupal::url('entity.node.canonical', array('node' => $book_link['pid']));
419
      $build['#attached']['html_head_link'][][] = array(
420 421 422
        'rel' => 'up',
        'href' => $parent_href,
      );
423
      $variables['parent_url'] = $parent_href;
424
      $variables['parent_title'] = SafeMarkup::checkPlain($parent['title']);
Dries's avatar
Dries committed
425
    }
426

427
    if ($next = $book_outline->nextLink($book_link)) {
428
      $next_href = \Drupal::url('entity.node.canonical', array('node' => $next['nid']));
429
      $build['#attached']['html_head_link'][][] = array(
430 431 432
        'rel' => 'next',
        'href' => $next_href,
      );
433
      $variables['next_url'] = $next_href;
434
      $variables['next_title'] = SafeMarkup::checkPlain($next['title']);
Dries's avatar
Dries committed
435
    }
436
  }
Dries's avatar
Dries committed
437

438 439 440 441
  if (!empty($build)) {
    drupal_render($build);
  }

442 443 444 445 446 447 448 449 450 451 452
  $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] = '';
453
    }
Dries's avatar
Dries committed
454
  }
Dries's avatar
Dries committed
455
}
Dries's avatar
Dries committed
456

457
/**
458
 * Prepares variables for book export templates.
459
 *
460
 * Default template: book-export-html.html.twig.
461
 *
462 463 464 465 466
 * @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.
467 468
 */
function template_preprocess_book_export_html(&$variables) {
469
  global $base_url;
470
  $language_interface = \Drupal::languageManager()->getCurrentLanguage();
471

472
  $variables['title'] = SafeMarkup::checkPlain($variables['title']);
473
  $variables['base_url'] = $base_url;
474
  $variables['language'] = $language_interface;
475
  $variables['language_rtl'] = ($language_interface->getDirection() == LanguageInterface::DIRECTION_RTL);
476
  $variables['head'] = drupal_get_html_head();
477 478

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

485
/**
486 487 488
 * Prepares variables for single node export templates.
 *
 * Default template: book-node-export-html.html.twig.
489
 *
490 491
 * @param array $variables
 *   An associative array containing the following keys:
492 493 494
 *   - node: The node that will be output.
 *   - children: All the rendered child nodes within the current node. Defaults
 *     to an empty string.
495
 */
496 497
function template_preprocess_book_node_export_html(&$variables) {
  $variables['depth'] = $variables['node']->book['depth'];
498
  $variables['title'] = SafeMarkup::checkPlain($variables['node']->label());
499
  $variables['content'] = $variables['node']->rendered;
500 501
}

502
/**
503
 * Implements template_preprocess_HOOK() for book-tree.html.twig.
504 505 506 507 508
 */
function template_preprocess_book_tree(&$variables) {
  $variables['tree'] = $variables['tree']['#children'];
}

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
/**
 * 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;
526 527 528
  /** @var \Drupal\Core\Url $url */
  $url = $element['#url'];
  $url->setOptions($element['#localized_options'] + $url->getOptions());
529
  $output = \Drupal::l($element['#title'], $url);
530 531 532
  return '<li' . new Attribute($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

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

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

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

    // Update the setting for the "Add child page" link.
568
    if ($config->get('child_type') == $type->getOriginalId()) {
569
      $config->set('child_type', $type->id());
570
    }
571
    $config->save();
572
  }
Dries's avatar
Dries committed
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

/**
 * 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.');
      }
    }
  }
}