book.module 27.9 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\Core\Entity\EntityInterface;
9
use Drupal\node\NodeInterface;
10
use Drupal\node\NodeTypeInterface;
11
use Drupal\Core\Language\Language;
12
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
13
use Drupal\Core\Template\Attribute;
14

15
/**
16
 * Implements hook_help().
17
18
19
20
21
 */
function book_help($path, $arg) {
  switch ($path) {
    case 'admin/help#book':
      $output = '<h3>' . t('About') . '</h3>';
22
      $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. For more information, see the <a href="!book">online documentation for the Book module</a>.', array('!book' => 'https://drupal.org/documentation/modules/book')) . '</p>';
23
24
25
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Adding and managing book content') . '</dt>';
26
      $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 administration page</a>.', array('!admin-book' => \Drupal::url('book.admin'))) . '</dd>';
27
      $output .= '<dt>' . t('Book navigation') . '</dt>';
28
      $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 administration page</a>. For book pages to show up in the book navigation, they must be added to a book outline.", array('!admin-block' => \Drupal::url('block.admin_display'))) . '</dd>';
29
30
31
      $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 menu.') . '</dd>';
      $output .= '<dt>' . t('Printing books') . '</dt>';
32
      $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>';
33
34
      $output .= '</dl>';
      return $output;
35
    case 'admin/structure/book':
36
37
      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 'node/%/outline':
38
      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>';
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
/**
 * Implements hook_entity_bundle_info().
 */
function book_entity_bundle_info() {
  $bundles['menu_link']['book-toc'] = array(
    'label' => t('Book'),
    'translatable' => FALSE,
  );
  return $bundles;
}

/**
 * Implements hook_TYPE_load().
 */
function book_menu_link_load($entities) {
  foreach ($entities as $entity) {
    // Change the bundle of menu links related to a book.
    if (strpos($entity->menu_name, 'book-toc-') === 0) {
      $entity->bundle = 'book-toc';
    }
  }
}

65
/**
66
 * Implements hook_theme().
67
68
69
70
 */
function book_theme() {
  return array(
    'book_navigation' => array(
71
      'variables' => array('book_link' => NULL),
72
      'template' => 'book-navigation',
73
74
    ),
    'book_export_html' => array(
75
      'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
76
      'template' => 'book-export-html',
77
78
    ),
    'book_admin_table' => array(
79
      'render element' => 'form',
80
      'file' => 'book.admin.inc',
81
    ),
Dries's avatar
Dries committed
82
    'book_all_books_block' => array(
83
      'render element' => 'book_menus',
84
85
86
      'template' => 'book-all-books-block',
    ),
    'book_node_export_html' => array(
87
      'variables' => array('node' => NULL, 'children' => NULL),
88
      'template' => 'book-node-export-html',
Dries's avatar
Dries committed
89
    ),
90
91
92
  );
}

93
/**
94
 * Implements hook_permission().
95
 */
96
function book_permission() {
97
  return array(
98
99
100
101
102
103
104
    'administer book outlines' => array(
      'title' => t('Administer book outlines'),
    ),
    'create new books' => array(
      'title' => t('Create new books'),
    ),
    'add content to books' => array(
105
      'title' => t('Add content and child pages to books'),
106
107
    ),
    'access printer-friendly version' => array(
108
      'title' => t('View printer-friendly books'),
109
110
      'description' => t('View a book page and all of its sub-pages as a single document for ease of printing. Can be performance heavy.'),
    ),
111
  );
Dries's avatar
   
Dries committed
112
113
}

114
115
116
117
/**
 * Implements hook_entity_info().
 */
function book_entity_info(&$entity_info) {
118
  /** @var $entity_info \Drupal\Core\Entity\EntityTypeInterface[] */
119
  $entity_info['node']->setFormClass('book_outline', 'Drupal\book\Form\BookOutlineForm');
120
121
}

Dries's avatar
   
Dries committed
122
/**
123
 * Implements hook_node_links_alter().
Dries's avatar
   
Dries committed
124
 */
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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_controller = \Drupal::entityManager()->getAccessController('node');
        if (($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines')) && $access_controller->createAccess($child_type) && $node->isPublished() && $node->book['depth'] < MENU_MAX_DEPTH) {
          $links['book_add_child'] = array(
            'title' => t('Add child page'),
            'href' => 'node/add/' . $child_type,
            'query' => array('parent' => $node->book['mlid']),
          );
        }

        if ($account->hasPermission('access printer-friendly version')) {
          $links['book_printer'] = array(
            'title' => t('Printer-friendly version'),
            'href' => 'book/export/html/' . $node->id(),
            'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
          );
        }
148
      }
Dries's avatar
   
Dries committed
149
    }
150

151
152
153
154
155
156
157
    if (!empty($links)) {
      $node_links['book'] = array(
        '#theme' => 'links__node__book',
        '#links' => $links,
        '#attributes' => array('class' => array('links', 'inline')),
      );
    }
158
  }
