<?php

/**
 * @file
 * Allows users to create and organize related content in an outline.
 */

/**
 * Implements hook_help().
 */
function book_help($path, $arg) {
  switch ($path) {
    case 'admin/help#book':
      $output = '<h3>' . t('About') . '</h3>';
      $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 online handbook entry for <a href="@book">Book module</a>.', array('@book' => 'http://drupal.org/documentation/modules/book/')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Adding and managing book content') . '</dt>';
      $output .= '<dd>' . t('You can assign separate permissions for <em>creating</em>, <em>editing</em>, and <em>deleting</em> book content, as well as <em>adding content to books</em>, and <em>creating new books</em>. 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' => url('admin/content/book'))) . '</dd>';
      $output .= '<dt>' . t('Book navigation') . '</dt>';
      $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' => url('admin/structure/block'))) . '</dd>';
      $output .= '<dt>' . t('Collaboration') . '</dt>';
      $output .= '<dd>' . t('Books can be created collaboratively, as they allow users with appropriate permissions to add pages into existing books, and add those pages to a custom table of contents menu.') . '</dd>';
      $output .= '<dt>' . t('Printing books') . '</dt>';
      $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>';
      $output .= '</dl>';
      return $output;
    case 'admin/content/book':
      return '<p>' . t('The book module offers a means to organize a collection of related content pages, collectively known as a book. When viewed, this content automatically displays links to adjacent book pages, providing a simple navigation system for creating and reviewing structured content.') . '</p>';
    case 'node/%/outline':
      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' => url('book'), '@book-admin' => url('admin/content/book'))) . '</p>';
  }
}

/**
 * Implements hook_theme().
 */
function book_theme() {
  return array(
    'book_navigation' => array(
      'variables' => array('book_link' => NULL),
      'template' => 'book-navigation',
    ),
    'book_export_html' => array(
      'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
      'template' => 'book-export-html',
    ),
    'book_admin_table' => array(
      'render element' => 'form',
    ),
    'book_title_link' => array(
      'variables' => array('link' => NULL),
    ),
    'book_all_books_block' => array(
      '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',
    ),
  );
}

/**
 * Implements hook_permission().
 */
function book_permission() {
  return array(
    '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'),
    ),
    'access printer-friendly version' => array(
      'title' => t('View printer-friendly books'),
      'description' => t('View a book page and all of its sub-pages as a single document for ease of printing. Can be performance heavy.'),
    ),
  );
}

/**
 * Adds relevant book links to the node's links.
 *
 * @param $node
 *   The book page node to add links to.
 * @param $view_mode
 *   The view mode of the node.
 */
function book_node_view_link($node, $view_mode) {
  $links = array();

  if (isset($node->book['depth'])) {
    if ($view_mode == 'full' && node_is_page($node)) {
      $child_type = variable_get('book_child_type', 'book');
      if ((user_access('add content to books') || user_access('administer book outlines')) && node_access('create', $child_type) && $node->status == 1 && $node->book['depth'] < MENU_MAX_DEPTH) {
        $links['book_add_child'] = array(
          'title' => t('Add child page'),
          'href' => 'node/add/' . str_replace('_', '-', $child_type),
          'query' => array('parent' => $node->book['mlid']),
        );
      }

      if (user_access('access printer-friendly version')) {
        $links['book_printer'] = array(
          'title' => t('Printer-friendly version'),
          'href' => 'book/export/html/' . $node->nid,
          'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
        );
      }
    }
  }

  if (!empty($links)) {
    $node->content['links']['book'] = array(
      '#theme' => 'links__node__book',
      '#links' => $links,
      '#attributes' => array('class' => array('links', 'inline')),
    );
  }
}

/**
 * Implements hook_menu().
 */
function book_menu() {
  $items['admin/content/book'] = array(
    'title' => 'Books',
    'description' => "Manage your site's book outlines.",
    'page callback' => 'book_admin_overview',
    'access arguments' => array('administer book outlines'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'book.admin.inc',
  );
  $items['admin/content/book/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/content/book/settings'] = array(
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('book_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 8,
    'file' => 'book.admin.inc',
  );
  $items['admin/content/book/%node'] = array(
    'title' => 'Re-order book pages and change titles',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('book_admin_edit', 3),
    'access callback' => '_book_outline_access',
    'access arguments' => array(3),
    'type' => MENU_CALLBACK,
    'file' => 'book.admin.inc',
  );
  $items['book'] = array(
    'title' => 'Books',
    'page callback' => 'book_render',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'book.pages.inc',
  );
  $items['book/export/%/%'] = array(
    'page callback' => 'book_export',
    'page arguments' => array(2, 3),
    'access arguments' => array('access printer-friendly version'),
    'type' => MENU_CALLBACK,
    'file' => 'book.pages.inc',
  );
  $items['node/%node/outline'] = array(
    'title' => 'Outline',
    'page callback' => 'book_outline',
    'page arguments' => array(1),
    'access callback' => '_book_outline_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    'file' => 'book.pages.inc',
  );
  $items['node/%node/outline/remove'] = array(
    'title' => 'Remove from outline',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('book_remove_form', 1),
    'access callback' => '_book_outline_remove_access',
    'access arguments' => array(1),
    'file' => 'book.pages.inc',
  );

  return $items;
}

/**
 * Access callback: Determines if the outline tab is accessible.
 *
 * @param $node
 *   The node whose outline tab is to be viewed.
 */
function _book_outline_access($node) {
  return user_access('administer book outlines') && node_access('view', $node);
}

/**
 * Access callback: Determines if the user can remove nodes from the outline.
 *
 * @param $node
 *   The node to remove from the outline.
 *
 * @see book_menu()
 */
function _book_outline_remove_access($node) {
  return _book_node_is_removable($node) && _book_outline_access($node);
}

/**
 * Determines if a node can be removed from the book.
 *
 * A node can be removed from a book if it is actually in a book and it either
 * is not a top-level page or is a top-level page with no children.
 *
 * @param $node
 *   The node to remove from the outline.
 */
function _book_node_is_removable($node) {
  return (!empty($node->book['bid']) && (($node->book['bid'] != $node->nid) || !$node->book['has_children']));
}

/**
 * Implements hook_admin_paths().
 */
function book_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/outline' => TRUE,
      'node/*/outline/remove' => TRUE,
    );
    return $paths;
  }
}

