Newer
Older
Dries Buytaert
committed
* Allows users to create and organize related content in an outline.
use Drupal\book\BookManager;
use Drupal\book\BookManagerInterface;
use Drupal\Component\Utility\String;
Angie Byron
committed
use Drupal\Core\Entity\EntityInterface;
Dries Buytaert
committed
use Drupal\Core\Form\FormStateInterface;
Angie Byron
committed
use Drupal\Core\Render\Element;
Angie Byron
committed
use Drupal\Core\Routing\RouteMatchInterface;
Dries Buytaert
committed
use Drupal\node\NodeInterface;
use Drupal\node\NodeTypeInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Template\Attribute;
Angie Byron
committed
/**
Dries Buytaert
committed
* Implements hook_help().
Angie Byron
committed
*/
Angie Byron
committed
function book_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.book':
Angie Byron
committed
$output = '<h3>' . t('About') . '</h3>';
Jennifer Hodgdon
committed
$output .= '<p>' . t('The Book module is used for creating structured, multi-page content, such as site resource guides, manuals, and wikis. It allows you to create content that has chapters, sections, subsections, or any similarly-tiered structure. For more information, see the <a href="!book">online documentation for the Book module</a>.', array('!book' => 'https://drupal.org/documentation/modules/book')) . '</p>';
Angie Byron
committed
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Adding and managing book content') . '</dt>';
Jennifer Hodgdon
committed
$output .= '<dd>' . t('You can assign separate permissions for <em>creating new books</em> as well as <em>creating</em>, <em>editing</em> and <em>deleting</em> book content. Users with the <em>Administer book outlines</em> permission can add <em>any</em> type of content to a book by selecting the appropriate book outline while editing the content. They can also view a list of all books, and edit and rearrange section titles on the <a href="!admin-book">Book administration page</a>.', array('!admin-book' => \Drupal::url('book.admin'))) . '</dd>';
Angie Byron
committed
$output .= '<dt>' . t('Book navigation') . '</dt>';
Jennifer Hodgdon
committed
$output .= '<dd>' . t("Book pages have a default book-specific navigation block. This navigation block contains links that lead to the previous and next pages in the book, and to the level above the current page in the book's structure. This block can be enabled on the <a href='!admin-block'>Blocks administration page</a>. For book pages to show up in the book navigation, they must be added to a book outline.", array('!admin-block' => \Drupal::url('block.admin_display'))) . '</dd>';
Angie Byron
committed
$output .= '<dt>' . t('Collaboration') . '</dt>';
Dries Buytaert
committed
$output .= '<dd>' . t('Books can be created collaboratively, as they allow users with appropriate permissions to add pages into existing books, and add those pages to a custom table of contents.') . '</dd>';
Angie Byron
committed
$output .= '<dt>' . t('Printing books') . '</dt>';
$output .= '<dd>' . t("Users with the <em>View printer-friendly books</em> permission can select the <em>printer-friendly version</em> link visible at the bottom of a book page's content to generate a printer-friendly display of the page and all of its subsections.") . '</dd>';
Angie Byron
committed
$output .= '</dl>';
return $output;
case 'book.admin':
Angie Byron
committed
return '<p>' . t('The book module offers a means to organize a collection of related content pages, collectively known as a book. When viewed, this content automatically displays links to adjacent book pages, providing a simple navigation system for creating and reviewing structured content.') . '</p>';
case 'book.outline':
Jennifer Hodgdon
committed
return '<p>' . t('The outline feature allows you to include pages in the <a href="!book">Book hierarchy</a>, as well as move them within the hierarchy or to <a href="!book-admin">reorder an entire book</a>.', array('!book' => \Drupal::url('book.render'), '!book-admin' => \Drupal::url('book.admin'))) . '</p>';
Angie Byron
committed
}
}
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_theme().
Dries Buytaert
committed
*/
function book_theme() {
return array(
'book_navigation' => array(
'variables' => array('book_link' => NULL),
'template' => 'book-navigation',
Dries Buytaert
committed
),
Dries Buytaert
committed
'book_tree' => array(
'render element' => 'tree',
'template' => 'book-tree',
),
'book_link' => array(
'render element' => 'element',
),
Dries Buytaert
committed
'book_export_html' => array(
'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
'template' => 'book-export-html',
Dries Buytaert
committed
),
'book_admin_table' => array(
'render element' => 'form',
'file' => 'book.admin.inc',
Dries Buytaert
committed
),
'render element' => 'book_menus',
'template' => 'book-all-books-block',
),
'book_node_export_html' => array(
'variables' => array('node' => NULL, 'children' => NULL),
'template' => 'book-node-export-html',
Dries Buytaert
committed
);
}
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_permission().
Dries Buytaert
committed
*/
function book_permission() {
return array(
Angie Byron
committed
'administer book outlines' => array(
'title' => t('Administer book outlines'),
),
'create new books' => array(
'title' => t('Create new books'),
),
'add content to books' => array(
'title' => t('Add content and child pages to books'),
Angie Byron
committed
),
'access printer-friendly version' => array(
'title' => t('View printer-friendly books'),
Angie Byron
committed
'description' => t('View a book page and all of its sub-pages as a single document for ease of printing. Can be performance heavy.'),
),
);
Angie Byron
committed
/**
* Implements hook_entity_type_build().
Angie Byron
committed
*/
function book_entity_type_build(array &$entity_types) {
/** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
$entity_types['node']
Alex Pott
committed
->setFormClass('book_outline', 'Drupal\book\Form\BookOutlineForm')
->setLinkTemplate('book-outline-form', 'book.outline')
->setLinkTemplate('book-remove-form', 'book.remove');
Angie Byron
committed
}
Dries Buytaert
committed
* Implements hook_node_links_alter().
Dries Buytaert
committed
function book_node_links_alter(array &$node_links, NodeInterface $node, array &$context) {
if ($context['view_mode'] != 'rss') {
$account = \Drupal::currentUser();
if (isset($node->book['depth'])) {
if ($context['view_mode'] == 'full' && node_is_page($node)) {
$child_type = \Drupal::config('book.settings')->get('child_type');
$access_control_handler = \Drupal::entityManager()->getAccessControlHandler('node');
if (($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines')) && $access_control_handler->createAccess($child_type) && $node->isPublished() && $node->book['depth'] < BookManager::BOOK_MAX_DEPTH) {
Dries Buytaert
committed
$links['book_add_child'] = array(
'title' => t('Add child page'),
'href' => 'node/add/' . $child_type,
'query' => array('parent' => $node->id()),
Dries Buytaert
committed
);
}
if ($account->hasPermission('access printer-friendly version')) {
$links['book_printer'] = array(
'title' => t('Printer-friendly version'),
'href' => 'book/export/html/' . $node->id(),
'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
);
}
}
Dries Buytaert
committed
if (!empty($links)) {
$node_links['book'] = array(
'#theme' => 'links__node__book',
'#links' => $links,
'#attributes' => array('class' => array('links', 'inline')),
);
}
* Implements hook_form_BASE_FORM_ID_alter() for node_form().
* Adds the book form element to the node form.
Dries Buytaert
committed
*
* @see book_pick_book_nojs_submit()
Dries Buytaert
committed
function book_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$node = $form_state['controller']->getEntity();
$account = \Drupal::currentUser();
$access = $account->hasPermission('administer book outlines');
Dries Buytaert
committed
if (!$access) {
if ($account->hasPermission('add content to books') && ((!empty($node->book['bid']) && !$node->isNew()) || book_type_is_allowed($node->getType()))) {
Dries Buytaert
committed
// Already in the book hierarchy, or this node type is allowed.
$access = TRUE;
Dries Buytaert
committed
}
Dries Buytaert
committed
if ($access) {
$collapsed = !($node->isNew() && !empty($node->book['pid']));
$form = \Drupal::service('book.manager')->addFormElements($form, $form_state, $node, $account, $collapsed);
Dries Buytaert
committed
// Since the "Book" dropdown can't trigger a form submission when
// JavaScript is disabled, add a submit button to do that. book.admin.css hides
Dries Buytaert
committed
// this button when JavaScript is enabled.
$form['book']['pick-book'] = array(
'#type' => 'submit',
'#value' => t('Change book (update list of parents)'),
'#submit' => array('book_pick_book_nojs_submit'),
'#weight' => 20,
'#attached' => array(
Alex Pott
committed
'css' => array(drupal_get_path('module', 'book') . '/css/book.admin.css'),
Dries Buytaert
committed
);
catch
committed
$form['#entity_builders'][] = 'book_node_builder';
Steven Wittens
committed
}
Dries Buytaert
committed
catch
committed
/**
* Entity form builder to add the book information to the node.
*
* @todo: Remove this in favor of an entity field.
*/
Dries Buytaert
committed
function book_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
Alex Pott
committed
$entity->book = $form_state->getValue('book');
catch
committed
// Always save a revision for non-administrators.
if (!empty($entity->book['bid']) && !\Drupal::currentUser()->hasPermission('administer nodes')) {
$entity->setNewRevision();
}
catch
committed
}
Dries Buytaert
committed
/**
* Form submission handler for node_form().
Dries Buytaert
committed
*
* This handler is run when JavaScript is disabled. It triggers the form to
* rebuild so that the "Parent item" options are changed to reflect the newly
* selected book. When JavaScript is enabled, the submit button that triggers
* this handler is hidden, and the "Book" dropdown directly triggers the
* book_form_update() Ajax callback instead.
Dries Buytaert
committed
*
* @see book_form_update()
* @see book_form_node_form_alter()
Dries Buytaert
committed
*/
Dries Buytaert
committed
function book_pick_book_nojs_submit($form, FormStateInterface $form_state) {
$node = $form_state['controller']->getEntity();
Alex Pott
committed
$node->book = $form_state->getValue('book');
Dries Buytaert
committed
$form_state['rebuild'] = TRUE;
}
Dries Buytaert
committed
/**
* Renders a new parent page select element when the book selection changes.
*
* This function is called via Ajax when the selected book is changed on a node
Dries Buytaert
committed
* or book outline form.
*
* @return
* The rendered parent page select element.
*/
Alex Pott
committed
function book_form_update($form, FormStateInterface $form_state) {
return $form['book']['pid'];
Dries Buytaert
committed
}
Dries Buytaert
committed
/**
* Implements hook_ENTITY_TYPE_load() for node entities.
Dries Buytaert
committed
*/
Alex Pott
committed
function book_node_load($nodes) {
/** @var \Drupal\book\BookManagerInterface $book_manager */
$book_manager = \Drupal::service('book.manager');
$links = $book_manager->loadBookLinks(array_keys($nodes), FALSE);
foreach ($links as $record) {
$nodes[$record['nid']]->book = $record;
$nodes[$record['nid']]->book['link_path'] = 'node/' . $record['nid'];
$nodes[$record['nid']]->book['link_title'] = $nodes[$record['nid']]->label();
Dries Buytaert
committed
}
}
Dries Buytaert
committed
/**
* Implements hook_ENTITY_TYPE_view() for node entities.
Dries Buytaert
committed
*/
function book_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
if ($view_mode == 'full') {
if (!empty($node->book['bid']) && empty($node->in_preview)) {
Alex Pott
committed
$book_navigation = array( '#theme' => 'book_navigation', '#book_link' => $node->book);
$build['book_navigation'] = array(
Alex Pott
committed
'#markup' => drupal_render($book_navigation),
Dries Buytaert
committed
'#weight' => 100,
'#attached' => array(
'css' => array(
drupal_get_path('module', 'book') . '/css/book.theme.css',
),
),
Dries Buytaert
committed
);
}
}
}
Dries Buytaert
committed
/**
* Implements hook_ENTITY_TYPE_presave() for node entities.
Dries Buytaert
committed
*/
Angie Byron
committed
function book_node_presave(EntityInterface $node) {
Dries Buytaert
committed
// Make sure a new node gets a new menu link.
if ($node->isNew()) {
$node->book['nid'] = NULL;
Dries Buytaert
committed
}
}
Dries Buytaert
committed
/**
* Implements hook_ENTITY_TYPE_insert() for node entities.
Dries Buytaert
committed
*/
Angie Byron
committed
function book_node_insert(EntityInterface $node) {
/** @var \Drupal\book\BookManagerInterface $book_manager */
$book_manager = \Drupal::service('book.manager');
$book_manager->updateOutline($node);
Dries Buytaert
committed
}
Dries Buytaert
committed
/**
* Implements hook_ENTITY_TYPE_update() for node entities.
Dries Buytaert
committed
*/
Angie Byron
committed
function book_node_update(EntityInterface $node) {
/** @var \Drupal\book\BookManagerInterface $book_manager */
$book_manager = \Drupal::service('book.manager');
$book_manager->updateOutline($node);
Dries Buytaert
committed
}
Dries Buytaert
committed
/**
* Implements hook_ENTITY_TYPE_predelete() for node entities.
Dries Buytaert
committed
*/
Angie Byron
committed
function book_node_predelete(EntityInterface $node) {
Dries Buytaert
committed
if (!empty($node->book['bid'])) {
/** @var \Drupal\book\BookManagerInterface $book_manager */
$book_manager = \Drupal::service('book.manager');
$book_manager->deleteFromBook($node->book['nid']);
Dries Buytaert
committed
}
}
/**
* Implements hook_node_prepare_form().
Dries Buytaert
committed
*/
Dries Buytaert
committed
function book_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
/** @var \Drupal\book\BookManagerInterface $book_manager */
$book_manager = \Drupal::service('book.manager');
Angie Byron
committed
Dries Buytaert
committed
// Prepare defaults for the add/edit form.
$account = \Drupal::currentUser();
if (empty($node->book) && ($account->hasPermission('add content to books') || $account->hasPermission('administer book outlines'))) {
Dries Buytaert
committed
$node->book = array();
$query = \Drupal::request()->query;
if ($node->isNew() && !is_null($query->get('parent')) && is_numeric($query->get('parent'))) {
Dries Buytaert
committed
// Handle "Add child page" links:
$parent = $book_manager->loadBookLink($query->get('parent'), TRUE);
Dries Buytaert
committed
if ($parent && $parent['access']) {
$node->book['bid'] = $parent['bid'];
$node->book['pid'] = $parent['nid'];
Gábor Hojtsy
committed
}
Dries Buytaert
committed
}
// Set defaults.
Angie Byron
committed
$node_ref = !$node->isNew() ? $node->id() : 'new';
$node->book += $book_manager->getLinkDefaults($node_ref);
Dries Buytaert
committed
}
else {
if (isset($node->book['bid']) && !isset($node->book['original_bid'])) {
$node->book['original_bid'] = $node->book['bid'];
}
}
// Find the depth limit for the parent select.
if (isset($node->book['bid']) && !isset($node->book['parent_depth_limit'])) {
Angie Byron
committed
$node->book['parent_depth_limit'] = $book_manager->getParentDepthLimit($node->book);
* Implements hook_form_FORM_ID_alter() for node_delete_confirm().
*
* Alters the confirm form for a single node deletion.
*
* @see node_delete_confirm()
Alex Pott
committed
function book_form_node_delete_confirm_alter(&$form, FormStateInterface $form_state) {
$node = node_load($form['nid']['#value']);
if (isset($node->book) && $node->book['has_children']) {
$form['book_warning'] = array(
Angie Byron
committed
'#markup' => '<p>' . t('%title is part of a book outline, and has associated child pages. If you proceed with deletion, the child pages will be relocated automatically.', array('%title' => $node->label())) . '</p>',
Dries Buytaert
committed
/**
Alex Pott
committed
* Prepares variables for book listing block templates.
*
* Default template: book-all-books-block.html.twig.
Dries Buytaert
committed
*
* All non-renderable elements are removed so that the template has full access
* to the structured data but can also simply iterate over all elements and
* render them (as in the default template).
Dries Buytaert
committed
*
Jennifer Hodgdon
committed
* @param array $variables
* An associative array containing the following key:
Alex Pott
committed
* - book_menus: An associative array containing renderable menu links for all
* book menus.
Dries Buytaert
committed
*/
function template_preprocess_book_all_books_block(&$variables) {
// Remove all non-renderable elements.
$elements = $variables['book_menus'];
$variables['book_menus'] = array();
Angie Byron
committed
foreach (Element::children($elements) as $index) {
Angie Byron
committed
$variables['book_menus'][] = array(
'id' => $index,
'menu' => $elements[$index],
'title' => $elements[$index]['#book_title'],
);
Dries Buytaert
committed
}
}
Alex Pott
committed
* Prepares variables for book navigation templates.
*
* Default template: book-navigation.html.twig.
Jennifer Hodgdon
committed
* @param array $variables
* An associative array containing the following key:
Alex Pott
committed
* - book_link: An associative array of book link properties.
* Properties used: bid, link_title, depth, pid, nid.
Dries Buytaert
committed
*/
function template_preprocess_book_navigation(&$variables) {
$book_link = $variables['book_link'];
// Provide extra variables for themers. Not needed by default.
$variables['book_id'] = $book_link['bid'];
$variables['book_title'] = String::checkPlain($book_link['link_title']);
Alex Pott
committed
$variables['book_url'] = \Drupal::url('entity.node.canonical', array('node' => $book_link['bid']));
$variables['current_depth'] = $book_link['depth'];
$variables['tree'] = '';
/** @var \Drupal\book\BookOutline $book_outline */
$book_outline = \Drupal::service('book.outline');
if ($book_link['nid']) {
$variables['tree'] = $book_outline->childrenLinks($book_link);
catch
committed
$build = array();
if ($prev = $book_outline->prevLink($book_link)) {
Alex Pott
committed
$prev_href = \Drupal::url('entity.node.canonical', array('node' => $prev['nid']));
catch
committed
$build['#attached']['drupal_add_html_head_link'][][] = array(
'rel' => 'prev',
'href' => $prev_href,
);
$variables['prev_url'] = $prev_href;
$variables['prev_title'] = String::checkPlain($prev['title']);
/** @var \Drupal\book\BookManagerInterface $book_manager */
$book_manager = \Drupal::service('book.manager');
if ($book_link['pid'] && $parent = $book_manager->loadBookLink($book_link['pid'])) {
Alex Pott
committed
$parent_href = \Drupal::url('entity.node.canonical', array('node' => $book_link['pid']));
catch
committed
$build['#attached']['drupal_add_html_head_link'][][] = array(
'rel' => 'up',
'href' => $parent_href,
);
$variables['parent_url'] = $parent_href;
$variables['parent_title'] = String::checkPlain($parent['title']);
if ($next = $book_outline->nextLink($book_link)) {
Alex Pott
committed
$next_href = \Drupal::url('entity.node.canonical', array('node' => $next['nid']));
catch
committed
$build['#attached']['drupal_add_html_head_link'][][] = array(
'rel' => 'next',
'href' => $next_href,
);
$variables['next_url'] = $next_href;
$variables['next_title'] = String::checkPlain($next['title']);
catch
committed
if (!empty($build)) {
drupal_render($build);
}
$variables['has_links'] = FALSE;
// Link variables to filter for values and set state of the flag variable.
$links = array('prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title');
foreach ($links as $link) {
if (isset($variables[$link])) {
// Flag when there is a value.
$variables['has_links'] = TRUE;
}
else {
// Set empty to prevent notices.
$variables[$link] = '';
Dries Buytaert
committed
}
Alex Pott
committed
* Prepares variables for book export templates.
Alex Pott
committed
* Default template: book-export-html.html.twig.
Alex Pott
committed
* @param array $variables
* An associative array containing:
* - title: The title of the book.
* - contents: Output of each book page.
* - depth: The max depth of the book.
*/
function template_preprocess_book_export_html(&$variables) {
Dries Buytaert
committed
global $base_url;
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$variables['title'] = String::checkPlain($variables['title']);
$variables['base_url'] = $base_url;
$variables['language'] = $language_interface;
$variables['language_rtl'] = ($language_interface->direction == LanguageInterface::DIRECTION_RTL);
$variables['head'] = drupal_get_html_head();
Dries Buytaert
committed
// HTML element attributes.
$attributes = array();
$attributes['lang'] = $language_interface->id;
$attributes['dir'] = $language_interface->direction ? 'rtl' : 'ltr';
$variables['html_attributes'] = new Attribute($attributes);
Alex Pott
committed
* Prepares variables for single node export templates.
*
* Default template: book-node-export-html.html.twig.
Jennifer Hodgdon
committed
* @param array $variables
* An associative array containing the following keys:
Alex Pott
committed
* - node: The node that will be output.
* - children: All the rendered child nodes within the current node. Defaults
* to an empty string.
function template_preprocess_book_node_export_html(&$variables) {
$variables['depth'] = $variables['node']->book['depth'];
$variables['title'] = String::checkPlain($variables['node']->label());
Dries Buytaert
committed
$variables['content'] = $variables['node']->rendered;
Dries Buytaert
committed
/**
* Implements template_preprocess_HOOK() for theme_book_tree().
*/
function template_preprocess_book_tree(&$variables) {
$variables['tree'] = $variables['tree']['#children'];
}
/**
* Returns HTML for a book link and subtree.
*
* @param array $variables
* An associative array containing:
* - element: Structured array data for a book link.
*
* @ingroup themeable
*/
function theme_book_link(array $variables) {
$element = $variables['element'];
$sub_menu = '';
if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}
$element['#localized_options']['set_active_class'] = TRUE;
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . new Attribute($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
Dries Buytaert
committed
/**
* Determines if a given node type is in the list of types allowed for books.
Jennifer Hodgdon
committed
*
* @param string $type
* A node type.
*
* @return bool
* A Boolean TRUE if the node type can be included in books; otherwise, FALSE.
Dries Buytaert
committed
*/
function book_type_is_allowed($type) {
return in_array($type, \Drupal::config('book.settings')->get('allowed_types'));
Dries Buytaert
committed
}
* Implements hook_ENTITY_TYPE_update() for node_type entities.
Angie Byron
committed
* Updates book.settings configuration object if the machine-readable name of a
* node type is changed.
function book_node_type_update(NodeTypeInterface $type) {
if ($type->getOriginalId() != $type->id()) {
$config = \Drupal::config('book.settings');
// Update the list of node types that are allowed to be added to books.
Dries Buytaert
committed
$allowed_types = $config->get('allowed_types');
$old_key = array_search($type->getOriginalId(), $allowed_types);
Angie Byron
committed
if ($old_key !== FALSE) {
$allowed_types[$old_key] = $type->id();
Angie Byron
committed
// Ensure that the allowed_types array is sorted consistently.
// @see BookSettingsForm::submitForm()
Angie Byron
committed
sort($allowed_types);
Dries Buytaert
committed
$config->set('allowed_types', $allowed_types);
}
// Update the setting for the "Add child page" link.
if ($config->get('child_type') == $type->getOriginalId()) {
$config->set('child_type', $type->id());
Dries Buytaert
committed
$config->save();