Dries's avatar
   
Dries committed
159
160
}

Dries's avatar
   
Dries committed
161
/**
162
 * Implements hook_menu().
Dries's avatar
   
Dries committed
163
 */
164
function book_menu() {
165
  $items['admin/structure/book'] = array(
166
    'title' => 'Books',
167
    'description' => "Manage your site's book outlines.",
168
    'route_name' => 'book.admin',
169
170
  );
  $items['book'] = array(
171
    'title' => 'Books',
172
    'route_name' => 'book.render',
173
174
    'type' => MENU_SUGGESTED_ITEM,
  );
Dries's avatar
Dries committed
175
176
  $items['node/%node/outline/remove'] = array(
    'title' => 'Remove from outline',
177
    'route_name' => 'book.remove',
Dries's avatar
Dries committed
178
  );
179

Dries's avatar
   
Dries committed
180
181
182
  return $items;
}

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
 * Implements hook_menu_link_defaults().
 */
function book_menu_link_defaults() {
  $links['book.admin.outlines'] = array(
    'link_title' => 'Books',
    'description' => "Manage your site's book outlines.",
    'parent' => 'system.admin.structure',
    'route_name' => 'book.admin',
  );
  $links['book'] = array(
    'link_title' => 'Books',
    'route_name' => 'book.render',
    // @todo what to do about MENU_SUGGESTED_ITEM, maybe specify no menu_name?
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $links;
}

203
204
205
206
/**
 * Implements hook_admin_paths().
 */
function book_admin_paths() {
207
  if (\Drupal::config('node.settings')->get('use_admin_theme')) {
208
209
210
211
212
213
    $paths = array(
      'node/*/outline' => TRUE,
      'node/*/outline/remove' => TRUE,
    );
    return $paths;
  }
214
215
}

216
/**
Dries's avatar
Dries committed
217
218
 * Returns an array of all books.
 *
219
220
 * @todo Remove in favor of BookManager Service. http://drupal.org/node/1963894
 *
Dries's avatar
Dries committed
221
222
 * This list may be used for generating a list of all the books, or for building
 * the options for a form select.
223
224
225
 *
 * @return
 *   An array of all books.
226
 */
Dries's avatar
Dries committed
227
function book_get_books() {
228
  return \Drupal::service('book.manager')->getAllBooks();
229
}
230

Dries's avatar
Dries committed
231
/**
232
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
233
 *
234
 * Adds the book form element to the node form.
235
236
 *
 * @see book_pick_book_nojs_submit()
Dries's avatar
Dries committed
237
 */
238
function book_form_node_form_alter(&$form, &$form_state, $form_id) {
239
  $node = $form_state['controller']->getEntity();
240
  $account = \Drupal::currentUser();
241
  $access = $account->hasPermission('administer book outlines');
242
  if (!$access) {
243
    if ($account->hasPermission('add content to books') && ((!empty($node->book['mlid']) && !$node->isNew()) || book_type_is_allowed($node->getType()))) {
244
245
      // Already in the book hierarchy, or this node type is allowed.
      $access = TRUE;
Dries's avatar
Dries committed
246
    }
247
  }
Dries's avatar
Dries committed
248

249
  if ($access) {
250
    $form = \Drupal::service('book.manager')->addFormElements($form, $form_state, $node, $account);
251
    // Since the "Book" dropdown can't trigger a form submission when
252
    // JavaScript is disabled, add a submit button to do that. book.admin.css hides
253
254
255
256
257
258
    // this 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,
259
      '#attached' => array(
260
        'css' => array(drupal_get_path('module', 'book') . '/css/book.admin.css'),
261
      ),
262
    );
263
    $form['#entity_builders'][] = 'book_node_builder';
264
  }
Dries's avatar
Dries committed
265
}
266