/**
 * Implements hook_entity_info_alter().
 */
function book_entity_info_alter(&$info) {
  // Add the 'Print' view mode for nodes.
  $info['node']['view modes'] += array(
    'print' => array(
      'label' => t('Print'),
      'custom settings' => FALSE,
    ),
  );
}

/**
 * Implements hook_block_info().
 */
function book_block_info() {
  $block = array();
  $block['navigation']['info'] = t('Book navigation');
  $block['navigation']['cache'] = DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE;

  return $block;
}

/**
 * Implements hook_block_view().
 *
 * Displays the book table of contents in a block when the current page is a
 * single-node view of a book node.
 */
function book_block_view($delta = '') {
  $block = array();
  $current_bid = 0;
  if ($node = menu_get_object()) {
    $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
  }

  if (variable_get('book_block_mode', 'all pages') == 'all pages') {
    $block['subject'] = t('Book navigation');
    $book_menus = array();
    $pseudo_tree = array(0 => array('below' => FALSE));
    foreach (book_get_books() as $book_id => $book) {
      if ($book['bid'] == $current_bid) {
        // If the current page is a node associated with a book, the menu
        // needs to be retrieved.
        $book_menus[$book_id] = menu_tree_output(menu_tree_all_data($node->book['menu_name'], $node->book));
      }
      else {
        // Since we know we will only display a link to the top node, there
        // is no reason to run an additional menu tree query for each book.
        $book['in_active_trail'] = FALSE;
        // Check whether user can access the book link.
        $book_node = node_load($book['nid']);
        $book['access'] = node_access('view', $book_node);
        $pseudo_tree[0]['link'] = $book;
        $book_menus[$book_id] = menu_tree_output($pseudo_tree);
      }
    }
    $book_menus['#theme'] = 'book_all_books_block';
    $block['content'] = $book_menus;
  }
  elseif ($current_bid) {
    // Only display this block when the user is browsing a book.
  $select = db_select('node', 'n')
    ->fields('n', array('title'))
    ->condition('n.nid', $node->book['bid'])
    ->addTag('node_access');
    $title = $select->execute()->fetchField();
    // Only show the block if the user has view access for the top-level node.
    if ($title) {
      $tree = menu_tree_all_data($node->book['menu_name'], $node->book);
      // There should only be one element at the top level.
      $data = array_shift($tree);
      $block['subject'] = theme('book_title_link', array('link' => $data['link']));
      $block['content'] = ($data['below']) ? menu_tree_output($data['below']) : '';
    }
  }

  return $block;
}

/**
 * Implements hook_block_configure().
 */
function book_block_configure($delta = '') {
  $block = array();
  $options = array(
    'all pages' => t('Show block on all pages'),
    'book pages' => t('Show block only on book pages'),
  );
  $form['book_block_mode'] = array(
    '#type' => 'radios',
    '#title' => t('Book navigation block display'),
    '#options' => $options,
    '#default_value' => variable_get('book_block_mode', 'all pages'),
    '#description' => t("If <em>Show block on all pages</em> is selected, the block will contain the automatically generated menus for all of the site's books. If <em>Show block only on book pages</em> is selected, the block will contain only the one menu corresponding to the current page's book. In this case, if the current page is not in a book, no block will be displayed. The <em>Page specific visibility settings</em> or other visibility settings can be used in addition to selectively display this block."),
    );

  return $form;
}

/**
 * Implements hook_block_save().
 */
function book_block_save($delta = '', $edit = array()) {
  $block = array();
  variable_set('book_block_mode', $edit['book_block_mode']);
}

/**
 * Returns HTML for a link to a book title when used as a block title.
 *
 * @param $variables
 *   An associative array containing:
 *   - link: An array containing title, href and options for the link.
 *
 * @ingroup themeable
 */
function theme_book_title_link($variables) {
  $link = $variables['link'];

  $link['options']['attributes']['class'] = array('book-title');

  return l($link['title'], $link['href'], $link['options']);
}

/**
 * Returns an array of all books.
 *
 * This list may be used for generating a list of all the books, or for building
 * the options for a form select.
 *
 * @return
 *   An array of all books.
 */
