book.module

You are here

  1. 7 modules/book/book.module
  2. 4.6 modules/book.module
  3. 4.7 modules/book.module
  4. 5 modules/book/book.module
  5. 6 modules/book/book.module
  6. 8 core/modules/book/book.module

Allows users to create and organize related content in an outline.

Functions

Namesort descending Description
book_admin_paths Implements hook_admin_paths().
book_block_configure Implements hook_block_configure().
book_block_info Implements hook_block_info().
book_block_save Implements hook_block_save().
book_block_view Implements hook_block_view().
book_children Formats the menu links for the child pages of the current page.
book_entity_info_alter Implements hook_entity_info_alter().
book_export_traverse Traverses the book tree to build printable or exportable output.
book_form_node_delete_confirm_alter Implements hook_form_FORM_ID_alter() for node_delete_confirm().
book_form_node_form_alter Implements hook_form_BASE_FORM_ID_alter() for node_form().
book_form_update Renders a new parent page select element when the book selection changes.
book_get_books Returns an array of all books.
book_get_flat_menu Gets the book menu tree for a page and returns it as a linear array.
book_help Implements hook_help().
book_link_load Gets a book menu link by its menu link ID.
book_menu Implements hook_menu().
book_menu_name Generates the corresponding menu name from a book ID.
book_menu_subtree_data Gets the data representing a subtree of the book hierarchy.
book_next Fetches the menu link for the next page of the book.
book_node_delete Implements hook_node_delete().
book_node_export Generates printer-friendly HTML for a node.
book_node_insert Implements hook_node_insert().
book_node_load Implements hook_node_load().
book_node_prepare Implements hook_node_prepare().
book_node_presave Implements hook_node_presave().
book_node_type_update Implements hook_node_type_update().
book_node_update Implements hook_node_update().
book_node_view Implements hook_node_view().
book_node_view_link Adds relevant book links to the node's links.
book_page_alter Implements hook_page_alter().
book_permission Implements hook_permission().
book_pick_book_nojs_submit Form submission handler for node_form().
book_prev Fetches the menu link for the previous page of the book.
book_theme Implements hook_theme().
book_toc Returns an array of book pages in table of contents order.
book_type_is_allowed Determine if a given node type is in the list of types allowed for books.
book_update_bid Updates the book ID of a page and its children when it moves to a new book.
template_preprocess_book_all_books_block Processes variables for book-all-books-block.tpl.php.
template_preprocess_book_export_html Processes variables for book-export-html.tpl.php.
template_preprocess_book_navigation Processes variables for book-navigation.tpl.php.
template_preprocess_book_node_export_html Processes variables for book-node-export-html.tpl.php.
theme_book_title_link Returns HTML for a link to a book title when used as a block title.
_book_add_form_elements Builds the common elements of the book form for the node and outline forms.
_book_flatten_menu Recursively converts a tree of menu links to a flat array.
_book_link_defaults Returns an array with default values for a book page's menu link.
_book_node_is_removable Determines if a node can be removed from the book.
_book_outline_access Access callback: Determines if the outline tab is accessible.
_book_outline_remove_access Access callback: Determines if the user can remove nodes from the outline.
_book_parent_depth_limit Finds the depth limit for items in the parent select.
_book_parent_select Builds the parent selection form element for the node form or outline tab.
_book_toc_recurse Recursively processes and formats menu items for book_toc().
_book_update_outline Handles additions and updates to the book outline.

File