267
268
269
270
271
272
273
274
275
/**
 * 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, $entity, &$form, &$form_state) {
  $entity->book = $form_state['values']['book'];
}

276
/**
277
 * Form submission handler for node_form().
278
279
280
281
282
 *
 * 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
283
 * book_form_update() Ajax callback instead.
284
285
 *
 * @see book_form_update()
286
 * @see book_form_node_form_alter()
287
288
 */
function book_pick_book_nojs_submit($form, &$form_state) {
289
  $node = $form_state['controller']->getEntity();
290
  $node->book = $form_state['values']['book'];
291
292
293
  $form_state['rebuild'] = TRUE;
}

294
295
296
/**
 * Renders a new parent page select element when the book selection changes.
 *
297
 * This function is called via Ajax when the selected book is changed on a node
298
299
300
301
302
303
304
305
306
 * or book outline form.
 *
 * @return
 *   The rendered parent page select element.
 */
function book_form_update($form, $form_state) {
  return $form['book']['plid'];
}

Dries's avatar
Dries committed
307
/**
308
 * Gets the book menu tree for a page and returns it as a linear array.
309
 *
Dries's avatar
Dries committed
310
311
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
312
 *
313
 * @return
Dries's avatar
Dries committed
314
315
 *   A linear array of menu links in the order that the links are shown in the
 *   menu, so the previous and next pages are the elements before and after the
316
317
318
 *   element corresponding to the current node. The children of the current node
 *   (if any) will come immediately after it in the array, and links will only
 *   be fetched as deep as one level deeper than $book_link.
319
 */
Dries's avatar
Dries committed
320
function book_get_flat_menu($book_link) {
321
  $flat = &drupal_static(__FUNCTION__, array());
Dries's avatar
Dries committed
322
323

  if (!isset($flat[$book_link['mlid']])) {
324
325
    // Call bookTreeAllData() to take advantage of the menu system's caching.
    $tree = \Drupal::service('book.manager')->bookTreeAllData($book_link['menu_name'], $book_link, $book_link['depth'] + 1);
Dries's avatar
Dries committed
326
327
    $flat[$book_link['mlid']] = array();
    _book_flatten_menu($tree, $flat[$book_link['mlid']]);
Dries's avatar
   
Dries committed
328
  }
329

Dries's avatar
Dries committed
330
  return $flat[$book_link['mlid']];
Dries's avatar
   
Dries committed
331
332
}

333
/**
334
335
336
337
338
 * Recursively converts a tree of menu links to a flat array.
 *
 * @param $tree
 *   A tree of menu links in an array.
 * @param $flat
339
 *   A flat array of the menu links from $tree, passed by reference.
340
341
 *
 * @see book_get_flat_menu().
342
 */
Dries's avatar
Dries committed
343
344
345
346
347
348
349
350
function _book_flatten_menu($tree, &$flat) {
  foreach ($tree as $data) {
    if (!$data['link']['hidden']) {
      $flat[$data['link']['mlid']] = $data['link'];
      if ($data['below']) {
        _book_flatten_menu($data['below'], $flat);
      }
    }
Dries's avatar
   
Dries committed
351
  }
Dries's avatar
Dries committed
352
}
Dries's avatar
   
Dries committed
353

Dries's avatar
Dries committed
354
355
/**
 * Fetches the menu link for the previous page of the book.
356
357
358
359
360
361
362
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   A fully loaded menu link for the page before the one represented in
 *   $book_link.
Dries's avatar
Dries committed
363
364
365
366
367
 */