function book_get_books() {
  $all_books = &drupal_static(__FUNCTION__);

  if (!isset($all_books)) {
    $all_books = array();
    $nids = db_query("SELECT DISTINCT(bid) FROM {book}")->fetchCol();

    if ($nids) {
      $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
      $query->join('node', 'n', 'b.nid = n.nid');
      $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
      $query->addField('n', 'type', 'type');
      $query->addField('n', 'title', 'title');
      $query->fields('b');
      $query->fields('ml');
      $query->condition('n.nid', $nids, 'IN');
      $query->condition('n.status', 1);
      $query->orderBy('ml.weight');
      $query->orderBy('ml.link_title');
      $query->addTag('node_access');
      $result2 = $query->execute();
      foreach ($result2 as $link) {
        $link['href'] = $link['link_path'];
        $link['options'] = unserialize($link['options']);
        $all_books[$link['bid']] = $link;
      }
    }
  }

  return $all_books;
}

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 *
 * Adds the book fieldset to the node form.
 *
 * @see book_pick_book_nojs_submit()
 */
function book_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $access = user_access('administer book outlines');
  if (!$access) {
    if (user_access('add content to books') && ((!empty($node->book['mlid']) && !empty($node->nid)) || book_type_is_allowed($node->type))) {
      // Already in the book hierarchy, or this node type is allowed.
      $access = TRUE;
    }
  }

  if ($access) {
    _book_add_form_elements($form, $form_state, $node);
    // Since the "Book" dropdown can't trigger a form submission when
    // JavaScript is disabled, add a submit button to do that. book.css hides
    // 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,
    );
  }
}

/**
 * Form submission handler for node_form().
 *
 * 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.
 *
 * @see book_form_update()
 * @see book_form_node_form_alter()
 */
function book_pick_book_nojs_submit($form, &$form_state) {
  $form_state['node']->book = $form_state['values']['book'];
  $form_state['rebuild'] = TRUE;
}

/**
 * Builds the parent selection form element for the node form or outline tab.
 *
 * This function is also called when generating a new set of options during the
 * Ajax callback, so an array is returned that can be used to replace an
 * existing form element.
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   A parent selection form element.
 */
function _book_parent_select($book_link) {
  if (variable_get('menu_override_parent_selector', FALSE)) {
    return array();
  }
  // Offer a message or a drop-down to choose a different parent page.
  $form = array(
    '#type' => 'hidden',
    '#value' => -1,
    '#prefix' => '<div id="edit-book-plid-wrapper">',
    '#suffix' => '</div>',
  );

  if ($book_link['nid'] === $book_link['bid']) {
    // This is a book - at the top level.
    if ($book_link['original_bid'] === $book_link['bid']) {
      $form['#prefix'] .= '<em>' . t('This is the top-level page in this book.') . '</em>';
    }
    else {
      $form['#prefix'] .= '<em>' . t('This will be the top-level page in this book.') . '</em>';
    }
  }
  elseif (!$book_link['bid']) {
    $form['#prefix'] .= '<em>' . t('No book selected.') . '</em>';
  }
  else {
    $form = array(
      '#type' => 'select',
      '#title' => t('Parent item'),
      '#default_value' => $book_link['plid'],
      '#description' => 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.', array('!maxdepth' => MENU_MAX_DEPTH)),
      '#options' => book_toc($book_link['bid'], $book_link['parent_depth_limit'], array($book_link['mlid'])),
      '#attributes' => array('class' => array('book-title-select')),
      '#prefix' => '<div id="edit-book-plid-wrapper">',
      '#suffix' => '</div>',
    );
  }

  return $form;
}

/**
 * Builds the common elements of the book form for the node and outline forms.
 *
 * @param $node
 *   The node whose form is being viewed.
 */
function _book_add_form_elements(&$form, &$form_state, $node) {
  // If the form is being processed during the Ajax callback of our book bid
  // dropdown, then $form_state will hold the value that was selected.
  if (isset($form_state['values']['book'])) {
    $node->book = $form_state['values']['book'];
  }

  $form['book'] = array(
    '#type' => 'fieldset',
    '#title' => t('Book outline'),
    '#weight' => 10,
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#group' => 'additional_settings',
    '#attributes' => array(
      'class' => array('book-outline-form'),
    ),
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'book') . '/book.js'),
    ),
    '#tree' => TRUE,
  );
  foreach (array('menu_name', 'mlid', 'nid', 'router_path', 'has_children', 'options', 'module', 'original_bid', 'parent_depth_limit') as $key) {
    $form['book'][$key] = array(
      '#type' => 'value',
      '#value' => $node->book[$key],
    );
  }

  $form['book']['plid'] = _book_parent_select($node->book);

  // @see _book_admin_table_tree(). The weight may be larger than 15.
  $form['book']['weight'] = array(
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#default_value' => $node->book['weight'],
    '#delta' => max(15, abs($node->book['weight'])),
    '#weight' => 5,
    '#description' => t('Pages at a given level are ordered first by weight and then by title.'),
  );
  $options = array();
  $nid = isset($node->nid) ? $node->nid : 'new';

  if (isset($node->nid) && ($nid == $node->book['original_bid']) && ($node->book['parent_depth_limit'] == 0)) {
    // This is the top level node in a maximum depth book and thus cannot be moved.
    $options[$node->nid] = $node->title;
  }
  else {
    foreach (book_get_books() as $book) {
      $options[$book['nid']] = $book['title'];
    }
  }

  if (user_access('create new books') && ($nid == 'new' || ($nid != $node->book['original_bid']))) {
    // The node can become a new book, if it is not one already.
    $options = array($nid => '<' . t('create a new book') . '>') + $options;
  }
  if (!$node->book['mlid']) {
    // The node is not currently in the hierarchy.
    $options = array(0 => '<' . t('none') . '>') + $options;
  }

  // Add a drop-down to select the destination book.
  $form['book']['bid'] = array(
    '#type' => 'select',
    '#title' => t('Book'),
    '#default_value' => $node->book['bid'],
    '#options' => $options,
    '#access' => (bool) $options,
    '#description' => t('Your page will be a part of the selected book.'),
    '#weight' => -5,
    '#attributes' => array('class' => array('book-title-select')),
    '#ajax' => array(
      'callback' => 'book_form_update',
      'wrapper' => 'edit-book-plid-wrapper',
      'effect' => 'fade',
      'speed' => 'fast',
    ),
  );
}

