comparison core/modules/book/src/BookManager.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children af1871eacc83
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\book;
4
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Cache\Cache;
7 use Drupal\Core\Entity\EntityManagerInterface;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\Render\RendererInterface;
10 use Drupal\Core\Session\AccountInterface;
11 use Drupal\Core\StringTranslation\TranslationInterface;
12 use Drupal\Core\StringTranslation\StringTranslationTrait;
13 use Drupal\Core\Config\ConfigFactoryInterface;
14 use Drupal\Core\Template\Attribute;
15 use Drupal\node\NodeInterface;
16
17 /**
18 * Defines a book manager.
19 */
20 class BookManager implements BookManagerInterface {
21 use StringTranslationTrait;
22
23 /**
24 * Defines the maximum supported depth of the book tree.
25 */
26 const BOOK_MAX_DEPTH = 9;
27
28 /**
29 * Entity manager Service Object.
30 *
31 * @var \Drupal\Core\Entity\EntityManagerInterface
32 */
33 protected $entityManager;
34
35 /**
36 * Config Factory Service Object.
37 *
38 * @var \Drupal\Core\Config\ConfigFactoryInterface
39 */
40 protected $configFactory;
41
42 /**
43 * Books Array.
44 *
45 * @var array
46 */
47 protected $books;
48
49 /**
50 * Book outline storage.
51 *
52 * @var \Drupal\book\BookOutlineStorageInterface
53 */
54 protected $bookOutlineStorage;
55
56 /**
57 * Stores flattened book trees.
58 *
59 * @var array
60 */
61 protected $bookTreeFlattened;
62
63 /**
64 * The renderer.
65 *
66 * @var \Drupal\Core\Render\RendererInterface
67 */
68 protected $renderer;
69
70 /**
71 * Constructs a BookManager object.
72 */
73 public function __construct(EntityManagerInterface $entity_manager, TranslationInterface $translation, ConfigFactoryInterface $config_factory, BookOutlineStorageInterface $book_outline_storage, RendererInterface $renderer) {
74 $this->entityManager = $entity_manager;
75 $this->stringTranslation = $translation;
76 $this->configFactory = $config_factory;
77 $this->bookOutlineStorage = $book_outline_storage;
78 $this->renderer = $renderer;
79 }
80
81 /**
82 * {@inheritdoc}
83 */
84 public function getAllBooks() {
85 if (!isset($this->books)) {
86 $this->loadBooks();
87 }
88 return $this->books;
89 }
90
91 /**
92 * Loads Books Array.
93 */
94 protected function loadBooks() {
95 $this->books = [];
96 $nids = $this->bookOutlineStorage->getBooks();
97
98 if ($nids) {
99 $book_links = $this->bookOutlineStorage->loadMultiple($nids);
100 $nodes = $this->entityManager->getStorage('node')->loadMultiple($nids);
101 // @todo: Sort by weight and translated title.
102
103 // @todo: use route name for links, not system path.
104 foreach ($book_links as $link) {
105 $nid = $link['nid'];
106 if (isset($nodes[$nid]) && $nodes[$nid]->status) {
107 $link['url'] = $nodes[$nid]->urlInfo();
108 $link['title'] = $nodes[$nid]->label();
109 $link['type'] = $nodes[$nid]->bundle();
110 $this->books[$link['bid']] = $link;
111 }
112 }
113 }
114 }
115
116 /**
117 * {@inheritdoc}
118 */
119 public function getLinkDefaults($nid) {
120 return [
121 'original_bid' => 0,
122 'nid' => $nid,
123 'bid' => 0,
124 'pid' => 0,
125 'has_children' => 0,
126 'weight' => 0,
127 'options' => [],
128 ];
129 }
130
131 /**
132 * {@inheritdoc}
133 */
134 public function getParentDepthLimit(array $book_link) {
135 return static::BOOK_MAX_DEPTH - 1 - (($book_link['bid'] && $book_link['has_children']) ? $this->findChildrenRelativeDepth($book_link) : 0);
136 }
137
138 /**
139 * Determine the relative depth of the children of a given book link.
140 *
141 * @param array $book_link
142 * The book link.
143 *
144 * @return int
145 * The difference between the max depth in the book tree and the depth of
146 * the passed book link.
147 */
148 protected function findChildrenRelativeDepth(array $book_link) {
149 $max_depth = $this->bookOutlineStorage->getChildRelativeDepth($book_link, static::BOOK_MAX_DEPTH);
150 return ($max_depth > $book_link['depth']) ? $max_depth - $book_link['depth'] : 0;
151 }
152
153 /**
154 * {@inheritdoc}
155 */
156 public function addFormElements(array $form, FormStateInterface $form_state, NodeInterface $node, AccountInterface $account, $collapsed = TRUE) {
157 // If the form is being processed during the Ajax callback of our book bid
158 // dropdown, then $form_state will hold the value that was selected.
159 if ($form_state->hasValue('book')) {
160 $node->book = $form_state->getValue('book');
161 }
162 $form['book'] = [
163 '#type' => 'details',
164 '#title' => $this->t('Book outline'),
165 '#weight' => 10,
166 '#open' => !$collapsed,
167 '#group' => 'advanced',
168 '#attributes' => [
169 'class' => ['book-outline-form'],
170 ],
171 '#attached' => [
172 'library' => ['book/drupal.book'],
173 ],
174 '#tree' => TRUE,
175 ];
176 foreach (['nid', 'has_children', 'original_bid', 'parent_depth_limit'] as $key) {
177 $form['book'][$key] = [
178 '#type' => 'value',
179 '#value' => $node->book[$key],
180 ];
181 }
182
183 $form['book']['pid'] = $this->addParentSelectFormElements($node->book);
184
185 // @see \Drupal\book\Form\BookAdminEditForm::bookAdminTableTree(). The
186 // weight may be larger than 15.
187 $form['book']['weight'] = [
188 '#type' => 'weight',
189 '#title' => $this->t('Weight'),
190 '#default_value' => $node->book['weight'],
191 '#delta' => max(15, abs($node->book['weight'])),
192 '#weight' => 5,
193 '#description' => $this->t('Pages at a given level are ordered first by weight and then by title.'),
194 ];
195 $options = [];
196 $nid = !$node->isNew() ? $node->id() : 'new';
197 if ($node->id() && ($nid == $node->book['original_bid']) && ($node->book['parent_depth_limit'] == 0)) {
198 // This is the top level node in a maximum depth book and thus cannot be
199 // moved.
200 $options[$node->id()] = $node->label();
201 }
202 else {
203 foreach ($this->getAllBooks() as $book) {
204 $options[$book['nid']] = $book['title'];
205 }
206 }
207
208 if ($account->hasPermission('create new books') && ($nid == 'new' || ($nid != $node->book['original_bid']))) {
209 // The node can become a new book, if it is not one already.
210 $options = [$nid => $this->t('- Create a new book -')] + $options;
211 }
212 if (!$node->book['bid']) {
213 // The node is not currently in the hierarchy.
214 $options = [0 => $this->t('- None -')] + $options;
215 }
216
217 // Add a drop-down to select the destination book.
218 $form['book']['bid'] = [
219 '#type' => 'select',
220 '#title' => $this->t('Book'),
221 '#default_value' => $node->book['bid'],
222 '#options' => $options,
223 '#access' => (bool) $options,
224 '#description' => $this->t('Your page will be a part of the selected book.'),
225 '#weight' => -5,
226 '#attributes' => ['class' => ['book-title-select']],
227 '#ajax' => [
228 'callback' => 'book_form_update',
229 'wrapper' => 'edit-book-plid-wrapper',
230 'effect' => 'fade',
231 'speed' => 'fast',
232 ],
233 ];
234 return $form;
235 }
236
237 /**
238 * {@inheritdoc}
239 */
240 public function checkNodeIsRemovable(NodeInterface $node) {
241 return (!empty($node->book['bid']) && (($node->book['bid'] != $node->id()) || !$node->book['has_children']));
242 }
243
244 /**
245 * {@inheritdoc}
246 */
247 public function updateOutline(NodeInterface $node) {
248 if (empty($node->book['bid'])) {
249 return FALSE;
250 }
251
252 if (!empty($node->book['bid'])) {
253 if ($node->book['bid'] == 'new') {
254 // New nodes that are their own book.
255 $node->book['bid'] = $node->id();
256 }
257 elseif (!isset($node->book['original_bid'])) {
258 $node->book['original_bid'] = $node->book['bid'];
259 }
260 }
261
262 // Ensure we create a new book link if either the node itself is new, or the
263 // bid was selected the first time, so that the original_bid is still empty.
264 $new = empty($node->book['nid']) || empty($node->book['original_bid']);
265
266 $node->book['nid'] = $node->id();
267
268 // Create a new book from a node.
269 if ($node->book['bid'] == $node->id()) {
270 $node->book['pid'] = 0;
271 }
272 elseif ($node->book['pid'] < 0) {
273 // -1 is the default value in BookManager::addParentSelectFormElements().
274 // The node save should have set the bid equal to the node ID, but
275 // handle it here if it did not.
276 $node->book['pid'] = $node->book['bid'];
277 }
278
279 // Prevent changes to the book outline if the node being saved is not the
280 // default revision.
281 $updated = FALSE;
282 if (!$new) {
283 $original = $this->loadBookLink($node->id(), FALSE);
284 if ($node->book['bid'] != $original['bid'] || $node->book['pid'] != $original['pid'] || $node->book['weight'] != $original['weight']) {
285 $updated = TRUE;
286 }
287 }
288 if (($new || $updated) && !$node->isDefaultRevision()) {
289 return FALSE;
290 }
291
292 return $this->saveBookLink($node->book, $new);
293 }
294
295 /**
296 * {@inheritdoc}
297 */
298 public function getBookParents(array $item, array $parent = []) {
299 $book = [];
300 if ($item['pid'] == 0) {
301 $book['p1'] = $item['nid'];
302 for ($i = 2; $i <= static::BOOK_MAX_DEPTH; $i++) {
303 $parent_property = "p$i";
304 $book[$parent_property] = 0;
305 }
306 $book['depth'] = 1;
307 }
308 else {
309 $i = 1;
310 $book['depth'] = $parent['depth'] + 1;
311 while ($i < $book['depth']) {
312 $p = 'p' . $i++;
313 $book[$p] = $parent[$p];
314 }
315 $p = 'p' . $i++;
316 // The parent (p1 - p9) corresponding to the depth always equals the nid.
317 $book[$p] = $item['nid'];
318 while ($i <= static::BOOK_MAX_DEPTH) {
319 $p = 'p' . $i++;
320 $book[$p] = 0;
321 }
322 }
323 return $book;
324 }
325
326 /**
327 * Builds the parent selection form element for the node form or outline tab.
328 *
329 * This function is also called when generating a new set of options during
330 * the Ajax callback, so an array is returned that can be used to replace an
331 * existing form element.
332 *
333 * @param array $book_link
334 * A fully loaded book link that is part of the book hierarchy.
335 *
336 * @return array
337 * A parent selection form element.
338 */
339 protected function addParentSelectFormElements(array $book_link) {
340 $config = $this->configFactory->get('book.settings');
341 if ($config->get('override_parent_selector')) {
342 return [];
343 }
344 // Offer a message or a drop-down to choose a different parent page.
345 $form = [
346 '#type' => 'hidden',
347 '#value' => -1,
348 '#prefix' => '<div id="edit-book-plid-wrapper">',
349 '#suffix' => '</div>',
350 ];
351
352 if ($book_link['nid'] === $book_link['bid']) {
353 // This is a book - at the top level.
354 if ($book_link['original_bid'] === $book_link['bid']) {
355 $form['#prefix'] .= '<em>' . $this->t('This is the top-level page in this book.') . '</em>';
356 }
357 else {
358 $form['#prefix'] .= '<em>' . $this->t('This will be the top-level page in this book.') . '</em>';
359 }
360 }
361 elseif (!$book_link['bid']) {
362 $form['#prefix'] .= '<em>' . $this->t('No book selected.') . '</em>';
363 }
364 else {
365 $form = [
366 '#type' => 'select',
367 '#title' => $this->t('Parent item'),
368 '#default_value' => $book_link['pid'],
369 '#description' => $this->t('The parent page in the book. The maximum depth for a book and all child pages is @maxdepth. Some pages in the selected book may not be available as parents if selecting them would exceed this limit.', ['@maxdepth' => static::BOOK_MAX_DEPTH]),
370 '#options' => $this->getTableOfContents($book_link['bid'], $book_link['parent_depth_limit'], [$book_link['nid']]),
371 '#attributes' => ['class' => ['book-title-select']],
372 '#prefix' => '<div id="edit-book-plid-wrapper">',
373 '#suffix' => '</div>',
374 ];
375 }
376 $this->renderer->addCacheableDependency($form, $config);
377
378 return $form;
379 }
380
381 /**
382 * Recursively processes and formats book links for getTableOfContents().
383 *
384 * This helper function recursively modifies the table of contents array for
385 * each item in the book tree, ignoring items in the exclude array or at a
386 * depth greater than the limit. Truncates titles over thirty characters and
387 * appends an indentation string incremented by depth.
388 *
389 * @param array $tree
390 * The data structure of the book's outline tree. Includes hidden links.
391 * @param string $indent
392 * A string appended to each node title. Increments by '--' per depth
393 * level.
394 * @param array $toc
395 * Reference to the table of contents array. This is modified in place, so
396 * the function does not have a return value.
397 * @param array $exclude
398 * Optional array of Node ID values. Any link whose node ID is in this
399 * array will be excluded (along with its children).
400 * @param int $depth_limit
401 * Any link deeper than this value will be excluded (along with its
402 * children).
403 */
404 protected function recurseTableOfContents(array $tree, $indent, array &$toc, array $exclude, $depth_limit) {
405 $nids = [];
406 foreach ($tree as $data) {
407 if ($data['link']['depth'] > $depth_limit) {
408 // Don't iterate through any links on this level.
409 return;
410 }
411 if (!in_array($data['link']['nid'], $exclude)) {
412 $nids[] = $data['link']['nid'];
413 }
414 }
415
416 $nodes = $this->entityManager->getStorage('node')->loadMultiple($nids);
417
418 foreach ($tree as $data) {
419 $nid = $data['link']['nid'];
420 // Check for excluded or missing node.
421 if (empty($nodes[$nid])) {
422 continue;
423 }
424 $toc[$nid] = $indent . ' ' . Unicode::truncate($nodes[$nid]->label(), 30, TRUE, TRUE);
425 if ($data['below']) {
426 $this->recurseTableOfContents($data['below'], $indent . '--', $toc, $exclude, $depth_limit);
427 }
428 }
429 }
430
431 /**
432 * {@inheritdoc}
433 */
434 public function getTableOfContents($bid, $depth_limit, array $exclude = []) {
435 $tree = $this->bookTreeAllData($bid);
436 $toc = [];
437 $this->recurseTableOfContents($tree, '', $toc, $exclude, $depth_limit);
438
439 return $toc;
440 }
441
442 /**
443 * {@inheritdoc}
444 */
445 public function deleteFromBook($nid) {
446 $original = $this->loadBookLink($nid, FALSE);
447 $this->bookOutlineStorage->delete($nid);
448
449 if ($nid == $original['bid']) {
450 // Handle deletion of a top-level post.
451 $result = $this->bookOutlineStorage->loadBookChildren($nid);
452 $children = $this->entityManager->getStorage('node')->loadMultiple(array_keys($result));
453 foreach ($children as $child) {
454 $child->book['bid'] = $child->id();
455 $this->updateOutline($child);
456 }
457 }
458 $this->updateOriginalParent($original);
459 $this->books = NULL;
460 Cache::invalidateTags(['bid:' . $original['bid']]);
461 }
462
463 /**
464 * {@inheritdoc}
465 */
466 public function bookTreeAllData($bid, $link = NULL, $max_depth = NULL) {
467 $tree = &drupal_static(__METHOD__, []);
468 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
469
470 // Use $nid as a flag for whether the data being loaded is for the whole
471 // tree.
472 $nid = isset($link['nid']) ? $link['nid'] : 0;
473 // Generate a cache ID (cid) specific for this $bid, $link, $language, and
474 // depth.
475 $cid = 'book-links:' . $bid . ':all:' . $nid . ':' . $language_interface->getId() . ':' . (int) $max_depth;
476
477 if (!isset($tree[$cid])) {
478 // If the tree data was not in the static cache, build $tree_parameters.
479 $tree_parameters = [
480 'min_depth' => 1,
481 'max_depth' => $max_depth,
482 ];
483 if ($nid) {
484 $active_trail = $this->getActiveTrailIds($bid, $link);
485 $tree_parameters['expanded'] = $active_trail;
486 $tree_parameters['active_trail'] = $active_trail;
487 $tree_parameters['active_trail'][] = $nid;
488 }
489
490 // Build the tree using the parameters; the resulting tree will be cached.
491 $tree[$cid] = $this->bookTreeBuild($bid, $tree_parameters);
492 }
493
494 return $tree[$cid];
495 }
496
497 /**
498 * {@inheritdoc}
499 */
500 public function getActiveTrailIds($bid, $link) {
501 // The tree is for a single item, so we need to match the values in its
502 // p columns and 0 (the top level) with the plid values of other links.
503 $active_trail = [0];
504 for ($i = 1; $i < static::BOOK_MAX_DEPTH; $i++) {
505 if (!empty($link["p$i"])) {
506 $active_trail[] = $link["p$i"];
507 }
508 }
509 return $active_trail;
510 }
511
512 /**
513 * {@inheritdoc}
514 */
515 public function bookTreeOutput(array $tree) {
516 $items = $this->buildItems($tree);
517
518 $build = [];
519
520 if ($items) {
521 // Make sure drupal_render() does not re-order the links.
522 $build['#sorted'] = TRUE;
523 // Get the book id from the last link.
524 $item = end($items);
525 // Add the theme wrapper for outer markup.
526 // Allow menu-specific theme overrides.
527 $build['#theme'] = 'book_tree__book_toc_' . $item['original_link']['bid'];
528 $build['#items'] = $items;
529 // Set cache tag.
530 $build['#cache']['tags'][] = 'config:system.book.' . $item['original_link']['bid'];
531 }
532
533 return $build;
534 }
535
536 /**
537 * Builds the #items property for a book tree's renderable array.
538 *
539 * Helper function for ::bookTreeOutput().
540 *
541 * @param array $tree
542 * A data structure representing the tree.
543 *
544 * @return array
545 * The value to use for the #items property of a renderable menu.
546 */
547 protected function buildItems(array $tree) {
548 $items = [];
549
550 foreach ($tree as $data) {
551 $element = [];
552
553 // Generally we only deal with visible links, but just in case.
554 if (!$data['link']['access']) {
555 continue;
556 }
557 // Set a class for the <li> tag. Since $data['below'] may contain local
558 // tasks, only set 'expanded' to true if the link also has children within
559 // the current book.
560 $element['is_expanded'] = FALSE;
561 $element['is_collapsed'] = FALSE;
562 if ($data['link']['has_children'] && $data['below']) {
563 $element['is_expanded'] = TRUE;
564 }
565 elseif ($data['link']['has_children']) {
566 $element['is_collapsed'] = TRUE;
567 }
568
569 // Set a helper variable to indicate whether the link is in the active
570 // trail.
571 $element['in_active_trail'] = FALSE;
572 if ($data['link']['in_active_trail']) {
573 $element['in_active_trail'] = TRUE;
574 }
575
576 // Allow book-specific theme overrides.
577 $element['attributes'] = new Attribute();
578 $element['title'] = $data['link']['title'];
579 $node = $this->entityManager->getStorage('node')->load($data['link']['nid']);
580 $element['url'] = $node->urlInfo();
581 $element['localized_options'] = !empty($data['link']['localized_options']) ? $data['link']['localized_options'] : [];
582 $element['localized_options']['set_active_class'] = TRUE;
583 $element['below'] = $data['below'] ? $this->buildItems($data['below']) : [];
584 $element['original_link'] = $data['link'];
585 // Index using the link's unique nid.
586 $items[$data['link']['nid']] = $element;
587 }
588
589 return $items;
590 }
591
592 /**
593 * Builds a book tree, translates links, and checks access.
594 *
595 * @param int $bid
596 * The Book ID to find links for.
597 * @param array $parameters
598 * (optional) An associative array of build parameters. Possible keys:
599 * - expanded: An array of parent link IDs to return only book links that
600 * are children of one of the parent link IDs in this list. If empty,
601 * the whole outline is built, unless 'only_active_trail' is TRUE.
602 * - active_trail: An array of node IDs, representing the currently active
603 * book link.
604 * - only_active_trail: Whether to only return links that are in the active
605 * trail. This option is ignored if 'expanded' is non-empty.
606 * - min_depth: The minimum depth of book links in the resulting tree.
607 * Defaults to 1, which is to build the whole tree for the book.
608 * - max_depth: The maximum depth of book links in the resulting tree.
609 * - conditions: An associative array of custom database select query
610 * condition key/value pairs; see
611 * \Drupal\book\BookOutlineStorage::getBookMenuTree() for the actual
612 * query.
613 *
614 * @return array
615 * A fully built book tree.
616 */
617 protected function bookTreeBuild($bid, array $parameters = []) {
618 // Build the book tree.
619 $data = $this->doBookTreeBuild($bid, $parameters);
620 // Check access for the current user to each item in the tree.
621 $this->bookTreeCheckAccess($data['tree'], $data['node_links']);
622 return $data['tree'];
623 }
624
625 /**
626 * Builds a book tree.
627 *
628 * This function may be used build the data for a menu tree only, for example
629 * to further massage the data manually before further processing happens.
630 * _menu_tree_check_access() needs to be invoked afterwards.
631 *
632 * @param int $bid
633 * The book ID to find links for.
634 * @param array $parameters
635 * (optional) An associative array of build parameters. Possible keys:
636 * - expanded: An array of parent link IDs to return only book links that
637 * are children of one of the parent link IDs in this list. If empty,
638 * the whole outline is built, unless 'only_active_trail' is TRUE.
639 * - active_trail: An array of node IDs, representing the currently active
640 * book link.
641 * - only_active_trail: Whether to only return links that are in the active
642 * trail. This option is ignored if 'expanded' is non-empty.
643 * - min_depth: The minimum depth of book links in the resulting tree.
644 * Defaults to 1, which is to build the whole tree for the book.
645 * - max_depth: The maximum depth of book links in the resulting tree.
646 * - conditions: An associative array of custom database select query
647 * condition key/value pairs; see
648 * \Drupal\book\BookOutlineStorage::getBookMenuTree() for the actual
649 * query.
650 *
651 * @return array
652 * An array with links representing the tree structure of the book.
653 *
654 * @see \Drupal\book\BookOutlineStorageInterface::getBookMenuTree()
655 */
656 protected function doBookTreeBuild($bid, array $parameters = []) {
657 // Static cache of already built menu trees.
658 $trees = &drupal_static(__METHOD__, []);
659 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
660
661 // Build the cache id; sort parents to prevent duplicate storage and remove
662 // default parameter values.
663 if (isset($parameters['expanded'])) {
664 sort($parameters['expanded']);
665 }
666 $tree_cid = 'book-links:' . $bid . ':tree-data:' . $language_interface->getId() . ':' . hash('sha256', serialize($parameters));
667
668 // If we do not have this tree in the static cache, check {cache_data}.
669 if (!isset($trees[$tree_cid])) {
670 $cache = \Drupal::cache('data')->get($tree_cid);
671 if ($cache && $cache->data) {
672 $trees[$tree_cid] = $cache->data;
673 }
674 }
675
676 if (!isset($trees[$tree_cid])) {
677 $min_depth = (isset($parameters['min_depth']) ? $parameters['min_depth'] : 1);
678 $result = $this->bookOutlineStorage->getBookMenuTree($bid, $parameters, $min_depth, static::BOOK_MAX_DEPTH);
679
680 // Build an ordered array of links using the query result object.
681 $links = [];
682 foreach ($result as $link) {
683 $link = (array) $link;
684 $links[$link['nid']] = $link;
685 }
686 $active_trail = (isset($parameters['active_trail']) ? $parameters['active_trail'] : []);
687 $data['tree'] = $this->buildBookOutlineData($links, $active_trail, $min_depth);
688 $data['node_links'] = [];
689 $this->bookTreeCollectNodeLinks($data['tree'], $data['node_links']);
690
691 // Cache the data, if it is not already in the cache.
692 \Drupal::cache('data')->set($tree_cid, $data, Cache::PERMANENT, ['bid:' . $bid]);
693 $trees[$tree_cid] = $data;
694 }
695
696 return $trees[$tree_cid];
697 }
698
699 /**
700 * {@inheritdoc}
701 */
702 public function bookTreeCollectNodeLinks(&$tree, &$node_links) {
703 // All book links are nodes.
704 // @todo clean this up.
705 foreach ($tree as $key => $v) {
706 $nid = $v['link']['nid'];
707 $node_links[$nid][$tree[$key]['link']['nid']] = &$tree[$key]['link'];
708 $tree[$key]['link']['access'] = FALSE;
709 if ($tree[$key]['below']) {
710 $this->bookTreeCollectNodeLinks($tree[$key]['below'], $node_links);
711 }
712 }
713 }
714
715 /**
716 * {@inheritdoc}
717 */
718 public function bookTreeGetFlat(array $book_link) {
719 if (!isset($this->bookTreeFlattened[$book_link['nid']])) {
720 // Call $this->bookTreeAllData() to take advantage of caching.
721 $tree = $this->bookTreeAllData($book_link['bid'], $book_link, $book_link['depth'] + 1);
722 $this->bookTreeFlattened[$book_link['nid']] = [];
723 $this->flatBookTree($tree, $this->bookTreeFlattened[$book_link['nid']]);
724 }
725
726 return $this->bookTreeFlattened[$book_link['nid']];
727 }
728
729 /**
730 * Recursively converts a tree of menu links to a flat array.
731 *
732 * @param array $tree
733 * A tree of menu links in an array.
734 * @param array $flat
735 * A flat array of the menu links from $tree, passed by reference.
736 *
737 * @see static::bookTreeGetFlat()
738 */
739 protected function flatBookTree(array $tree, array &$flat) {
740 foreach ($tree as $data) {
741 $flat[$data['link']['nid']] = $data['link'];
742 if ($data['below']) {
743 $this->flatBookTree($data['below'], $flat);
744 }
745 }
746 }
747
748 /**
749 * {@inheritdoc}
750 */
751 public function loadBookLink($nid, $translate = TRUE) {
752 $links = $this->loadBookLinks([$nid], $translate);
753 return isset($links[$nid]) ? $links[$nid] : FALSE;
754 }
755
756 /**
757 * {@inheritdoc}
758 */
759 public function loadBookLinks($nids, $translate = TRUE) {
760 $result = $this->bookOutlineStorage->loadMultiple($nids, $translate);
761 $links = [];
762 foreach ($result as $link) {
763 if ($translate) {
764 $this->bookLinkTranslate($link);
765 }
766 $links[$link['nid']] = $link;
767 }
768
769 return $links;
770 }
771
772 /**
773 * {@inheritdoc}
774 */
775 public function saveBookLink(array $link, $new) {
776 // Keep track of Book IDs for cache clear.
777 $affected_bids[$link['bid']] = $link['bid'];
778 $link += $this->getLinkDefaults($link['nid']);
779 if ($new) {
780 // Insert new.
781 $parents = $this->getBookParents($link, (array) $this->loadBookLink($link['pid'], FALSE));
782 $this->bookOutlineStorage->insert($link, $parents);
783
784 // Update the has_children status of the parent.
785 $this->updateParent($link);
786 }
787 else {
788 $original = $this->loadBookLink($link['nid'], FALSE);
789 // Using the Book ID as the key keeps this unique.
790 $affected_bids[$original['bid']] = $original['bid'];
791 // Handle links that are moving.
792 if ($link['bid'] != $original['bid'] || $link['pid'] != $original['pid']) {
793 // Update the bid for this page and all children.
794 if ($link['pid'] == 0) {
795 $link['depth'] = 1;
796 $parent = [];
797 }
798 // In case the form did not specify a proper PID we use the BID as new
799 // parent.
800 elseif (($parent_link = $this->loadBookLink($link['pid'], FALSE)) && $parent_link['bid'] != $link['bid']) {
801 $link['pid'] = $link['bid'];
802 $parent = $this->loadBookLink($link['pid'], FALSE);
803 $link['depth'] = $parent['depth'] + 1;
804 }
805 else {
806 $parent = $this->loadBookLink($link['pid'], FALSE);
807 $link['depth'] = $parent['depth'] + 1;
808 }
809 $this->setParents($link, $parent);
810 $this->moveChildren($link, $original);
811
812 // Update the has_children status of the original parent.
813 $this->updateOriginalParent($original);
814 // Update the has_children status of the new parent.
815 $this->updateParent($link);
816 }
817 // Update the weight and pid.
818 $this->bookOutlineStorage->update($link['nid'], [
819 'weight' => $link['weight'],
820 'pid' => $link['pid'],
821 'bid' => $link['bid'],
822 ]);
823 }
824 $cache_tags = [];
825 foreach ($affected_bids as $bid) {
826 $cache_tags[] = 'bid:' . $bid;
827 }
828 Cache::invalidateTags($cache_tags);
829 return $link;
830 }
831
832 /**
833 * Moves children from the original parent to the updated link.
834 *
835 * @param array $link
836 * The link being saved.
837 * @param array $original
838 * The original parent of $link.
839 */
840 protected function moveChildren(array $link, array $original) {
841 $p = 'p1';
842 $expressions = [];
843 for ($i = 1; $i <= $link['depth']; $p = 'p' . ++$i) {
844 $expressions[] = [$p, ":p_$i", [":p_$i" => $link[$p]]];
845 }
846 $j = $original['depth'] + 1;
847 while ($i <= static::BOOK_MAX_DEPTH && $j <= static::BOOK_MAX_DEPTH) {
848 $expressions[] = ['p' . $i++, 'p' . $j++, []];
849 }
850 while ($i <= static::BOOK_MAX_DEPTH) {
851 $expressions[] = ['p' . $i++, 0, []];
852 }
853
854 $shift = $link['depth'] - $original['depth'];
855 if ($shift > 0) {
856 // The order of expressions must be reversed so the new values don't
857 // overwrite the old ones before they can be used because "Single-table
858 // UPDATE assignments are generally evaluated from left to right"
859 // @see http://dev.mysql.com/doc/refman/5.0/en/update.html
860 $expressions = array_reverse($expressions);
861 }
862
863 $this->bookOutlineStorage->updateMovedChildren($link['bid'], $original, $expressions, $shift);
864 }
865
866 /**
867 * Sets the has_children flag of the parent of the node.
868 *
869 * This method is mostly called when a book link is moved/created etc. So we
870 * want to update the has_children flag of the new parent book link.
871 *
872 * @param array $link
873 * The book link, data reflecting its new position, whose new parent we want
874 * to update.
875 *
876 * @return bool
877 * TRUE if the update was successful (either there is no parent to update,
878 * or the parent was updated successfully), FALSE on failure.
879 */
880 protected function updateParent(array $link) {
881 if ($link['pid'] == 0) {
882 // Nothing to update.
883 return TRUE;
884 }
885 return $this->bookOutlineStorage->update($link['pid'], ['has_children' => 1]);
886 }
887
888 /**
889 * Updates the has_children flag of the parent of the original node.
890 *
891 * This method is called when a book link is moved or deleted. So we want to
892 * update the has_children flag of the parent node.
893 *
894 * @param array $original
895 * The original link whose parent we want to update.
896 *
897 * @return bool
898 * TRUE if the update was successful (either there was no original parent to
899 * update, or the original parent was updated successfully), FALSE on
900 * failure.
901 */
902 protected function updateOriginalParent(array $original) {
903 if ($original['pid'] == 0) {
904 // There were no parents of this link. Nothing to update.
905 return TRUE;
906 }
907 // Check if $original had at least one child.
908 $original_number_of_children = $this->bookOutlineStorage->countOriginalLinkChildren($original);
909
910 $parent_has_children = ((bool) $original_number_of_children) ? 1 : 0;
911 // Update the parent. If the original link did not have children, then the
912 // parent now does not have children. If the original had children, then the
913 // the parent has children now (still).
914 return $this->bookOutlineStorage->update($original['pid'], ['has_children' => $parent_has_children]);
915 }
916
917 /**
918 * Sets the p1 through p9 properties for a book link being saved.
919 *
920 * @param array $link
921 * The book link to update, passed by reference.
922 * @param array $parent
923 * The parent values to set.
924 */
925 protected function setParents(array &$link, array $parent) {
926 $i = 1;
927 while ($i < $link['depth']) {
928 $p = 'p' . $i++;
929 $link[$p] = $parent[$p];
930 }
931 $p = 'p' . $i++;
932 // The parent (p1 - p9) corresponding to the depth always equals the nid.
933 $link[$p] = $link['nid'];
934 while ($i <= static::BOOK_MAX_DEPTH) {
935 $p = 'p' . $i++;
936 $link[$p] = 0;
937 }
938 }
939
940 /**
941 * {@inheritdoc}
942 */
943 public function bookTreeCheckAccess(&$tree, $node_links = []) {
944 if ($node_links) {
945 // @todo Extract that into its own method.
946 $nids = array_keys($node_links);
947
948 // @todo This should be actually filtering on the desired node status
949 // field language and just fall back to the default language.
950 $nids = \Drupal::entityQuery('node')
951 ->condition('nid', $nids, 'IN')
952 ->condition('status', 1)
953 ->execute();
954
955 foreach ($nids as $nid) {
956 foreach ($node_links[$nid] as $mlid => $link) {
957 $node_links[$nid][$mlid]['access'] = TRUE;
958 }
959 }
960 }
961 $this->doBookTreeCheckAccess($tree);
962 }
963
964 /**
965 * Sorts the menu tree and recursively checks access for each item.
966 *
967 * @param array $tree
968 * The book tree to operate on.
969 */
970 protected function doBookTreeCheckAccess(&$tree) {
971 $new_tree = [];
972 foreach ($tree as $key => $v) {
973 $item = &$tree[$key]['link'];
974 $this->bookLinkTranslate($item);
975 if ($item['access']) {
976 if ($tree[$key]['below']) {
977 $this->doBookTreeCheckAccess($tree[$key]['below']);
978 }
979 // The weights are made a uniform 5 digits by adding 50000 as an offset.
980 // After calling $this->bookLinkTranslate(), $item['title'] has the
981 // translated title. Adding the nid to the end of the index insures that
982 // it is unique.
983 $new_tree[(50000 + $item['weight']) . ' ' . $item['title'] . ' ' . $item['nid']] = $tree[$key];
984 }
985 }
986 // Sort siblings in the tree based on the weights and localized titles.
987 ksort($new_tree);
988 $tree = $new_tree;
989 }
990
991 /**
992 * {@inheritdoc}
993 */
994 public function bookLinkTranslate(&$link) {
995 $node = NULL;
996 // Access will already be set in the tree functions.
997 if (!isset($link['access'])) {
998 $node = $this->entityManager->getStorage('node')->load($link['nid']);
999 $link['access'] = $node && $node->access('view');
1000 }
1001 // For performance, don't localize a link the user can't access.
1002 if ($link['access']) {
1003 // @todo - load the nodes en-mass rather than individually.
1004 if (!$node) {
1005 $node = $this->entityManager->getStorage('node')
1006 ->load($link['nid']);
1007 }
1008 // The node label will be the value for the current user's language.
1009 $link['title'] = $node->label();
1010 $link['options'] = [];
1011 }
1012 return $link;
1013 }
1014
1015 /**
1016 * Sorts and returns the built data representing a book tree.
1017 *
1018 * @param array $links
1019 * A flat array of book links that are part of the book. Each array element
1020 * is an associative array of information about the book link, containing
1021 * the fields from the {book} table. This array must be ordered depth-first.
1022 * @param array $parents
1023 * An array of the node ID values that are in the path from the current
1024 * page to the root of the book tree.
1025 * @param int $depth
1026 * The minimum depth to include in the returned book tree.
1027 *
1028 * @return array
1029 * An array of book links in the form of a tree. Each item in the tree is an
1030 * associative array containing:
1031 * - link: The book link item from $links, with additional element
1032 * 'in_active_trail' (TRUE if the link ID was in $parents).
1033 * - below: An array containing the sub-tree of this item, where each
1034 * element is a tree item array with 'link' and 'below' elements. This
1035 * array will be empty if the book link has no items in its sub-tree
1036 * having a depth greater than or equal to $depth.
1037 */
1038 protected function buildBookOutlineData(array $links, array $parents = [], $depth = 1) {
1039 // Reverse the array so we can use the more efficient array_pop() function.
1040 $links = array_reverse($links);
1041 return $this->buildBookOutlineRecursive($links, $parents, $depth);
1042 }
1043
1044 /**
1045 * Builds the data representing a book tree.
1046 *
1047 * The function is a bit complex because the rendering of a link depends on
1048 * the next book link.
1049 *
1050 * @param array $links
1051 * A flat array of book links that are part of the book. Each array element
1052 * is an associative array of information about the book link, containing
1053 * the fields from the {book} table. This array must be ordered depth-first.
1054 * @param array $parents
1055 * An array of the node ID values that are in the path from the current page
1056 * to the root of the book tree.
1057 * @param int $depth
1058 * The minimum depth to include in the returned book tree.
1059 *
1060 * @return array
1061 * Book tree.
1062 */
1063 protected function buildBookOutlineRecursive(&$links, $parents, $depth) {
1064 $tree = [];
1065 while ($item = array_pop($links)) {
1066 // We need to determine if we're on the path to root so we can later build
1067 // the correct active trail.
1068 $item['in_active_trail'] = in_array($item['nid'], $parents);
1069 // Add the current link to the tree.
1070 $tree[$item['nid']] = [
1071 'link' => $item,
1072 'below' => [],
1073 ];
1074 // Look ahead to the next link, but leave it on the array so it's
1075 // available to other recursive function calls if we return or build a
1076 // sub-tree.
1077 $next = end($links);
1078 // Check whether the next link is the first in a new sub-tree.
1079 if ($next && $next['depth'] > $depth) {
1080 // Recursively call buildBookOutlineRecursive to build the sub-tree.
1081 $tree[$item['nid']]['below'] = $this->buildBookOutlineRecursive($links, $parents, $next['depth']);
1082 // Fetch next link after filling the sub-tree.
1083 $next = end($links);
1084 }
1085 // Determine if we should exit the loop and $request = return.
1086 if (!$next || $next['depth'] < $depth) {
1087 break;
1088 }
1089 }
1090 return $tree;
1091 }
1092
1093 /**
1094 * {@inheritdoc}
1095 */
1096 public function bookSubtreeData($link) {
1097 $tree = &drupal_static(__METHOD__, []);
1098
1099 // Generate a cache ID (cid) specific for this $link.
1100 $cid = 'book-links:subtree-cid:' . $link['nid'];
1101
1102 if (!isset($tree[$cid])) {
1103 $tree_cid_cache = \Drupal::cache('data')->get($cid);
1104
1105 if ($tree_cid_cache && $tree_cid_cache->data) {
1106 // If the cache entry exists, it will just be the cid for the actual
1107 // data. This avoids duplication of large amounts of data.
1108 $cache = \Drupal::cache('data')->get($tree_cid_cache->data);
1109
1110 if ($cache && isset($cache->data)) {
1111 $data = $cache->data;
1112 }
1113 }
1114
1115 // If the subtree data was not in the cache, $data will be NULL.
1116 if (!isset($data)) {
1117 $result = $this->bookOutlineStorage->getBookSubtree($link, static::BOOK_MAX_DEPTH);
1118 $links = [];
1119 foreach ($result as $item) {
1120 $links[] = $item;
1121 }
1122 $data['tree'] = $this->buildBookOutlineData($links, [], $link['depth']);
1123 $data['node_links'] = [];
1124 $this->bookTreeCollectNodeLinks($data['tree'], $data['node_links']);
1125 // Compute the real cid for book subtree data.
1126 $tree_cid = 'book-links:subtree-data:' . hash('sha256', serialize($data));
1127 // Cache the data, if it is not already in the cache.
1128
1129 if (!\Drupal::cache('data')->get($tree_cid)) {
1130 \Drupal::cache('data')->set($tree_cid, $data, Cache::PERMANENT, ['bid:' . $link['bid']]);
1131 }
1132 // Cache the cid of the (shared) data using the book and item-specific
1133 // cid.
1134 \Drupal::cache('data')->set($cid, $tree_cid, Cache::PERMANENT, ['bid:' . $link['bid']]);
1135 }
1136 // Check access for the current user to each item in the tree.
1137 $this->bookTreeCheckAccess($data['tree'], $data['node_links']);
1138 $tree[$cid] = $data['tree'];
1139 }
1140
1141 return $tree[$cid];
1142 }
1143
1144 }