function book_prev($book_link) {
  // If the parent is zero, we are at the start of a book.
  if ($book_link['plid'] == 0) {
    return NULL;
Dries's avatar
   
Dries committed
368
  }
Dries's avatar
Dries committed
369
370
371
372
373
374
375
376
377
378
379
380
  $flat = book_get_flat_menu($book_link);
  // Assigning the array to $flat resets the array pointer for use with each().
  $curr = NULL;
  do {
    $prev = $curr;
    list($key, $curr) = each($flat);
  } while ($key && $key != $book_link['mlid']);

  if ($key == $book_link['mlid']) {
    // The previous page in the book may be a child of the previous visible link.
    if ($prev['depth'] == $book_link['depth'] && $prev['has_children']) {
      // The subtree will have only one link at the top level - get its data.
381
      $tree = \Drupal::service('book.manager')->bookMenuSubtreeData($prev);
382
      $data = array_shift($tree);
Dries's avatar
Dries committed
383
384
385
386
      // The link of interest is the last child - iterate to find the deepest one.
      while ($data['below']) {
        $data = end($data['below']);
      }
387

Dries's avatar
Dries committed
388
389
390
391
392
      return $data['link'];
    }
    else {
      return $prev;
    }
Dries's avatar
   
Dries committed
393
394
395
  }
}

396
/**
Dries's avatar
Dries committed
397
 * Fetches the menu link for the next page of the book.
398
399
400
401
402
403
404
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   A fully loaded menu link for the page after the one represented in
 *   $book_link.
405
 */
Dries's avatar
Dries committed
406
407
408
409
function book_next($book_link) {
  $flat = book_get_flat_menu($book_link);
  // Assigning the array to $flat resets the array pointer for use with each().
  do {
410
    list($key, ) = each($flat);
411
412
413
  }
  while ($key && $key != $book_link['mlid']);

Dries's avatar
Dries committed
414
415
  if ($key == $book_link['mlid']) {
    return current($flat);
Dries's avatar
   
Dries committed
416
  }
Dries's avatar
Dries committed
417
}
Dries's avatar
   
Dries committed
418

Dries's avatar
Dries committed
419
/**
420
421
422
423
424
425
426
 * Formats the menu links for the child pages of the current page.
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   HTML for the links to the child pages of the current page.
Dries's avatar
Dries committed
427
428
429
 */
function book_children($book_link) {
  $flat = book_get_flat_menu($book_link);
430

Dries's avatar
Dries committed
431
432
433
434
435
436
  $children = array();

  if ($book_link['has_children']) {
    // Walk through the array until we find the current page.
    do {
      $link = array_shift($flat);
437
438
    }
    while ($link && ($link['mlid'] != $book_link['mlid']));
Dries's avatar
Dries committed
439
440
441
442
443
    // Continue though the array and collect the links whose parent is this page.
    while (($link = array_shift($flat)) && $link['plid'] == $book_link['mlid']) {
      $data['link'] = $link;
      $data['below'] = '';
      $children[] = $data;
Dries's avatar
   
Dries committed
444
445
    }
  }
446

447
  if ($children) {
448
    $elements = \Drupal::service('book.manager')->bookTreeOutput($children);
449
450
451
    return drupal_render($elements);
  }
  return '';
Dries's avatar
   
Dries committed
452
453
}

454
/**
455
 * Implements hook_node_load().
456
 */
457
function book_node_load($nodes) {
458
  $result = db_query("SELECT * FROM {book} b INNER JOIN {menu_links} ml ON b.mlid = ml.mlid WHERE b.nid IN (:nids)", array(':nids' =>  array_keys($nodes)), array('fetch' => PDO::FETCH_ASSOC));
459
460
461
462
463
  foreach ($result as $record) {
    $nodes[$record['nid']]->book = $record;
    $nodes[$record['nid']]->book['href'] = $record['link_path'];
    $nodes[$record['nid']]->book['title'] = $record['link_title'];
    $nodes[$record['nid']]->book['options'] = unserialize($record['options']);
464
465
  }
}
466

467
/**
468
 * Implements hook_node_view().
469
 */
470
function book_node_view(EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
471
  if ($view_mode == 'full') {
472
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
473
      $book_navigation = array( '#theme' => 'book_navigation', '#book_link' => $node->book);
474
      $node->content['book_navigation'] = array(
475
        '#markup' => drupal_render($book_navigation),
476
        '#weight' => 100,
477
478
479
480
481
        '#attached' => array(
          'css' => array(
            drupal_get_path('module', 'book') . '/css/book.theme.css',
          ),
        ),
482
483
484
      );
    }
  }