/**
 * 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
 * or book outline form.
 *
 * @return
 *   The rendered parent page select element.
 */
function book_form_update($form, $form_state) {
  return $form['book']['plid'];
}

/**
 * Handles additions and updates to the book outline.
 *
 * This common helper function performs all additions and updates to the book
 * outline through node addition, node editing, node deletion, or the outline
 * tab.
 *
 * @param $node
 *   The node that is being saved, added, deleted, or moved.
 *
 * @return
 *   TRUE if the menu link was saved; FALSE otherwise.
 */
function _book_update_outline($node) {
  if (empty($node->book['bid'])) {
    return FALSE;
  }
  $new = empty($node->book['mlid']);

  $node->book['link_path'] = 'node/' . $node->nid;
  $node->book['link_title'] = $node->title;
  $node->book['parent_mismatch'] = FALSE; // The normal case.

  if ($node->book['bid'] == $node->nid) {
    $node->book['plid'] = 0;
    $node->book['menu_name'] = book_menu_name($node->nid);
  }
  else {
    // Check in case the parent is not is this book; the book takes precedence.
    if (!empty($node->book['plid'])) {
      $parent = db_query("SELECT * FROM {book} WHERE mlid = :mlid", array(
        ':mlid' => $node->book['plid'],
      ))->fetchAssoc();
    }
    if (empty($node->book['plid']) || !$parent || $parent['bid'] != $node->book['bid']) {
      $node->book['plid'] = db_query("SELECT mlid FROM {book} WHERE nid = :nid", array(
        ':nid' => $node->book['bid'],
      ))->fetchField();
      $node->book['parent_mismatch'] = TRUE; // Likely when JS is disabled.
    }
  }

  if (menu_link_save($node->book)) {
    if ($new) {
      // Insert new.
      db_insert('book')
        ->fields(array(
          'nid' => $node->nid,
          'mlid' => $node->book['mlid'],
          'bid' => $node->book['bid'],
        ))
        ->execute();
      // Reset the cache of stored books.
      drupal_static_reset('book_get_books');
    }
    else {
      if ($node->book['bid'] != db_query("SELECT bid FROM {book} WHERE nid = :nid", array(
          ':nid' => $node->nid,
        ))->fetchField()) {
        // Update the bid for this page and all children.
        book_update_bid($node->book);
        // Reset the cache of stored books.
        drupal_static_reset('book_get_books');
      }
    }

    return TRUE;
  }

  // Failed to save the menu link.
  return FALSE;
}

/**
 * Updates the book ID of a page and its children when it moves to a new book.
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 */
function book_update_bid($book_link) {
  $query = db_select('menu_links');
  $query->addField('menu_links', 'mlid');
  for ($i = 1; $i <= MENU_MAX_DEPTH && $book_link["p$i"]; $i++) {
    $query->condition("p$i", $book_link["p$i"]);
  }
  $mlids = $query->execute()->fetchCol();

  if ($mlids) {
    db_update('book')
      ->fields(array('bid' => $book_link['bid']))
      ->condition('mlid', $mlids, 'IN')
      ->execute();
  }
}

/**
 * Gets the book menu tree for a page and returns it as a linear array.
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   A linear array of menu links in the order that the links are shown in the
 *   menu, so the previous and next pages are the elements before and after the
 *   element corresponding to the current node. The children of the current node
 *   (if any) will come immediately after it in the array, and links will only
 *   be fetched as deep as one level deeper than $book_link.
 */
function book_get_flat_menu($book_link) {
  $flat = &drupal_static(__FUNCTION__, array());

  if (!isset($flat[$book_link['mlid']])) {
    // Call menu_tree_all_data() to take advantage of the menu system's caching.
    $tree = menu_tree_all_data($book_link['menu_name'], $book_link, $book_link['depth'] + 1);
    $flat[$book_link['mlid']] = array();
    _book_flatten_menu($tree, $flat[$book_link['mlid']]);
  }

  return $flat[$book_link['mlid']];
}