modules/book/book.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Allows users to create and organize related content in an outline.
  5. */
  6. /**
  7. * Implements hook_help().
  8. */
  9. function book_help($path, $arg) {
  10. switch ($path) {
  11. case 'admin/help#book':
  12. $output = '<h3>' . t('About') . '</h3>';
  13. $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>';
  14. $output .= '<h3>' . t('Uses') . '</h3>';
  15. $output .= '<dl>';
  16. $output .= '<dt>' . t('Adding and managing book content') . '</dt>';
  17. $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>';
  18. $output .= '<dt>' . t('Book navigation') . '</dt>';
  19. $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>';
  20. $output .= '<dt>' . t('Collaboration') . '</dt>';
  21. $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>';
  22. $output .= '<dt>' . t('Printing books') . '</dt>';
  23. $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>';
  24. $output .= '</dl>';
  25. return $output;
  26. case 'admin/content/book':
  27. 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>';
  28. case 'node/%/outline':
  29. 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>';
  30. }
  31. }
  32. /**
  33. * Implements hook_theme().
  34. */
  35. function book_theme() {
  36. return array(
  37. 'book_navigation' => array(
  38. 'variables' => array('book_link' => NULL),
  39. 'template' => 'book-navigation',
  40. ),
  41. 'book_export_html' => array(
  42. 'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
  43. 'template' => 'book-export-html',
  44. ),
  45. 'book_admin_table' => array(
  46. 'render element' => 'form',
  47. ),
  48. 'book_title_link' => array(
  49. 'variables' => array('link' => NULL),
  50. ),
  51. 'book_all_books_block' => array(
  52. 'render element' => 'book_menus',
  53. 'template' => 'book-all-books-block',
  54. ),
  55. 'book_node_export_html' => array(
  56. 'variables' => array('node' => NULL, 'children' => NULL),
  57. 'template' => 'book-node-export-html',
  58. ),
  59. );
  60. }
  61. /**
  62. * Implements hook_permission().
  63. */
  64. function book_permission() {
  65. return array(
  66. 'administer book outlines' => array(
  67. 'title' => t('Administer book outlines'),
  68. ),
  69. 'create new books' => array(
  70. 'title' => t('Create new books'),
  71. ),
  72. 'add content to books' => array(
  73. 'title' => t('Add content and child pages to books'),
  74. ),
  75. 'access printer-friendly version' => array(
  76. 'title' => t('View printer-friendly books'),
  77. 'description' => t('View a book page and all of its sub-pages as a single document for ease of printing. Can be performance heavy.'),
  78. ),
  79. );
  80. }
  81. /**
  82. * Adds relevant book links to the node's links.
  83. *
  84. * @param $node
  85. * The book page node to add links to.
  86. * @param $view_mode
  87. * The view mode of the node.
  88. */
  89. function book_node_view_link($node, $view_mode) {
  90. $links = array();
  91. if (isset($node->book['depth'])) {
  92. if ($view_mode == 'full' && node_is_page($node)) {
  93. $child_type = variable_get('book_child_type', 'book');
  94. 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) {
  95. $links['book_add_child'] = array(
  96. 'title' => t('Add child page'),
  97. 'href' => 'node/add/' . str_replace('_', '-', $child_type),
  98. 'query' => array('parent' => $node->book['mlid']),
  99. );
  100. }
  101. if (user_access('access printer-friendly version')) {
  102. $links['book_printer'] = array(
  103. 'title' => t('Printer-friendly version'),
  104. 'href' => 'book/export/html/' . $node->nid,
  105. 'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
  106. );
  107. }
  108. }
  109. }
  110. if (!empty($links)) {
  111. $node->content['links']['book'] = array(
  112. '#theme' => 'links__node__book',
  113. '#links' => $links,
  114. '#attributes' => array('class' => array('links', 'inline')),
  115. );
  116. }
  117. }
  118. /**
  119. * Implements hook_menu().
  120. */
  121. function book_menu() {
  122. $items['admin/content/book'] = array(
  123. 'title' => 'Books',
  124. 'description' => "Manage your site's book outlines.",
  125. 'page callback' => 'book_admin_overview',
  126. 'access arguments' => array('administer book outlines'),
  127. 'type' => MENU_LOCAL_TASK,
  128. 'file' => 'book.admin.inc',
  129. );
  130. $items['admin/content/book/list'] = array(
  131. 'title' => 'List',
  132. 'type' => MENU_DEFAULT_LOCAL_TASK,
  133. );
  134. $items['admin/content/book/settings'] = array(
  135. 'title' => 'Settings',
  136. 'page callback' => 'drupal_get_form',
  137. 'page arguments' => array('book_admin_settings'),
  138. 'access arguments' => array('administer site configuration'),
  139. 'type' => MENU_LOCAL_TASK,
  140. 'weight' => 8,
  141. 'file' => 'book.admin.inc',
  142. );
  143. $items['admin/content/book/%node'] = array(
  144. 'title' => 'Re-order book pages and change titles',
  145. 'page callback' => 'drupal_get_form',
  146. 'page arguments' => array('book_admin_edit', 3),
  147. 'access callback' => '_book_outline_access',
  148. 'access arguments' => array(3),
  149. 'type' => MENU_CALLBACK,
  150. 'file' => 'book.admin.inc',
  151. );
  152. $items['book'] = array(
  153. 'title' => 'Books',
  154. 'page callback' => 'book_render',
  155. 'access arguments' => array('access content'),
  156. 'type' => MENU_SUGGESTED_ITEM,
  157. 'file' => 'book.pages.inc',
  158. );
  159. $items['book/export/%/%'] = array(
  160. 'page callback' => 'book_export',
  161. 'page arguments' => array(2, 3),
  162. 'access arguments' => array('access printer-friendly version'),
  163. 'type' => MENU_CALLBACK,
  164. 'file' => 'book.pages.inc',
  165. );
  166. $items['node/%node/outline'] = array(
  167. 'title' => 'Outline',
  168. 'page callback' => 'book_outline',
  169. 'page arguments' => array(1),
  170. 'access callback' => '_book_outline_access',
  171. 'access arguments' => array(1),
  172. 'type' => MENU_LOCAL_TASK,
  173. 'weight' => 2,
  174. 'file' => 'book.pages.inc',
  175. );
  176. $items['node/%node/outline/remove'] = array(
  177. 'title' => 'Remove from outline',
  178. 'page callback' => 'drupal_get_form',
  179. 'page arguments' => array('book_remove_form', 1),
  180. 'access callback' => '_book_outline_remove_access',
  181. 'access arguments' => array(1),
  182. 'file' => 'book.pages.inc',
  183. );
  184. return $items;
  185. }
  186. /**
  187. * Access callback: Determines if the outline tab is accessible.
  188. *
  189. * @param $node
  190. * The node whose outline tab is to be viewed.
  191. */
  192. function _book_outline_access($node) {
  193. return user_access('administer book outlines') && node_access('view', $node);
  194. }
  195. /**
  196. * Access callback: Determines if the user can remove nodes from the outline.
  197. *
  198. * @param $node
  199. * The node to remove from the outline.
  200. *
  201. * @see book_menu()
  202. */
  203. function _book_outline_remove_access($node) {
  204. return _book_node_is_removable($node) && _book_outline_access($node);
  205. }
  206. /**
  207. * Determines if a node can be removed from the book.
  208. *
  209. * A node can be removed from a book if it is actually in a book and it either
  210. * is not a top-level page or is a top-level page with no children.
  211. *
  212. * @param $node
  213. * The node to remove from the outline.
  214. */
  215. function _book_node_is_removable($node) {
  216. return (!empty($node->book['bid']) && (($node->book['bid'] != $node->nid) || !$node->book['has_children']));
  217. }
  218. /**
  219. * Implements hook_admin_paths().
  220. */
  221. function book_admin_paths() {
  222. if (variable_get('node_admin_theme')) {
  223. $paths = array(
  224. 'node/*/outline' => TRUE,
  225. 'node/*/outline/remove' => TRUE,
  226. );
  227. return $paths;
  228. }
  229. }
  230. /**
  231. * Implements hook_entity_info_alter().
  232. */
  233. function book_entity_info_alter(&$info) {
  234. // Add the 'Print' view mode for nodes.
  235. $info['node']['view modes'] += array(
  236. 'print' => array(
  237. 'label' => t('Print'),
  238. 'custom settings' => FALSE,
  239. ),
  240. );
  241. }
  242. /**
  243. * Implements hook_block_info().
  244. */
  245. function book_block_info() {
  246. $block = array();
  247. $block['navigation']['info'] = t('Book navigation');
  248. $block['navigation']['cache'] = DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE;
  249. return $block;
  250. }
  251. /**
  252. * Implements hook_block_view().
  253. *
  254. * Displays the book table of contents in a block when the current page is a
  255. * single-node view of a book node.
  256. */
  257. function book_block_view($delta = '') {
  258. $block = array();
  259. $current_bid = 0;
  260. if ($node = menu_get_object()) {
  261. $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
  262. }
  263. if (variable_get('book_block_mode', 'all pages') == 'all pages') {
  264. $block['subject'] = t('Book navigation');
  265. $book_menus = array();
  266. $pseudo_tree = array(0 => array('below' => FALSE));
  267. foreach (book_get_books() as $book_id => $book) {
  268. if ($book['bid'] == $current_bid) {
  269. // If the current page is a node associated with a book, the menu
  270. // needs to be retrieved.
  271. $book_menus[$book_id] = menu_tree_output(menu_tree_all_data($node->book['menu_name'], $node->book));
  272. }
  273. else {
  274. // Since we know we will only display a link to the top node, there
  275. // is no reason to run an additional menu tree query for each book.
  276. $book['in_active_trail'] = FALSE;
  277. // Check whether user can access the book link.
  278. $book_node = node_load($book['nid']);
  279. $book['access'] = node_access('view', $book_node);
  280. $pseudo_tree[0]['link'] = $book;
  281. $book_menus[$book_id] = menu_tree_output($pseudo_tree);
  282. }
  283. }
  284. $book_menus['#theme'] = 'book_all_books_block';
  285. $block['content'] = $book_menus;
  286. }
  287. elseif ($current_bid) {
  288. // Only display this block when the user is browsing a book.
  289. $select = db_select('node', 'n')
  290. ->fields('n', array('title'))
  291. ->condition('n.nid', $node->book['bid'])
  292. ->addTag('node_access');
  293. $title = $select->execute()->fetchField();
  294. // Only show the block if the user has view access for the top-level node.
  295. if ($title) {
  296. $tree = menu_tree_all_data($node->book['menu_name'], $node->book);
  297. // There should only be one element at the top level.
  298. $data = array_shift($tree);
  299. $block['subject'] = theme('book_title_link', array('link' => $data['link']));
  300. $block['content'] = ($data['below']) ? menu_tree_output($data['below']) : '';
  301. }
  302. }
  303. return $block;
  304. }
  305. /**
  306. * Implements hook_block_configure().
  307. */
  308. function book_block_configure($delta = '') {
  309. $block = array();
  310. $options = array(
  311. 'all pages' => t('Show block on all pages'),
  312. 'book pages' => t('Show block only on book pages'),
  313. );
  314. $form['book_block_mode'] = array(
  315. '#type' => 'radios',
  316. '#title' => t('Book navigation block display'),
  317. '#options' => $options,
  318. '#default_value' => variable_get('book_block_mode', 'all pages'),
  319. '#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."),
  320. );
  321. return $form;
  322. }
  323. /**
  324. * Implements hook_block_save().
  325. */
  326. function book_block_save($delta = '', $edit = array()) {
  327. $block = array();
  328. variable_set('book_block_mode', $edit['book_block_mode']);
  329. }
  330. /**
  331. * Returns HTML for a link to a book title when used as a block title.
  332. *
  333. * @param $variables
  334. * An associative array containing:
  335. * - link: An array containing title, href and options for the link.
  336. *
  337. * @ingroup themeable
  338. */
  339. function theme_book_title_link($variables) {
  340. $link = $variables['link'];
  341. $link['options']['attributes']['class'] = array('book-title');
  342. return l($link['title'], $link['href'], $link['options']);
  343. }
  344. /**
  345. * Returns an array of all books.
  346. *
  347. * This list may be used for generating a list of all the books, or for building
  348. * the options for a form select.
  349. *
  350. * @return
  351. * An array of all books.
  352. */
  353. function book_get_books() {
  354. $all_books = &drupal_static(__FUNCTION__);
  355. if (!isset($all_books)) {
  356. $all_books = array();
  357. $nids = db_query("SELECT DISTINCT(bid) FROM {book}")->fetchCol();
  358. if ($nids) {
  359. $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
  360. $query->join('node', 'n', 'b.nid = n.nid');
  361. $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
  362. $query->addField('n', 'type', 'type');
  363. $query->addField('n', 'title', 'title');
  364. $query->fields('b');
  365. $query->fields('ml');
  366. $query->condition('n.nid', $nids, 'IN');
  367. $query->condition('n.status', 1);
  368. $query->orderBy('ml.weight');
  369. $query->orderBy('ml.link_title');
  370. $query->addTag('node_access');
  371. $result2 = $query->execute();
  372. foreach ($result2 as $link) {
  373. $link['href'] = $link['link_path'];
  374. $link['options'] = unserialize($link['options']);
  375. $all_books[$link['bid']] = $link;
  376. }
  377. }
  378. }
  379. return $all_books;
  380. }
  381. /**
  382. * Implements hook_form_BASE_FORM_ID_alter() for node_form().
  383. *
  384. * Adds the book fieldset to the node form.
  385. *
  386. * @see book_pick_book_nojs_submit()
  387. */
  388. function book_form_node_form_alter(&$form, &$form_state, $form_id) {
  389. $node = $form['#node'];
  390. $access = user_access('administer book outlines');
  391. if (!$access) {
  392. if (user_access('add content to books') && ((!empty($node->book['mlid']) && !empty($node->nid)) || book_type_is_allowed($node->type))) {
  393. // Already in the book hierarchy, or this node type is allowed.
  394. $access = TRUE;
  395. }
  396. }
  397. if ($access) {
  398. _book_add_form_elements($form, $form_state, $node);
  399. // Since the "Book" dropdown can't trigger a form submission when
  400. // JavaScript is disabled, add a submit button to do that. book.css hides
  401. // this button when JavaScript is enabled.
  402. $form['book']['pick-book'] = array(
  403. '#type' => 'submit',
  404. '#value' => t('Change book (update list of parents)'),
  405. '#submit' => array('book_pick_book_nojs_submit'),
  406. '#weight' => 20,
  407. );
  408. }
  409. }
  410. /**
  411. * Form submission handler for node_form().
  412. *
  413. * This handler is run when JavaScript is disabled. It triggers the form to
  414. * rebuild so that the "Parent item" options are changed to reflect the newly
  415. * selected book. When JavaScript is enabled, the submit button that triggers
  416. * this handler is hidden, and the "Book" dropdown directly triggers the
  417. * book_form_update() Ajax callback instead.
  418. *
  419. * @see book_form_update()
  420. * @see book_form_node_form_alter()
  421. */
  422. function book_pick_book_nojs_submit($form, &$form_state) {
  423. $form_state['node']->book = $form_state['values']['book'];
  424. $form_state['rebuild'] = TRUE;
  425. }
  426. /**
  427. * Builds the parent selection form element for the node form or outline tab.
  428. *
  429. * This function is also called when generating a new set of options during the
  430. * Ajax callback, so an array is returned that can be used to replace an
  431. * existing form element.
  432. *
  433. * @param $book_link
  434. * A fully loaded menu link that is part of the book hierarchy.
  435. *
  436. * @return
  437. * A parent selection form element.
  438. */
  439. function _book_parent_select($book_link) {
  440. if (variable_get('menu_override_parent_selector', FALSE)) {
  441. return array();
  442. }
  443. // Offer a message or a drop-down to choose a different parent page.
  444. $form = array(
  445. '#type' => 'hidden',
  446. '#value' => -1,
  447. '#prefix' => '<div id="edit-book-plid-wrapper">',
  448. '#suffix' => '</div>',
  449. );
  450. if ($book_link['nid'] === $book_link['bid']) {
  451. // This is a book - at the top level.
  452. if ($book_link['original_bid'] === $book_link['bid']) {
  453. $form['#prefix'] .= '<em>' . t('This is the top-level page in this book.') . '</em>';
  454. }
  455. else {
  456. $form['#prefix'] .= '<em>' . t('This will be the top-level page in this book.') . '</em>';
  457. }
  458. }
  459. elseif (!$book_link['bid']) {
  460. $form['#prefix'] .= '<em>' . t('No book selected.') . '</em>';
  461. }
  462. else {
  463. $form = array(
  464. '#type' => 'select',
  465. '#title' => t('Parent item'),
  466. '#default_value' => $book_link['plid'],
  467. '#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)),
  468. '#options' => book_toc($book_link['bid'], $book_link['parent_depth_limit'], array($book_link['mlid'])),
  469. '#attributes' => array('class' => array('book-title-select')),
  470. '#prefix' => '<div id="edit-book-plid-wrapper">',
  471. '#suffix' => '</div>',
  472. );
  473. }
  474. return $form;
  475. }
  476. /**
  477. * Builds the common elements of the book form for the node and outline forms.
  478. *
  479. * @param $node
  480. * The node whose form is being viewed.
  481. */
  482. function _book_add_form_elements(&$form, &$form_state, $node) {
  483. // If the form is being processed during the Ajax callback of our book bid
  484. // dropdown, then $form_state will hold the value that was selected.
  485. if (isset($form_state['values']['book'])) {
  486. $node->book = $form_state['values']['book'];
  487. }
  488. $form['book'] = array(
  489. '#type' => 'fieldset',
  490. '#title' => t('Book outline'),
  491. '#weight' => 10,
  492. '#collapsible' => TRUE,
  493. '#collapsed' => TRUE,
  494. '#group' => 'additional_settings',
  495. '#attributes' => array(
  496. 'class' => array('book-outline-form'),
  497. ),
  498. '#attached' => array(
  499. 'js' => array(drupal_get_path('module', 'book') . '/book.js'),
  500. ),
  501. '#tree' => TRUE,
  502. );
  503. foreach (array('menu_name', 'mlid', 'nid', 'router_path', 'has_children', 'options', 'module', 'original_bid', 'parent_depth_limit') as $key) {
  504. $form['book'][$key] = array(
  505. '#type' => 'value',
  506. '#value' => $node->book[$key],
  507. );
  508. }
  509. $form['book']['plid'] = _book_parent_select($node->book);
  510. // @see _book_admin_table_tree(). The weight may be larger than 15.
  511. $form['book']['weight'] = array(
  512. '#type' => 'weight',
  513. '#title' => t('Weight'),
  514. '#default_value' => $node->book['weight'],
  515. '#delta' => max(15, abs($node->book['weight'])),
  516. '#weight' => 5,
  517. '#description' => t('Pages at a given level are ordered first by weight and then by title.'),
  518. );
  519. $options = array();
  520. $nid = isset($node->nid) ? $node->nid : 'new';
  521. if (isset($node->nid) && ($nid == $node->book['original_bid']) && ($node->book['parent_depth_limit'] == 0)) {
  522. // This is the top level node in a maximum depth book and thus cannot be moved.
  523. $options[$node->nid] = $node->title;
  524. }
  525. else {
  526. foreach (book_get_books() as $book) {
  527. $options[$book['nid']] = $book['title'];
  528. }
  529. }
  530. if (user_access('create new books') && ($nid == 'new' || ($nid != $node->book['original_bid']))) {
  531. // The node can become a new book, if it is not one already.
  532. $options = array($nid => '<' . t('create a new book') . '>') + $options;
  533. }
  534. if (!$node->book['mlid']) {
  535. // The node is not currently in the hierarchy.
  536. $options = array(0 => '<' . t('none') . '>') + $options;
  537. }
  538. // Add a drop-down to select the destination book.
  539. $form['book']['bid'] = array(
  540. '#type' => 'select',
  541. '#title' => t('Book'),
  542. '#default_value' => $node->book['bid'],
  543. '#options' => $options,
  544. '#access' => (bool) $options,
  545. '#description' => t('Your page will be a part of the selected book.'),
  546. '#weight' => -5,
  547. '#attributes' => array('class' => array('book-title-select')),
  548. '#ajax' => array(
  549. 'callback' => 'book_form_update',
  550. 'wrapper' => 'edit-book-plid-wrapper',
  551. 'effect' => 'fade',
  552. 'speed' => 'fast',
  553. ),
  554. );
  555. }
  556. /**
  557. * Renders a new parent page select element when the book selection changes.
  558. *
  559. * This function is called via Ajax when the selected book is changed on a node
  560. * or book outline form.
  561. *
  562. * @return
  563. * The rendered parent page select element.
  564. */
  565. function book_form_update($form, $form_state) {
  566. return $form['book']['plid'];
  567. }
  568. /**
  569. * Handles additions and updates to the book outline.
  570. *
  571. * This common helper function performs all additions and updates to the book
  572. * outline through node addition, node editing, node deletion, or the outline
  573. * tab.
  574. *
  575. * @param $node
  576. * The node that is being saved, added, deleted, or moved.
  577. *
  578. * @return
  579. * TRUE if the menu link was saved; FALSE otherwise.
  580. */
  581. function _book_update_outline($node) {
  582. if (empty($node->book['bid'])) {
  583. return FALSE;
  584. }
  585. $new = empty($node->book['mlid']);
  586. $node->book['link_path'] = 'node/' . $node->nid;
  587. $node->book['link_title'] = $node->title;
  588. $node->book['parent_mismatch'] = FALSE; // The normal case.
  589. if ($node->book['bid'] == $node->nid) {
  590. $node->book['plid'] = 0;
  591. $node->book['menu_name'] = book_menu_name($node->nid);
  592. }
  593. else {
  594. // Check in case the parent is not is this book; the book takes precedence.
  595. if (!empty($node->book['plid'])) {
  596. $parent = db_query("SELECT * FROM {book} WHERE mlid = :mlid", array(
  597. ':mlid' => $node->book['plid'],
  598. ))->fetchAssoc();
  599. }
  600. if (empty($node->book['plid']) || !$parent || $parent['bid'] != $node->book['bid']) {
  601. $node->book['plid'] = db_query("SELECT mlid FROM {book} WHERE nid = :nid", array(
  602. ':nid' => $node->book['bid'],
  603. ))->fetchField();
  604. $node->book['parent_mismatch'] = TRUE; // Likely when JS is disabled.
  605. }
  606. }
  607. if (menu_link_save($node->book)) {
  608. if ($new) {
  609. // Insert new.
  610. db_insert('book')
  611. ->fields(array(
  612. 'nid' => $node->nid,
  613. 'mlid' => $node->book['mlid'],
  614. 'bid' => $node->book['bid'],
  615. ))
  616. ->execute();
  617. // Reset the cache of stored books.
  618. drupal_static_reset('book_get_books');
  619. }
  620. else {
  621. if ($node->book['bid'] != db_query("SELECT bid FROM {book} WHERE nid = :nid", array(
  622. ':nid' => $node->nid,
  623. ))->fetchField()) {
  624. // Update the bid for this page and all children.
  625. book_update_bid($node->book);
  626. // Reset the cache of stored books.
  627. drupal_static_reset('book_get_books');
  628. }
  629. }
  630. return TRUE;
  631. }
  632. // Failed to save the menu link.
  633. return FALSE;
  634. }
  635. /**
  636. * Updates the book ID of a page and its children when it moves to a new book.
  637. *
  638. * @param $book_link
  639. * A fully loaded menu link that is part of the book hierarchy.
  640. */
  641. function book_update_bid($book_link) {
  642. $query = db_select('menu_links');
  643. $query->addField('menu_links', 'mlid');
  644. for ($i = 1; $i <= MENU_MAX_DEPTH && $book_link["p$i"]; $i++) {
  645. $query->condition("p$i", $book_link["p$i"]);
  646. }
  647. $mlids = $query->execute()->fetchCol();
  648. if ($mlids) {
  649. db_update('book')
  650. ->fields(array('bid' => $book_link['bid']))
  651. ->condition('mlid', $mlids, 'IN')
  652. ->execute();
  653. }
  654. }
  655. /**
  656. * Gets the book menu tree for a page and returns it as a linear array.
  657. *
  658. * @param $book_link
  659. * A fully loaded menu link that is part of the book hierarchy.
  660. *
  661. * @return
  662. * A linear array of menu links in the order that the links are shown in the
  663. * menu, so the previous and next pages are the elements before and after the
  664. * element corresponding to the current node. The children of the current node
  665. * (if any) will come immediately after it in the array, and links will only
  666. * be fetched as deep as one level deeper than $book_link.
  667. */
  668. function book_get_flat_menu($book_link) {
  669. $flat = &drupal_static(__FUNCTION__, array());
  670. if (!isset($flat[$book_link['mlid']])) {
  671. // Call menu_tree_all_data() to take advantage of the menu system's caching.
  672. $tree = menu_tree_all_data($book_link['menu_name'], $book_link, $book_link['depth'] + 1);
  673. $flat[$book_link['mlid']] = array();
  674. _book_flatten_menu($tree, $flat[$book_link['mlid']]);
  675. }
  676. return $flat[$book_link['mlid']];
  677. }
  678. /**
  679. * Recursively converts a tree of menu links to a flat array.
  680. *
  681. * @param $tree
  682. * A tree of menu links in an array.
  683. * @param $flat
  684. * A flat array of the menu links from $tree, passed by reference.
  685. *
  686. * @see book_get_flat_menu().
  687. */
  688. function _book_flatten_menu($tree, &$flat) {
  689. foreach ($tree as $data) {
  690. if (!$data['link']['hidden']) {
  691. $flat[$data['link']['mlid']] = $data['link'];
  692. if ($data['below']) {
  693. _book_flatten_menu($data['below'], $flat);
  694. }
  695. }
  696. }
  697. }
  698. /**
  699. * Fetches the menu link for the previous page of the book.
  700. *
  701. * @param $book_link
  702. * A fully loaded menu link that is part of the book hierarchy.
  703. *
  704. * @return
  705. * A fully loaded menu link for the page before the one represented in
  706. * $book_link.
  707. */
  708. function book_prev($book_link) {
  709. // If the parent is zero, we are at the start of a book.
  710. if ($book_link['plid'] == 0) {
  711. return NULL;
  712. }
  713. $flat = book_get_flat_menu($book_link);
  714. // Assigning the array to $flat resets the array pointer for use with each().
  715. $curr = NULL;
  716. do {
  717. $prev = $curr;
  718. list($key, $curr) = each($flat);
  719. } while ($key && $key != $book_link['mlid']);
  720. if ($key == $book_link['mlid']) {
  721. // The previous page in the book may be a child of the previous visible link.
  722. if ($prev['depth'] == $book_link['depth'] && $prev['has_children']) {
  723. // The subtree will have only one link at the top level - get its data.
  724. $tree = book_menu_subtree_data($prev);
  725. $data = array_shift($tree);
  726. // The link of interest is the last child - iterate to find the deepest one.
  727. while ($data['below']) {
  728. $data = end($data['below']);
  729. }
  730. return $data['link'];
  731. }
  732. else {
  733. return $prev;
  734. }
  735. }
  736. }
  737. /**
  738. * Fetches the menu link for the next page of the book.
  739. *
  740. * @param $book_link
  741. * A fully loaded menu link that is part of the book hierarchy.
  742. *
  743. * @return
  744. * A fully loaded menu link for the page after the one represented in
  745. * $book_link.
  746. */
  747. function book_next($book_link) {
  748. $flat = book_get_flat_menu($book_link);
  749. // Assigning the array to $flat resets the array pointer for use with each().
  750. do {
  751. list($key, $curr) = each($flat);
  752. }
  753. while ($key && $key != $book_link['mlid']);
  754. if ($key == $book_link['mlid']) {
  755. return current($flat);
  756. }
  757. }
  758. /**
  759. * Formats the menu links for the child pages of the current page.
  760. *
  761. * @param $book_link
  762. * A fully loaded menu link that is part of the book hierarchy.
  763. *
  764. * @return
  765. * HTML for the links to the child pages of the current page.
  766. */
  767. function book_children($book_link) {
  768. $flat = book_get_flat_menu($book_link);
  769. $children = array();
  770. if ($book_link['has_children']) {
  771. // Walk through the array until we find the current page.
  772. do {
  773. $link = array_shift($flat);
  774. }
  775. while ($link && ($link['mlid'] != $book_link['mlid']));
  776. // Continue though the array and collect the links whose parent is this page.
  777. while (($link = array_shift($flat)) && $link['plid'] == $book_link['mlid']) {
  778. $data['link'] = $link;
  779. $data['below'] = '';
  780. $children[] = $data;
  781. }
  782. }
  783. if ($children) {
  784. $elements = menu_tree_output($children);
  785. return drupal_render($elements);
  786. }
  787. return '';
  788. }
  789. /**
  790. * Generates the corresponding menu name from a book ID.
  791. *
  792. * @param $bid
  793. * The book ID for which to make a menu name.
  794. *
  795. * @return
  796. * The menu name.
  797. */
  798. function book_menu_name($bid) {
  799. return 'book-toc-' . $bid;
  800. }
  801. /**
  802. * Implements hook_node_load().
  803. */
  804. function book_node_load($nodes, $types) {
  805. $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));
  806. foreach ($result as $record) {
  807. $nodes[$record['nid']]->book = $record;
  808. $nodes[$record['nid']]->book['href'] = $record['link_path'];
  809. $nodes[$record['nid']]->book['title'] = $record['link_title'];
  810. $nodes[$record['nid']]->book['options'] = unserialize($record['options']);
  811. }
  812. }
  813. /**
  814. * Implements hook_node_view().
  815. */
  816. function book_node_view($node, $view_mode) {
  817. if ($view_mode == 'full') {
  818. if (!empty($node->book['bid']) && empty($node->in_preview)) {
  819. $node->content['book_navigation'] = array(
  820. '#markup' => theme('book_navigation', array('book_link' => $node->book)),
  821. '#weight' => 100,
  822. );
  823. }
  824. }
  825. if ($view_mode != 'rss') {
  826. book_node_view_link($node, $view_mode);
  827. }
  828. }
  829. /**
  830. * Implements hook_page_alter().
  831. *
  832. * Adds the book menu to the list of menus used to build the active trail when
  833. * viewing a book page.
  834. */
  835. function book_page_alter(&$page) {
  836. if (($node = menu_get_object()) && !empty($node->book['bid'])) {
  837. $active_menus = menu_get_active_menu_names();
  838. $active_menus[] = $node->book['menu_name'];
  839. menu_set_active_menu_names($active_menus);
  840. }
  841. }
  842. /**
  843. * Implements hook_node_presave().
  844. */
  845. function book_node_presave($node) {
  846. // Always save a revision for non-administrators.
  847. if (!empty($node->book['bid']) && !user_access('administer nodes')) {
  848. $node->revision = 1;
  849. // The database schema requires a log message for every revision.
  850. if (!isset($node->log)) {
  851. $node->log = '';
  852. }
  853. }
  854. // Make sure a new node gets a new menu link.
  855. if (empty($node->nid)) {
  856. $node->book['mlid'] = NULL;
  857. }
  858. }
  859. /**
  860. * Implements hook_node_insert().
  861. */
  862. function book_node_insert($node) {
  863. if (!empty($node->book['bid'])) {
  864. if ($node->book['bid'] == 'new') {
  865. // New nodes that are their own book.
  866. $node->book['bid'] = $node->nid;
  867. }
  868. $node->book['nid'] = $node->nid;
  869. $node->book['menu_name'] = book_menu_name($node->book['bid']);
  870. _book_update_outline($node);
  871. }
  872. }
  873. /**
  874. * Implements hook_node_update().
  875. */
  876. function book_node_update($node) {
  877. if (!empty($node->book['bid'])) {
  878. if ($node->book['bid'] == 'new') {
  879. // New nodes that are their own book.
  880. $node->book['bid'] = $node->nid;
  881. }
  882. $node->book['nid'] = $node->nid;
  883. $node->book['menu_name'] = book_menu_name($node->book['bid']);
  884. _book_update_outline($node);
  885. }
  886. }
  887. /**
  888. * Implements hook_node_delete().
  889. */
  890. function book_node_delete($node) {
  891. if (!empty($node->book['bid'])) {
  892. if ($node->nid == $node->book['bid']) {
  893. // Handle deletion of a top-level post.
  894. $result = db_query("SELECT b.nid FROM {menu_links} ml INNER JOIN {book} b on b.mlid = ml.mlid WHERE ml.plid = :plid", array(
  895. ':plid' => $node->book['mlid']
  896. ));
  897. foreach ($result as $child) {
  898. $child_node = node_load($child->nid);
  899. $child_node->book['bid'] = $child_node->nid;
  900. _book_update_outline($child_node);
  901. }
  902. }
  903. menu_link_delete($node->book['mlid']);
  904. db_delete('book')
  905. ->condition('mlid', $node->book['mlid'])
  906. ->execute();
  907. drupal_static_reset('book_get_books');
  908. }
  909. }
  910. /**
  911. * Implements hook_node_prepare().
  912. */
  913. function book_node_prepare($node) {
  914. // Prepare defaults for the add/edit form.
  915. if (empty($node->book) && (user_access('add content to books') || user_access('administer book outlines'))) {
  916. $node->book = array();
  917. if (empty($node->nid) && isset($_GET['parent']) && is_numeric($_GET['parent'])) {
  918. // Handle "Add child page" links:
  919. $parent = book_link_load($_GET['parent']);
  920. if ($parent && $parent['access']) {
  921. $node->book['bid'] = $parent['bid'];
  922. $node->book['plid'] = $parent['mlid'];
  923. $node->book['menu_name'] = $parent['menu_name'];
  924. }
  925. }
  926. // Set defaults.
  927. $node->book += _book_link_defaults(!empty($node->nid) ? $node->nid : 'new');
  928. }
  929. else {
  930. if (isset($node->book['bid']) && !isset($node->book['original_bid'])) {
  931. $node->book['original_bid'] = $node->book['bid'];
  932. }
  933. }
  934. // Find the depth limit for the parent select.
  935. if (isset($node->book['bid']) && !isset($node->book['parent_depth_limit'])) {
  936. $node->book['parent_depth_limit'] = _book_parent_depth_limit($node->book);
  937. }
  938. }
  939. /**
  940. * Finds the depth limit for items in the parent select.
  941. *
  942. * @param $book_link
  943. * A fully loaded menu link that is part of the book hierarchy.
  944. *
  945. * @return
  946. * The depth limit for items in the parent select.
  947. */
  948. function _book_parent_depth_limit($book_link) {
  949. return MENU_MAX_DEPTH - 1 - (($book_link['mlid'] && $book_link['has_children']) ? menu_link_children_relative_depth($book_link) : 0);
  950. }
  951. /**
  952. * Implements hook_form_FORM_ID_alter() for node_delete_confirm().
  953. *
  954. * Alters the confirm form for a single node deletion.
  955. *
  956. * @see node_delete_confirm()
  957. */
  958. function book_form_node_delete_confirm_alter(&$form, $form_state) {
  959. $node = node_load($form['nid']['#value']);
  960. if (isset($node->book) && $node->book['has_children']) {
  961. $form['book_warning'] = array(
  962. '#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>',
  963. '#weight' => -10,
  964. );
  965. }
  966. }
  967. /**
  968. * Returns an array with default values for a book page's menu link.
  969. *
  970. * @param $nid
  971. * The ID of the node whose menu link is being created.
  972. *
  973. * @return
  974. * The default values for the menu link.
  975. */
  976. function _book_link_defaults($nid) {
  977. 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());
  978. }
  979. /**
  980. * Processes variables for book-all-books-block.tpl.php.
  981. *
  982. * All non-renderable elements are removed so that the template has full access
  983. * to the structured data but can also simply iterate over all elements and
  984. * render them (as in the default template).
  985. *
  986. * @param $variables
  987. * An associative array containing the following key:
  988. * - book_menus
  989. *
  990. * @see book-all-books-block.tpl.php
  991. */
  992. function template_preprocess_book_all_books_block(&$variables) {
  993. // Remove all non-renderable elements.
  994. $elements = $variables['book_menus'];
  995. $variables['book_menus'] = array();
  996. foreach (element_children($elements) as $index) {
  997. $variables['book_menus'][$index] = $elements[$index];
  998. }
  999. }
  1000. /**
  1001. * Processes variables for book-navigation.tpl.php.
  1002. *
  1003. * @param $variables
  1004. * An associative array containing the following key:
  1005. * - book_link
  1006. *
  1007. * @see book-navigation.tpl.php
  1008. */
  1009. function template_preprocess_book_navigation(&$variables) {
  1010. $book_link = $variables['book_link'];
  1011. // Provide extra variables for themers. Not needed by default.
  1012. $variables['book_id'] = $book_link['bid'];
  1013. $variables['book_title'] = check_plain($book_link['link_title']);
  1014. $variables['book_url'] = 'node/' . $book_link['bid'];
  1015. $variables['current_depth'] = $book_link['depth'];
  1016. $variables['tree'] = '';
  1017. if ($book_link['mlid']) {
  1018. $variables['tree'] = book_children($book_link);
  1019. if ($prev = book_prev($book_link)) {
  1020. $prev_href = url($prev['href']);
  1021. drupal_add_html_head_link(array('rel' => 'prev', 'href' => $prev_href));
  1022. $variables['prev_url'] = $prev_href;
  1023. $variables['prev_title'] = check_plain($prev['title']);
  1024. }
  1025. if ($book_link['plid'] && $parent = book_link_load($book_link['plid'])) {
  1026. $parent_href = url($parent['href']);
  1027. drupal_add_html_head_link(array('rel' => 'up', 'href' => $parent_href));
  1028. $variables['parent_url'] = $parent_href;
  1029. $variables['parent_title'] = check_plain($parent['title']);
  1030. }
  1031. if ($next = book_next($book_link)) {
  1032. $next_href = url($next['href']);
  1033. drupal_add_html_head_link(array('rel' => 'next', 'href' => $next_href));
  1034. $variables['next_url'] = $next_href;
  1035. $variables['next_title'] = check_plain($next['title']);
  1036. }
  1037. }
  1038. $variables['has_links'] = FALSE;
  1039. // Link variables to filter for values and set state of the flag variable.
  1040. $links = array('prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title');
  1041. foreach ($links as $link) {
  1042. if (isset($variables[$link])) {
  1043. // Flag when there is a value.
  1044. $variables['has_links'] = TRUE;
  1045. }
  1046. else {
  1047. // Set empty to prevent notices.
  1048. $variables[$link] = '';
  1049. }
  1050. }
  1051. }
  1052. /**
  1053. * Recursively processes and formats menu items for book_toc().
  1054. *
  1055. * This helper function recursively modifies the table of contents array for
  1056. * each item in the menu tree, ignoring items in the exclude array or at a depth
  1057. * greater than the limit. Truncates titles over thirty characters and appends
  1058. * an indentation string incremented by depth.
  1059. *
  1060. * @param $tree
  1061. * The data structure of the book's menu tree. Includes hidden links.
  1062. * @param $indent
  1063. * A string appended to each menu item title. Increments by '--' per depth
  1064. * level.
  1065. * @param $toc
  1066. * Reference to the table of contents array. This is modified in place, so the
  1067. * function does not have a return value.
  1068. * @param $exclude
  1069. * (optional) An array of menu link ID values. Any link whose menu link ID is
  1070. * in this array will be excluded (along with its children). Defaults to an
  1071. * empty array.
  1072. * @param $depth_limit
  1073. * Any link deeper than this value will be excluded (along with its children).
  1074. */
  1075. function _book_toc_recurse($tree, $indent, &$toc, $exclude, $depth_limit) {
  1076. foreach ($tree as $data) {
  1077. if ($data['link']['depth'] > $depth_limit) {
  1078. // Don't iterate through any links on this level.
  1079. break;
  1080. }
  1081. if (!in_array($data['link']['mlid'], $exclude)) {
  1082. $toc[$data['link']['mlid']] = $indent . ' ' . truncate_utf8($data['link']['title'], 30, TRUE, TRUE);
  1083. if ($data['below']) {
  1084. _book_toc_recurse($data['below'], $indent . '--', $toc, $exclude, $depth_limit);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. /**
  1090. * Returns an array of book pages in table of contents order.
  1091. *
  1092. * @param $bid
  1093. * The ID of the book whose pages are to be listed.
  1094. * @param $depth_limit
  1095. * Any link deeper than this value will be excluded (along with its children).
  1096. * @param $exclude
  1097. * Optional array of menu link ID values. Any link whose menu link ID is in
  1098. * this array will be excluded (along with its children).
  1099. *
  1100. * @return
  1101. * An array of (menu link ID, title) pairs for use as options for selecting a
  1102. * book page.
  1103. */
  1104. function book_toc($bid, $depth_limit, $exclude = array()) {
  1105. $tree = menu_tree_all_data(book_menu_name($bid));
  1106. $toc = array();
  1107. _book_toc_recurse($tree, '', $toc, $exclude, $depth_limit);
  1108. return $toc;
  1109. }
  1110. /**
  1111. * Processes variables for book-export-html.tpl.php.
  1112. *
  1113. * @param $variables
  1114. * An associative array containing the following keys:
  1115. * - title
  1116. * - contents
  1117. * - depth
  1118. *
  1119. * @see book-export-html.tpl.php
  1120. */
  1121. function template_preprocess_book_export_html(&$variables) {
  1122. global $base_url, $language;
  1123. $variables['title'] = check_plain($variables['title']);
  1124. $variables['base_url'] = $base_url;
  1125. $variables['language'] = $language;
  1126. $variables['language_rtl'] = ($language->direction == LANGUAGE_RTL);
  1127. $variables['head'] = drupal_get_html_head();
  1128. $variables['dir'] = $language->direction ? 'rtl' : 'ltr';
  1129. }
  1130. /**
  1131. * Traverses the book tree to build printable or exportable output.
  1132. *
  1133. * During the traversal, the $visit_func() callback is applied to each node and
  1134. * is called recursively for each child of the node (in weight, title order).
  1135. *
  1136. * @param $tree
  1137. * A subtree of the book menu hierarchy, rooted at the current page.
  1138. * @param $visit_func
  1139. * A function callback to be called upon visiting a node in the tree.
  1140. *
  1141. * @return
  1142. * The output generated in visiting each node.
  1143. */
  1144. function book_export_traverse($tree, $visit_func) {
  1145. $output = '';
  1146. foreach ($tree as $data) {
  1147. // Note- access checking is already performed when building the tree.
  1148. if ($node = node_load($data['link']['nid'], FALSE)) {
  1149. $children = '';
  1150. if ($data['below']) {
  1151. $children = book_export_traverse($data['below'], $visit_func);
  1152. }
  1153. if (function_exists($visit_func)) {
  1154. $output .= call_user_func($visit_func, $node, $children);
  1155. }
  1156. else {
  1157. // Use the default function.
  1158. $output .= book_node_export($node, $children);
  1159. }
  1160. }
  1161. }
  1162. return $output;
  1163. }
  1164. /**
  1165. * Generates printer-friendly HTML for a node.
  1166. *
  1167. * @param $node
  1168. * The node that will be output.
  1169. * @param $children
  1170. * (optional) All the rendered child nodes within the current node. Defaults
  1171. * to an empty string.
  1172. *
  1173. * @return
  1174. * The HTML generated for the given node.
  1175. *
  1176. * @see book_export_traverse()
  1177. */
  1178. function book_node_export($node, $children = '') {
  1179. $build = node_view($node, 'print');
  1180. unset($build['#theme']);
  1181. // @todo Rendering should happen in the template using render().
  1182. $node->rendered = drupal_render($build);
  1183. return theme('book_node_export_html', array('node' => $node, 'children' => $children));
  1184. }
  1185. /**
  1186. * Processes variables for book-node-export-html.tpl.php.
  1187. *
  1188. * @param $variables
  1189. * An associative array containing the following keys:
  1190. * - node
  1191. * - children
  1192. *
  1193. * @see book-node-export-html.tpl.php
  1194. */
  1195. function template_preprocess_book_node_export_html(&$variables) {
  1196. $variables['depth'] = $variables['node']->book['depth'];
  1197. $variables['title'] = check_plain($variables['node']->title);
  1198. $variables['content'] = $variables['node']->rendered;
  1199. }
  1200. /**
  1201. * Determine if a given node type is in the list of types allowed for books.
  1202. *
  1203. * @param $type
  1204. * A node type.
  1205. *
  1206. * @return
  1207. * A Boolean TRUE if the node type can be included in books; otherwise, FALSE.
  1208. */
  1209. function book_type_is_allowed($type) {
  1210. return in_array($type, variable_get('book_allowed_types', array('book')));
  1211. }
  1212. /**
  1213. * Implements hook_node_type_update().
  1214. *
  1215. * Updates the Book module's persistent variables if the machine-readable name
  1216. * of a node type is changed.
  1217. */
  1218. function book_node_type_update($type) {
  1219. if (!empty($type->old_type) && $type->old_type != $type->type) {
  1220. // Update the list of node types that are allowed to be added to books.
  1221. $allowed_types = variable_get('book_allowed_types', array('book'));
  1222. $key = array_search($type->old_type, $allowed_types);
  1223. if ($key !== FALSE) {
  1224. $allowed_types[$type->type] = $allowed_types[$key] ? $type->type : 0;
  1225. unset($allowed_types[$key]);
  1226. variable_set('book_allowed_types', $allowed_types);
  1227. }
  1228. // Update the setting for the "Add child page" link.
  1229. if (variable_get('book_child_type', 'book') == $type->old_type) {
  1230. variable_set('book_child_type', $type->type);
  1231. }
  1232. }
  1233. }
  1234. /**
  1235. * Gets a book menu link by its menu link ID.
  1236. *
  1237. * Like menu_link_load(), but adds additional data from the {book} table.
  1238. *
  1239. * Do not call when loading a node, since this function may call node_load().
  1240. *
  1241. * @param $mlid
  1242. * The menu link ID of the menu item.
  1243. *
  1244. * @return
  1245. * A menu link, with the link translated for rendering and data added from the
  1246. * {book} table. FALSE if there is an error.
  1247. */
  1248. function book_link_load($mlid) {
  1249. 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(
  1250. ':mlid' => $mlid,
  1251. ))->fetchAssoc()) {
  1252. _menu_link_translate($item);
  1253. return $item;
  1254. }
  1255. return FALSE;
  1256. }
  1257. /**
  1258. * Gets the data representing a subtree of the book hierarchy.
  1259. *
  1260. * The root of the subtree will be the link passed as a parameter, so the
  1261. * returned tree will contain this item and all its descendents in the menu
  1262. * tree.
  1263. *
  1264. * @param $link
  1265. * A fully loaded menu link.
  1266. *
  1267. * @return
  1268. * A subtree of menu links in an array, in the order they should be rendered.
  1269. */
  1270. function book_menu_subtree_data($link) {
  1271. $tree = &drupal_static(__FUNCTION__, array());
  1272. // Generate a cache ID (cid) specific for this $menu_name and $link.
  1273. $cid = 'links:' . $link['menu_name'] . ':subtree-cid:' . $link['mlid'];
  1274. if (!isset($tree[$cid])) {
  1275. $cache = cache_get($cid, 'cache_menu');
  1276. if ($cache && isset($cache->data)) {
  1277. // If the cache entry exists, it will just be the cid for the actual data.
  1278. // This avoids duplication of large amounts of data.
  1279. $cache = cache_get($cache->data, 'cache_menu');
  1280. if ($cache && isset($cache->data)) {
  1281. $data = $cache->data;
  1282. }
  1283. }
  1284. // If the subtree data was not in the cache, $data will be NULL.
  1285. if (!isset($data)) {
  1286. $query = db_select('menu_links', 'ml', array('fetch' => PDO::FETCH_ASSOC));
  1287. $query->join('menu_router', 'm', 'm.path = ml.router_path');
  1288. $query->join('book', 'b', 'ml.mlid = b.mlid');
  1289. $query->fields('b');
  1290. $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'));
  1291. $query->fields('ml');
  1292. $query->condition('menu_name', $link['menu_name']);
  1293. for ($i = 1; $i <= MENU_MAX_DEPTH && $link["p$i"]; ++$i) {
  1294. $query->condition("p$i", $link["p$i"]);
  1295. }
  1296. for ($i = 1; $i <= MENU_MAX_DEPTH; ++$i) {
  1297. $query->orderBy("p$i");
  1298. }
  1299. $links = array();
  1300. foreach ($query->execute() as $item) {
  1301. $links[] = $item;
  1302. }
  1303. $data['tree'] = menu_tree_data($links, array(), $link['depth']);
  1304. $data['node_links'] = array();
  1305. menu_tree_collect_node_links($data['tree'], $data['node_links']);
  1306. // Compute the real cid for book subtree data.
  1307. $tree_cid = 'links:' . $item['menu_name'] . ':subtree-data:' . hash('sha256', serialize($data));
  1308. // Cache the data, if it is not already in the cache.
  1309. if (!cache_get($tree_cid, 'cache_menu')) {
  1310. cache_set($tree_cid, $data, 'cache_menu');
  1311. }
  1312. // Cache the cid of the (shared) data using the menu and item-specific cid.
  1313. cache_set($cid, $tree_cid, 'cache_menu');
  1314. }
  1315. // Check access for the current user to each item in the tree.
  1316. menu_tree_check_access($data['tree'], $data['node_links']);
  1317. $tree[$cid] = $data['tree'];
  1318. }
  1319. return $tree[$cid];
  1320. }