485
486
}

487
/**
488
 * Implements hook_node_presave().
489
 */
490
function book_node_presave(EntityInterface $node) {
491
  // Always save a revision for non-administrators.
492
  if (!empty($node->book['bid']) && !\Drupal::currentUser()->hasPermission('administer nodes')) {
493
    $node->setNewRevision();
494
495
  }
  // Make sure a new node gets a new menu link.
496
  if ($node->isNew()) {
497
498
499
    $node->book['mlid'] = NULL;
  }
}
500

501
/**
502
 * Implements hook_node_insert().
503
 */
504
function book_node_insert(EntityInterface $node) {
505
  $book_manager = \Drupal::service('book.manager');
506
507
508
  if (!empty($node->book['bid'])) {
    if ($node->book['bid'] == 'new') {
      // New nodes that are their own book.
509
      $node->book['bid'] = $node->id();
510
    }
511
    $node->book['nid'] = $node->id();
512
513
    $node->book['menu_name'] = $book_manager->createMenuName($node->book['bid']);
    $book_manager->updateOutline($node);
514
515
  }
}
516

517
/**
518
 * Implements hook_node_update().
519
 */
520
function book_node_update(EntityInterface $node) {
521
  $book_manager = \Drupal::service('book.manager');
522
523
524
  if (!empty($node->book['bid'])) {
    if ($node->book['bid'] == 'new') {
      // New nodes that are their own book.
525
      $node->book['bid'] = $node->id();
526
    }
527
    $node->book['nid'] = $node->id();
528
529
    $node->book['menu_name'] = $book_manager->createMenuName($node->book['bid']);
    $book_manager->updateOutline($node);
530
531
  }
}
532

533
/**
534
 * Implements hook_node_predelete().
535
 */
536
function book_node_predelete(EntityInterface $node) {
537
  if (!empty($node->book['bid'])) {
538
    if ($node->id() == $node->book['bid']) {
539
      // Handle deletion of a top-level post.
540
541
542
543
      $result = db_query("SELECT b.nid FROM {menu_links} ml INNER JOIN {book} b on b.mlid = ml.mlid WHERE ml.plid = :plid", array(
        ':plid' => $node->book['mlid']
      ));
      foreach ($result as $child) {
544
545
        $child_node = node_load($child->id());
        $child_node->book['bid'] = $child_node->id();
546
        \Drupal::service('book.manager')->updateOutline($child_node);
Dries's avatar
Dries committed
547
      }
548
    }
549
    // @todo - remove this call when we change the schema.
550
    menu_link_delete($node->book['mlid']);
551
552
553
    db_delete('book')
      ->condition('mlid', $node->book['mlid'])
      ->execute();
554
    drupal_static_reset('book_get_books');
555
556
557
558
  }
}

/**
559
 * Implements hook_node_prepare_form().
560
 */
561
function book_node_prepare_form(NodeInterface $node, $form_display, $operation, array &$form_state) {
562
  // Get BookManager service
563
  $book_manager = \Drupal::service('book.manager');
564

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

570
    $query = \Drupal::request()->query;
571
    if ($node->isNew() && !is_null($query->get('parent')) && is_numeric($query->get('parent'))) {
572
      // Handle "Add child page" links:
573
      $parent = book_link_load($query->get('parent'));
574
575
576
577
578

      if ($parent && $parent['access']) {
        $node->book['bid'] = $parent['bid'];
        $node->book['plid'] = $parent['mlid'];
        $node->book['menu_name'] = $parent['menu_name'];
579
      }
580
581
    }
    // Set defaults.
582
583
    $node_ref = !$node->isNew() ? $node->id() : 'new';
    $node->book += $book_manager->getLinkDefaults($node_ref);
584
585
586
587
588
589
590
591
  }
  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'])) {
592
    $node->book['parent_depth_limit'] = $book_manager->getParentDepthLimit($node->book);
Dries's avatar
Dries committed
593
594
595
596
  }
}