/**
 * Recursively converts a tree of menu links to a flat array.
 *
 * @param $tree
 *   A tree of menu links in an array.
 * @param $flat
 *   A flat array of the menu links from $tree, passed by reference.
 *
 * @see book_get_flat_menu().
 */
function _book_flatten_menu($tree, &$flat) {
  foreach ($tree as $data) {
    if (!$data['link']['hidden']) {
      $flat[$data['link']['mlid']] = $data['link'];
      if ($data['below']) {
        _book_flatten_menu($data['below'], $flat);
      }
    }
  }
}

/**
 * Fetches the menu link for the previous page of the book.
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   A fully loaded menu link for the page before the one represented in
 *   $book_link.
 */
function book_prev($book_link) {
  // If the parent is zero, we are at the start of a book.
  if ($book_link['plid'] == 0) {
    return NULL;
  }
  $flat = book_get_flat_menu($book_link);
  reset($flat);
  $curr = NULL;
  do {
    $prev = $curr;
    $curr = current($flat);
    $key = key($flat);
    next($flat);
  } while ($key && $key != $book_link['mlid']);

  if ($key == $book_link['mlid']) {
    // The previous page in the book may be a child of the previous visible link.
    if ($prev['depth'] == $book_link['depth'] && $prev['has_children']) {
      // The subtree will have only one link at the top level - get its data.
      $tree = book_menu_subtree_data($prev);
      $data = array_shift($tree);
      // The link of interest is the last child - iterate to find the deepest one.
      while ($data['below']) {
        $data = end($data['below']);
      }

      return $data['link'];
    }
    else {
      return $prev;
    }
  }
}

/**
 * Fetches the menu link for the next page of the book.
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   A fully loaded menu link for the page after the one represented in
 *   $book_link.
 */
function book_next($book_link) {
  $flat = book_get_flat_menu($book_link);
  reset($flat);
  do {
    $key = key($flat);
    next($flat);
  }
  while ($key && $key != $book_link['mlid']);

  if ($key == $book_link['mlid']) {
    return current($flat);
  }
}

/**
 * Formats the menu links for the child pages of the current page.
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   HTML for the links to the child pages of the current page.
 */
function book_children($book_link) {
  $flat = book_get_flat_menu($book_link);

  $children = array();

  if ($book_link['has_children']) {
    // Walk through the array until we find the current page.
    do {
      $link = array_shift($flat);
    }
    while ($link && ($link['mlid'] != $book_link['mlid']));
    // Continue though the array and collect the links whose parent is this page.
    while (($link = array_shift($flat)) && $link['plid'] == $book_link['mlid']) {
      $data['link'] = $link;
      $data['below'] = '';
      $children[] = $data;
    }
  }

  if ($children) {
    $elements = menu_tree_output($children);
    return drupal_render($elements);
  }
  return '';
}

/**
 * Generates the corresponding menu name from a book ID.
 *
 * @param $bid
 *   The book ID for which to make a menu name.
 *
 * @return
 *   The menu name.
 */
function book_menu_name($bid) {
  return 'book-toc-' . $bid;
}

/**
 * Implements hook_node_load().
 */
function book_node_load($nodes, $types) {
  $result = db_query("SELECT * FROM {book} b INNER JOIN {menu_links} ml ON b.mlid = ml.mlid WHERE b.nid IN (:nids)", array(':nids' =>  array_keys($nodes)), array('fetch' => PDO::FETCH_ASSOC));
  foreach ($result as $record) {
    $nodes[$record['nid']]->book = $record;
    $nodes[$record['nid']]->book['href'] = $record['link_path'];
    $nodes[$record['nid']]->book['title'] = $record['link_title'];
    $nodes[$record['nid']]->book['options'] = unserialize($record['options']);
  }
}

/**
 * Implements hook_node_view().
 */
function book_node_view($node, $view_mode) {
  if ($view_mode == 'full') {
    if (!empty($node->book['bid']) && empty($node->in_preview)) {
      $node->content['book_navigation'] = array(
        '#markup' => theme('book_navigation', array('book_link' => $node->book)),
        '#weight' => 100,
      );
    }
  }

  if ($view_mode != 'rss') {
    book_node_view_link($node, $view_mode);
  }
}

/**
 * Implements hook_page_alter().
 *
 * Adds the book menu to the list of menus used to build the active trail when
 * viewing a book page.
 */
function book_page_alter(&$page) {
  if (($node = menu_get_object()) && !empty($node->book['bid'])) {
    $active_menus = menu_get_active_menu_names();
    $active_menus[] = $node->book['menu_name'];
    menu_set_active_menu_names($active_menus);
  }
}

/**
 * Implements hook_node_presave().
 */
function book_node_presave($node) {
  // Always save a revision for non-administrators.
  if (!empty($node->book['bid']) && !user_access('administer nodes')) {
    $node->revision = 1;
    // The database schema requires a log message for every revision.
    if (!isset($node->log)) {
      $node->log = '';
    }
  }
  // Make sure a new node gets a new menu link.
  if (empty($node->nid)) {
    $node->book['mlid'] = NULL;
  }
}

/**
 * Implements hook_node_insert().
 */
