annotate core/modules/book/src/BookManager.php @ 9:1fc0ff908d1f

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