/**
597
 * Implements hook_form_FORM_ID_alter() for node_delete_confirm().
598
599
600
601
 *
 * Alters the confirm form for a single node deletion.
 *
 * @see node_delete_confirm()
Dries's avatar
Dries committed
602
603
604
605
606
607
 */
function book_form_node_delete_confirm_alter(&$form, $form_state) {
  $node = node_load($form['nid']['#value']);

  if (isset($node->book) && $node->book['has_children']) {
    $form['book_warning'] = array(
608
      '#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>',
Dries's avatar
Dries committed
609
610
      '#weight' => -10,
    );
Dries's avatar
   
Dries committed
611
  }
Dries's avatar
   
Dries committed
612
}
Dries's avatar
   
Dries committed
613

614
/**
615
 * Implements hook_preprocess_HOOK() for block templates.
616
617
 */
function book_preprocess_block(&$variables) {
618
  if ($variables['configuration']['module'] == 'book') {
619
    $variables['attributes']['role'] = 'navigation';
620
621
622
  }
}

623
/**
624
625
626
 * Prepares variables for book listing block templates.
 *
 * Default template: book-all-books-block.html.twig.
627
 *
628
629
630
 * 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).
631
 *
632
633
 * @param array $variables
 *   An associative array containing the following key:
634
635
 *   - book_menus: An associative array containing renderable menu links for all
 *     book menus.
636
637
638
639
640
641
642
643
644
645
 */
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'][$index] = $elements[$index];
  }
}

Dries's avatar
Dries committed
646
/**
647
648
649
 * Prepares variables for book navigation templates.
 *
 * Default template: book-navigation.html.twig.
Dries's avatar
Dries committed
650
 *
651
652
 * @param array $variables
 *   An associative array containing the following key:
653
654
 *   - book_link: An associative array of book link properties.
 *     Properties used: bid, link_title, depth, plid, mlid.
655
 */
656
657
658
659
660
661
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'] = check_plain($book_link['link_title']);
662
  $variables['book_url'] = 'node/' . $book_link['bid'];
663
664
  $variables['current_depth'] = $book_link['depth'];
  $variables['tree'] = '';
665

Dries's avatar
Dries committed
666
  if ($book_link['mlid']) {
667
    $variables['tree'] = book_children($book_link);
Dries's avatar
   
Dries committed
668

669
670
    $build = array();

Dries's avatar
Dries committed
671
    if ($prev = book_prev($book_link)) {
672
      $prev_href = url($prev['link_path']);
673
674
675
676
      $build['#attached']['drupal_add_html_head_link'][][] = array(
        'rel' => 'prev',
        'href' => $prev_href,
      );
677
678
      $variables['prev_url'] = $prev_href;
      $variables['prev_title'] = check_plain($prev['title']);
Dries's avatar
   
Dries committed
679
    }
680

Dries's avatar
Dries committed
681
    if ($book_link['plid'] && $parent = book_link_load($book_link['plid'])) {
682
      $parent_href = url($parent['link_path']);
683
684
685
686
      $build['#attached']['drupal_add_html_head_link'][][] = array(
        'rel' => 'up',
        'href' => $parent_href,
      );
687
688
      $variables['parent_url'] = $parent_href;
      $variables['parent_title'] = check_plain($parent['title']);
Dries's avatar
   
Dries committed
689
    }
690

Dries's avatar
Dries committed
691
    if ($next = book_next($book_link)) {
692
      $next_href = url($next['link_path']);
693
694
695
696
      $build['#attached']['drupal_add_html_head_link'][][] = array(
        'rel' => 'next',
        'href' => $next_href,
      );
697
698
      $variables['next_url'] = $next_href;
      $variables['next_title'] = check_plain($next['title']);
Dries's avatar
   
Dries committed
699
    }
700
  }
Dries's avatar
   
Dries committed
701

702
703
704
705
  if (!empty($build)) {
    drupal_render($build);
  }

706
707
708
709
710
711
712
713
714
715
716
  $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] = '';
717
    }
Dries's avatar
   
Dries committed
718
  }
Dries's avatar
   
Dries committed
719
}
Dries's avatar
 
Dries committed
720