function book_node_insert($node) {
  if (!empty($node->book['bid'])) {
    if ($node->book['bid'] == 'new') {
      // New nodes that are their own book.
      $node->book['bid'] = $node->nid;
    }
    $node->book['nid'] = $node->nid;
    $node->book['menu_name'] = book_menu_name($node->book['bid']);
    _book_update_outline($node);
  }
}

/**
 * Implements hook_node_update().
 */
function book_node_update($node) {
  if (!empty($node->book['bid'])) {
    if ($node->book['bid'] == 'new') {
      // New nodes that are their own book.
      $node->book['bid'] = $node->nid;
    }
    $node->book['nid'] = $node->nid;
    $node->book['menu_name'] = book_menu_name($node->book['bid']);
    _book_update_outline($node);
  }
}

/**
 * Implements hook_node_delete().
 */
function book_node_delete($node) {
  if (!empty($node->book['bid'])) {
    if ($node->nid == $node->book['bid']) {
      // Handle deletion of a top-level post.
      $result = db_query("SELECT b.nid FROM {menu_links} ml INNER JOIN {book} b on b.mlid = ml.mlid WHERE ml.plid = :plid", array(
        ':plid' => $node->book['mlid']
      ));
      foreach ($result as $child) {
        $child_node = node_load($child->nid);
        $child_node->book['bid'] = $child_node->nid;
        _book_update_outline($child_node);
      }
    }
    menu_link_delete($node->book['mlid']);
    db_delete('book')
      ->condition('mlid', $node->book['mlid'])
      ->execute();
    drupal_static_reset('book_get_books');
  }
}

/**
 * Implements hook_node_prepare().
 */
function book_node_prepare($node) {
  // Prepare defaults for the add/edit form.
  if (empty($node->book) && (user_access('add content to books') || user_access('administer book outlines'))) {
    $node->book = array();

    if (empty($node->nid) && isset($_GET['parent']) && is_numeric($_GET['parent'])) {
      // Handle "Add child page" links:
      $parent = book_link_load($_GET['parent']);

      if ($parent && $parent['access']) {
        $node->book['bid'] = $parent['bid'];
        $node->book['plid'] = $parent['mlid'];
        $node->book['menu_name'] = $parent['menu_name'];
      }
    }
    // Set defaults.
    $node->book += _book_link_defaults(!empty($node->nid) ? $node->nid : 'new');
  }
  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'])) {
    $node->book['parent_depth_limit'] = _book_parent_depth_limit($node->book);
  }
}

/**
 * Finds the depth limit for items in the parent select.
 *
 * @param $book_link
 *   A fully loaded menu link that is part of the book hierarchy.
 *
 * @return
 *   The depth limit for items in the parent select.
 */
function _book_parent_depth_limit($book_link) {
  return MENU_MAX_DEPTH - 1 - (($book_link['mlid'] && $book_link['has_children']) ? menu_link_children_relative_depth($book_link) : 0);
}

/**
 * Implements hook_form_FORM_ID_alter() for node_delete_confirm().
 *
 * Alters the confirm form for a single node deletion.
 *
 * @see node_delete_confirm()
 */
function book_form_node_delete_confirm_alter(&$form, $form_state) {
  $node = node_load($form['nid']['#value']);

  if (isset($node->book) && $node->book['has_children']) {
    $form['book_warning'] = array(
      '#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->title)) . '</p>',
      '#weight' => -10,
    );
  }
}

/**
 * Returns an array with default values for a book page's menu link.
 *
 * @param $nid
 *   The ID of the node whose menu link is being created.
 *
 * @return
 *   The default values for the menu link.
 */
function _book_link_defaults($nid) {
  return array('original_bid' => 0, 'menu_name' => '', 'nid' => $nid, 'bid' => 0, 'router_path' => 'node/%', 'plid' => 0, 'mlid' => 0, 'has_children' => 0, 'weight' => 0, 'module' => 'book', 'options' => array());
}

/**
 * Processes variables for book-all-books-block.tpl.php.
 *
 * 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).
 *
 * @param $variables
 *   An associative array containing the following key:
 *   - book_menus
 *
 * @see book-all-books-block.tpl.php
 */
function template_preprocess_book_all_books_block(&$variables) {
  // Remove all non-renderable elements.
  $elements = $variables['book_menus'];
  $variables['book_menus'] = array();
  foreach (element_children($elements) as $index) {
    $variables['book_menus'][$index] = $elements[$index];
  }
}

/**
 * Processes variables for book-navigation.tpl.php.
 *
 * @param $variables
 *   An associative array containing the following key:
 *   - book_link
 *
 * @see book-navigation.tpl.php
 */
