book.module

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

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

Functions & methods

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