721
/**
722
 * Prepares variables for book export templates.
723
 *
724
 * Default template: book-export-html.html.twig.
725
 *
726
727
728
729
730
 * @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.
731
732
 */
function template_preprocess_book_export_html(&$variables) {
733
  global $base_url;
734
  $language_interface = language(Language::TYPE_INTERFACE);
735
736
737

  $variables['title'] = check_plain($variables['title']);
  $variables['base_url'] = $base_url;
738
  $variables['language'] = $language_interface;
739
  $variables['language_rtl'] = ($language_interface->direction == Language::DIRECTION_RTL);
740
  $variables['head'] = drupal_get_html_head();
741
742

  // HTML element attributes.
743
  $attributes = array();
744
  $attributes['lang'] = $language_interface->id;
745
746
  $attributes['dir'] = $language_interface->direction ? 'rtl' : 'ltr';
  $variables['html_attributes'] = new Attribute($attributes);
747
748
}

749
/**
750
751
752
 * Prepares variables for single node export templates.
 *
 * Default template: book-node-export-html.html.twig.
Dries's avatar
Dries committed
753
 *
754
755
 * @param array $variables
 *   An associative array containing the following keys:
756
757
758
 *   - node: The node that will be output.
 *   - children: All the rendered child nodes within the current node. Defaults
 *     to an empty string.
759
 */
760
761
function template_preprocess_book_node_export_html(&$variables) {
  $variables['depth'] = $variables['node']->book['depth'];
762
  $variables['title'] = check_plain($variables['node']->label());
763
  $variables['content'] = $variables['node']->rendered;
764
765
}

766
/**
767
 * Determines if a given node type is in the list of types allowed for books.
768
769
770
771
772
773
 *
 * @param string $type
 *   A node type.
 *
 * @return bool
 *   A Boolean TRUE if the node type can be included in books; otherwise, FALSE.
774
 */
Dries's avatar
Dries committed
775
function book_type_is_allowed($type) {
776
  return in_array($type, \Drupal::config('book.settings')->get('allowed_types'));
777
778
}

Dries's avatar
Dries committed
779
/**
780
 * Implements hook_node_type_update().
Dries's avatar
Dries committed
781
 *
782
783
 * Updates book.settings configuration object if the machine-readable name of a
 * node type is changed.
Dries's avatar
Dries committed
784
 */
785
function book_node_type_update(NodeTypeInterface $type) {
786
  if ($type->getOriginalId() != $type->id()) {
787
    $config = \Drupal::config('book.settings');
788
    // Update the list of node types that are allowed to be added to books.
789
    $allowed_types = $config->get('allowed_types');
790
    $old_key = array_search($type->getOriginalId(), $allowed_types);
791

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

    // Update the setting for the "Add child page" link.
801
    if ($config->get('child_type') == $type->getOriginalId()) {
802
      $config->set('child_type', $type->id());
803
    }
804
    $config->save();
Dries's avatar
Dries committed
805
  }
Dries's avatar
   
Dries committed
806
807
}

Dries's avatar
Dries committed
808
/**
809
810
 * Gets a book menu link by its menu link ID.
 *
Dries's avatar
Dries committed
811
812
813
 * Like menu_link_load(), but adds additional data from the {book} table.
 *
 * Do not call when loading a node, since this function may call node_load().
814
815
816
817
818
819
 *
 * @param $mlid
 *   The menu link ID of the menu item.
 *
 * @return
 *   A menu link, with the link translated for rendering and data added from the
820
 *   {book} table. FALSE if there is an error.
Dries's avatar
Dries committed
821
822
 */
function book_link_load($mlid) {
823
  return entity_load('menu_link', $mlid);
Dries's avatar
Dries committed
824
825
}

826
827
828
829
830
831
/**
 * Implements hook_library_info().
 */
function book_library_info() {
  $libraries['drupal.book'] = array(
    'title' => 'Book',
832
    'version' => \Drupal::VERSION,
833
834
835
836
837
838
839
840
841
842
843
844
    'js' => array(
      drupal_get_path('module', 'book') . '/book.js' => array(),
    ),
    'dependencies' => array(
      array('system', 'jquery'),
      array('system', 'drupal'),
      array('system', 'drupal.form'),
    ),
  );

  return $libraries;
}