function template_preprocess_book_navigation(&$variables) {
  $book_link = $variables['book_link'];

  // Provide extra variables for themers. Not needed by default.
  $variables['book_id'] = $book_link['bid'];
  $variables['book_title'] = check_plain($book_link['link_title']);
  $variables['book_url'] = 'node/' . $book_link['bid'];
  $variables['current_depth'] = $book_link['depth'];
  $variables['tree'] = '';

  if ($book_link['mlid']) {
    $variables['tree'] = book_children($book_link);

    if ($prev = book_prev($book_link)) {
      $prev_href = url($prev['href']);
      drupal_add_html_head_link(array('rel' => 'prev', 'href' => $prev_href));
      $variables['prev_url'] = $prev_href;
      $variables['prev_title'] = check_plain($prev['title']);
    }

    if ($book_link['plid'] && $parent = book_link_load($book_link['plid'])) {
      $parent_href = url($parent['href']);
      drupal_add_html_head_link(array('rel' => 'up', 'href' => $parent_href));
      $variables['parent_url'] = $parent_href;
      $variables['parent_title'] = check_plain($parent['title']);
    }

    if ($next = book_next($book_link)) {
      $next_href = url($next['href']);
      drupal_add_html_head_link(array('rel' => 'next', 'href' => $next_href));
      $variables['next_url'] = $next_href;
      $variables['next_title'] = check_plain($next['title']);
    }
  }

  $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] = '';
    }
  }
}

/**
 * Recursively processes and formats menu items for book_toc().
 *
 * This helper function recursively modifies the table of contents array for
 * each item in the menu tree, ignoring items in the exclude array or at a depth
 * greater than the limit. Truncates titles over thirty characters and appends
 * an indentation string incremented by depth.
 *
 * @param $tree
 *   The data structure of the book's menu tree. Includes hidden links.
 * @param $indent
 *   A string appended to each menu item title. Increments by '--' per depth
 *   level.
 * @param $toc
 *   Reference to the table of contents array. This is modified in place, so the
 *   function does not have a return value.
 * @param $exclude
 *   (optional) An array of menu link ID values. Any link whose menu link ID is
 *   in this array will be excluded (along with its children). Defaults to an
 *   empty array.
 * @param $depth_limit
 *   Any link deeper than this value will be excluded (along with its children).
 */
function _book_toc_recurse($tree, $indent, &$toc, $exclude, $depth_limit) {
  foreach ($tree as $data) {
    if ($data['link']['depth'] > $depth_limit) {
      // Don't iterate through any links on this level.
      break;
    }

    if (!in_array($data['link']['mlid'], $exclude)) {
      $toc[$data['link']['mlid']] = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, TRUE);
      if ($data['below']) {
        _book_toc_recurse($data['below'], $indent . '--', $toc, $exclude, $depth_limit);
      }
    }
  }
}

/**
 * Returns an array of book pages in table of contents order.
 *
 * @param $bid
 *   The ID of the book whose pages are to be listed.
 * @param $depth_limit
 *   Any link deeper than this value will be excluded (along with its children).
 * @param $exclude
 *   Optional array of menu link ID values. Any link whose menu link ID is in
 *   this array will be excluded (along with its children).
 *
 * @return
 *   An array of (menu link ID, title) pairs for use as options for selecting a
 *   book page.
 */
function book_toc($bid, $depth_limit, $exclude = array()) {
  $tree = menu_tree_all_data(book_menu_name($bid));
  $toc = array();
  _book_toc_recurse($tree, '', $toc, $exclude, $depth_limit);

  return $toc;
}

/**
 * Processes variables for book-export-html.tpl.php.
 *
 * @param $variables
 *   An associative array containing the following keys:
 *   - title
 *   - contents
 *   - depth
 *
 * @see book-export-html.tpl.php
 */
function template_preprocess_book_export_html(&$variables) {
  global $base_url, $language;

  $variables['title'] = check_plain($variables['title']);
  $variables['base_url'] = $base_url;
  $variables['language'] = $language;
  $variables['language_rtl'] = ($language->direction == LANGUAGE_RTL);
  $variables['head'] = drupal_get_html_head();
  $variables['dir'] = $language->direction ? 'rtl' : 'ltr';
}

/**
 * Traverses the book tree to build printable or exportable output.
 *
 * During the traversal, the $visit_func() callback is applied to each node and
 * is called recursively for each child of the node (in weight, title order).
 *
 * @param $tree
 *   A subtree of the book menu hierarchy, rooted at the current page.
 * @param $visit_func
 *   A function callback to be called upon visiting a node in the tree.
 *
 * @return
 *   The output generated in visiting each node.
 */
function book_export_traverse($tree, $visit_func) {
  $output = '';

  foreach ($tree as $data) {
    // Note- access checking is already performed when building the tree.
    if ($node = node_load($data['link']['nid'], FALSE)) {
      $children = '';

      if ($data['below']) {
        $children = book_export_traverse($data['below'], $visit_func);
      }

      if (function_exists($visit_func)) {
        $output .= call_user_func($visit_func, $node, $children);
      }
      else {
        // Use the default function.
        $output .= book_node_export($node, $children);
      }
    }
  }

  return $output;
}

/**
 * Generates printer-friendly HTML for a node.
 *
 * @param $node
 *   The node that will be output.
 * @param $children
 *   (optional) All the rendered child nodes within the current node. Defaults
 *   to an empty string.
 *
 * @return
 *   The HTML generated for the given node.
 *
 * @see book_export_traverse()
 */
function book_node_export($node, $children = '') {
  $build = node_view($node, 'print');
  unset($build['#theme']);
  // @todo Rendering should happen in the template using render().
  $node->rendered = drupal_render($build);

  return theme('book_node_export_html', array('node' => $node, 'children' => $children));
}

