annotate core/modules/book/src/BookManager.php @ 19:fa3358dc1485 tip

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