/**
 * Processes variables for book-node-export-html.tpl.php.
 *
 * @param $variables
 *   An associative array containing the following keys:
 *   - node
 *   - children
 *
 * @see book-node-export-html.tpl.php
 */
function template_preprocess_book_node_export_html(&$variables) {
  $variables['depth'] = $variables['node']->book['depth'];
  $variables['title'] = check_plain($variables['node']->title);
  $variables['content'] = $variables['node']->rendered;
}

/**
 * Determine if a given node type is in the list of types allowed for books.
 *
 * @param $type
 *   A node type.
 *
 * @return
 *   A Boolean TRUE if the node type can be included in books; otherwise, FALSE.
 */
function book_type_is_allowed($type) {
  return in_array($type, variable_get('book_allowed_types', array('book')));
}

/**
 * Implements hook_node_type_update().
 *
 * Updates the Book module's persistent variables if the machine-readable name
 * of a node type is changed.
 */
function book_node_type_update($type) {
  if (!empty($type->old_type) && $type->old_type != $type->type) {
    // Update the list of node types that are allowed to be added to books.
    $allowed_types = variable_get('book_allowed_types', array('book'));
    $key = array_search($type->old_type, $allowed_types);

    if ($key !== FALSE) {
      $allowed_types[$type->type] = $allowed_types[$key] ? $type->type : 0;
      unset($allowed_types[$key]);
      variable_set('book_allowed_types', $allowed_types);
    }

    // Update the setting for the "Add child page" link.
    if (variable_get('book_child_type', 'book') == $type->old_type) {
      variable_set('book_child_type', $type->type);
    }
  }
}

/**
 * Gets a book menu link by its menu link ID.
 *
 * Like menu_link_load(), but adds additional data from the {book} table.
 *
 * Do not call when loading a node, since this function may call node_load().
 *
 * @param $mlid
 *   The menu link ID of the menu item.
 *
 * @return
 *   A menu link, with the link translated for rendering and data added from the
 *   {book} table. FALSE if there is an error.
 */
function book_link_load($mlid) {
  if ($item = db_query("SELECT * FROM {menu_links} ml INNER JOIN {book} b ON b.mlid = ml.mlid LEFT JOIN {menu_router} m ON m.path = ml.router_path WHERE ml.mlid = :mlid", array(
      ':mlid' => $mlid,
    ))->fetchAssoc()) {
    _menu_link_translate($item);
    return $item;
  }

  return FALSE;
}

/**
 * Gets the data representing a subtree of the book hierarchy.
 *
 * The root of the subtree will be the link passed as a parameter, so the
 * returned tree will contain this item and all its descendents in the menu
 * tree.
 *
 * @param $link
 *   A fully loaded menu link.
 *
 * @return
 *   A subtree of menu links in an array, in the order they should be rendered.
 */
function book_menu_subtree_data($link) {
  $tree = &drupal_static(__FUNCTION__, array());

  // Generate a cache ID (cid) specific for this $menu_name and $link.
  $cid = 'links:' . $link['menu_name'] . ':subtree-cid:' . $link['mlid'];

  if (!isset($tree[$cid])) {
    $cache = cache_get($cid, 'cache_menu');

    if ($cache && isset($cache->data)) {
      // If the cache entry exists, it will just be the cid for the actual data.
      // This avoids duplication of large amounts of data.
      $cache = cache_get($cache->data, 'cache_menu');

      if ($cache && isset($cache->data)) {
        $data = $cache->data;
      }
    }

    // If the subtree data was not in the cache, $data will be NULL.
    if (!isset($data)) {
      $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
      $query->join('menu_router', 'm', 'm.path = ml.router_path');
      $query->join('book', 'b', 'ml.mlid = b.mlid');
      $query->fields('b');
      $query->fields('m', array('load_functions', 'to_arg_functions', 'access_callback', 'access_arguments', 'page_callback', 'page_arguments', 'delivery_callback', 'title', 'title_callback', 'title_arguments', 'type'));
      $query->fields('ml');
      $query->condition('menu_name', $link['menu_name']);
      for ($i = 1; $i <= MENU_MAX_DEPTH && $link["p$i"]; ++$i) {
        $query->condition("p$i", $link["p$i"]);
      }
      for ($i = 1; $i <= MENU_MAX_DEPTH; ++$i) {
        $query->orderBy("p$i");
      }
      $links = array();
      foreach ($query->execute() as $item) {
        $links[] = $item;
      }
      $data['tree'] = menu_tree_data($links, array(), $link['depth']);
      $data['node_links'] = array();
      menu_tree_collect_node_links($data['tree'], $data['node_links']);
      // Compute the real cid for book subtree data.
      $tree_cid = 'links:' . $item['menu_name'] . ':subtree-data:' . hash('sha256', serialize($data));
      // Cache the data, if it is not already in the cache.

      if (!cache_get($tree_cid, 'cache_menu')) {
        cache_set($tree_cid, $data, 'cache_menu');
      }
      // Cache the cid of the (shared) data using the menu and item-specific cid.
      cache_set($cid, $tree_cid, 'cache_menu');
    }
    // Check access for the current user to each item in the tree.
    menu_tree_check_access($data['tree'], $data['node_links']);
    $tree[$cid] = $data['tree'];
  }

  return $tree[$cid];
}
