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 structure the pages of a site in a hierarchy or outline.

Functions

Namesort descending Description
book_block Implementation of hook_block().
book_build_active_trail Build an active trail to show in the breadcrumb.
book_children Format the menu links for the child pages of the current page.
book_export_traverse Traverse the book tree to build printable or exportable output.
book_form_alter Implementation of hook_form_alter(). Adds the book fieldset to the node form.
book_form_node_delete_confirm_alter Form altering function for the confirm form for a single node deletion.
book_get_books Returns an array of all books.
book_get_flat_menu Get the book menu tree for a page, and return it as a linear array.
book_help Implementation of hook_help().
book_init Implementation of hook_init(). Add's the book module's CSS.
book_link Implementation of hook_link().
book_link_load Like menu_link_load(), but adds additional data from the {book} table.
book_menu Implementation of hook_menu().
book_menu_name Generate the corresponding menu name from a book ID.
book_menu_subtree_data Get the data representing a subtree of the book hierarchy.
book_next Fetches the menu link for the next page of the book.
book_nodeapi Implementation of hook_nodeapi().
book_node_export Generates printer-friendly HTML for a node.
book_node_type Implementation of hook_node_type().
book_perm Implementation of hook_perm().
book_prev Fetches the menu link for the previous page of the book.
book_theme Implementation of 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 Update the bid for a page and its children when it is moved to a new book.
template_preprocess_book_export_html Process variables for book-export-html.tpl.php.
template_preprocess_book_navigation Process variables for book-navigation.tpl.php.
template_preprocess_book_node_export_html Process variables for book-node-export-html.tpl.php.
theme_book_title_link Generate the HTML output for a link to a book title when used as a block title.
_book_add_form_elements Build the common elements of the book form for the node and outline forms.
_book_flatten_menu Recursive helper function for book_get_flat_menu().
_book_link_defaults Return an array with default values for a book link.
_book_outline_access Menu item access callback - determine if the outline tab is accessible.
_book_outline_remove_access Menu item access callback - determine if the user can remove nodes from the outline.
_book_parent_depth_limit Find the depth limit for items in the parent select.
_book_parent_select Build the parent selection form element for the node form or outline tab
_book_toc_recurse A recursive helper function for book_toc().
_book_update_outline Common helper function to handles additions and updates to the book outline.

File

modules/book/book.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Allows users to structure the pages of a site in a hierarchy or outline.
  5. */
  6. /**
  7. * Implementation of hook_theme()
  8. */
  9. function book_theme() {
  10. return array(
  11. 'book_navigation' => array(
  12. 'arguments' => array('book_link' => NULL),
  13. 'template' => 'book-navigation',
  14. ),
  15. 'book_export_html' => array(
  16. 'arguments' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
  17. 'template' => 'book-export-html',
  18. ),
  19. 'book_admin_table' => array(
  20. 'arguments' => array('form' => NULL),
  21. ),
  22. 'book_title_link' => array(
  23. 'arguments' => array('link' => NULL),
  24. ),
  25. 'book_all_books_block' => array(
  26. 'arguments' => array('book_menus' => array()),
  27. 'template' => 'book-all-books-block',
  28. ),
  29. 'book_node_export_html' => array(
  30. 'arguments' => array('node' => NULL, 'children' => NULL),
  31. 'template' => 'book-node-export-html',
  32. ),
  33. );
  34. }
  35. /**
  36. * Implementation of hook_perm().
  37. */
  38. function book_perm() {
  39. return array('add content to books', 'administer book outlines', 'create new books', 'access printer-friendly version');
  40. }
  41. /**
  42. * Implementation of hook_link().
  43. */
  44. function book_link($type, $node = NULL, $teaser = FALSE) {
  45. $links = array();
  46. if ($type == 'node' && isset($node->book)) {
  47. if (!$teaser) {
  48. $child_type = variable_get('book_child_type', 'book');
  49. 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) {
  50. $links['book_add_child'] = array(
  51. 'title' => t('Add child page'),
  52. 'href' => "node/add/". str_replace('_', '-', $child_type),
  53. 'query' => "parent=". $node->book['mlid'],
  54. );
  55. }
  56. if (user_access('access printer-friendly version')) {
  57. $links['book_printer'] = array(
  58. 'title' => t('Printer-friendly version'),
  59. 'href' => 'book/export/html/'. $node->nid,
  60. 'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
  61. );
  62. }
  63. }
  64. }
  65. return $links;
  66. }
  67. /**
  68. * Implementation of hook_menu().
  69. */
  70. function book_menu() {
  71. $items['admin/content/book'] = array(
  72. 'title' => 'Books',
  73. 'description' => "Manage your site's book outlines.",
  74. 'page callback' => 'book_admin_overview',
  75. 'access arguments' => array('administer book outlines'),
  76. 'file' => 'book.admin.inc',
  77. );
  78. $items['admin/content/book/list'] = array(
  79. 'title' => 'List',
  80. 'type' => MENU_DEFAULT_LOCAL_TASK,
  81. );
  82. $items['admin/content/book/settings'] = array(
  83. 'title' => 'Settings',
  84. 'page callback' => 'drupal_get_form',
  85. 'page arguments' => array('book_admin_settings'),
  86. 'access arguments' => array('administer site configuration'),
  87. 'type' => MENU_LOCAL_TASK,
  88. 'weight' => 8,
  89. 'file' => 'book.admin.inc',
  90. );
  91. $items['admin/content/book/%node'] = array(
  92. 'title' => 'Re-order book pages and change titles',
  93. 'page callback' => 'drupal_get_form',
  94. 'page arguments' => array('book_admin_edit', 3),
  95. 'access callback' => '_book_outline_access',
  96. 'access arguments' => array(3),
  97. 'type' => MENU_CALLBACK,
  98. 'file' => 'book.admin.inc',
  99. );
  100. $items['book'] = array(
  101. 'title' => 'Books',
  102. 'page callback' => 'book_render',
  103. 'access arguments' => array('access content'),
  104. 'type' => MENU_SUGGESTED_ITEM,
  105. 'file' => 'book.pages.inc',
  106. );
  107. $items['book/export/%/%'] = array(
  108. 'page callback' => 'book_export',
  109. 'page arguments' => array(2, 3),
  110. 'access arguments' => array('access printer-friendly version'),
  111. 'type' => MENU_CALLBACK,
  112. 'file' => 'book.pages.inc',
  113. );
  114. $items['node/%node/outline'] = array(
  115. 'title' => 'Outline',
  116. 'page callback' => 'book_outline',
  117. 'page arguments' => array(1),
  118. 'access callback' => '_book_outline_access',
  119. 'access arguments' => array(1),
  120. 'type' => MENU_LOCAL_TASK,
  121. 'weight' => 2,
  122. 'file' => 'book.pages.inc',
  123. );
  124. $items['node/%node/outline/remove'] = array(
  125. 'title' => 'Remove from outline',
  126. 'page callback' => 'drupal_get_form',
  127. 'page arguments' => array('book_remove_form', 1),
  128. 'access callback' => '_book_outline_remove_access',
  129. 'access arguments' => array(1),
  130. 'type' => MENU_CALLBACK,
  131. 'file' => 'book.pages.inc',
  132. );
  133. $items['book/js/form'] = array(
  134. 'page callback' => 'book_form_update',
  135. 'access arguments' => array('access content'),
  136. 'type' => MENU_CALLBACK,
  137. 'file' => 'book.pages.inc',
  138. );
  139. return $items;
  140. }
  141. /**
  142. * Menu item access callback - determine if the outline tab is accessible.
  143. */
  144. function _book_outline_access($node) {
  145. return user_access('administer book outlines') && node_access('view', $node);
  146. }
  147. /**
  148. * Menu item access callback - determine if the user can remove nodes from the outline.
  149. */
  150. function _book_outline_remove_access($node) {
  151. return isset($node->book) && ($node->book['bid'] != $node->nid) && _book_outline_access($node);
  152. }
  153. /**
  154. * Implementation of hook_init(). Add's the book module's CSS.
  155. */
  156. function book_init() {
  157. drupal_add_css(drupal_get_path('module', 'book') .'/book.css');
  158. }
  159. /**
  160. * Implementation of hook_block().
  161. *
  162. * Displays the book table of contents in a block when the current page is a
  163. * single-node view of a book node.
  164. */
  165. function book_block($op = 'list', $delta = 0, $edit = array()) {
  166. $block = array();
  167. switch ($op) {
  168. case 'list':
  169. $block[0]['info'] = t('Book navigation');
  170. $block[0]['cache'] = BLOCK_CACHE_PER_PAGE | BLOCK_CACHE_PER_ROLE;
  171. return $block;
  172. case 'view':
  173. $current_bid = 0;
  174. if ($node = menu_get_object()) {
  175. $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
  176. }
  177. if (variable_get('book_block_mode', 'all pages') == 'all pages') {
  178. $block['subject'] = t('Book navigation');
  179. $book_menus = array();
  180. $pseudo_tree = array(0 => array('below' => FALSE));
  181. foreach (book_get_books() as $book_id => $book) {
  182. if ($book['bid'] == $current_bid) {
  183. // If the current page is a node associated with a book, the menu
  184. // needs to be retrieved.
  185. $book_menus[$book_id] = menu_tree_output(menu_tree_all_data($node->book['menu_name'], $node->book));
  186. }
  187. else {
  188. // Since we know we will only display a link to the top node, there
  189. // is no reason to run an additional menu tree query for each book.
  190. $book['in_active_trail'] = FALSE;
  191. $pseudo_tree[0]['link'] = $book;
  192. $book_menus[$book_id] = menu_tree_output($pseudo_tree);
  193. }
  194. }
  195. $block['content'] = theme('book_all_books_block', $book_menus);
  196. }
  197. elseif ($current_bid) {
  198. // Only display this block when the user is browsing a book.
  199. $title = db_result(db_query(db_rewrite_sql('SELECT n.title FROM {node} n WHERE n.nid = %d'), $node->book['bid']));
  200. // Only show the block if the user has view access for the top-level node.
  201. if ($title) {
  202. $tree = menu_tree_all_data($node->book['menu_name'], $node->book);
  203. // There should only be one element at the top level.
  204. $data = array_shift($tree);
  205. $block['subject'] = theme('book_title_link', $data['link']);
  206. $block['content'] = ($data['below']) ? menu_tree_output($data['below']) : '';
  207. }
  208. }
  209. return $block;
  210. case 'configure':
  211. $options = array(
  212. 'all pages' => t('Show block on all pages'),
  213. 'book pages' => t('Show block only on book pages'),
  214. );
  215. $form['book_block_mode'] = array(
  216. '#type' => 'radios',
  217. '#title' => t('Book navigation block display'),
  218. '#options' => $options,
  219. '#default_value' => variable_get('book_block_mode', 'all pages'),
  220. '#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."),
  221. );
  222. return $form;
  223. case 'save':
  224. variable_set('book_block_mode', $edit['book_block_mode']);
  225. break;
  226. }
  227. }
  228. /**
  229. * Generate the HTML output for a link to a book title when used as a block title.
  230. *
  231. * @ingroup themeable
  232. */
  233. function theme_book_title_link($link) {
  234. $link['options']['attributes']['class'] = 'book-title';
  235. return l($link['title'], $link['href'], $link['options']);
  236. }
  237. /**
  238. * Returns an array of all books.
  239. *
  240. * This list may be used for generating a list of all the books, or for building
  241. * the options for a form select.
  242. */
  243. function book_get_books() {
  244. static $all_books;
  245. if (!isset($all_books)) {
  246. $all_books = array();
  247. $result = db_query("SELECT DISTINCT(bid) FROM {book}");
  248. $nids = array();
  249. while ($book = db_fetch_array($result)) {
  250. $nids[] = $book['bid'];
  251. }
  252. if ($nids) {
  253. $result2 = db_query(db_rewrite_sql("SELECT n.type, n.title, b.*, ml.* FROM {book} b INNER JOIN {node} n on b.nid = n.nid INNER JOIN {menu_links} ml ON b.mlid = ml.mlid WHERE n.nid IN (". implode(',', $nids) .") AND n.status = 1 ORDER BY ml.weight, ml.link_title"));
  254. while ($link = db_fetch_array($result2)) {
  255. $link['href'] = $link['link_path'];
  256. $link['options'] = unserialize($link['options']);
  257. $all_books[$link['bid']] = $link;
  258. }
  259. }
  260. }
  261. return $all_books;
  262. }
  263. /**
  264. * Implementation of hook_form_alter(). Adds the book fieldset to the node form.
  265. *
  266. * @see book_pick_book_submit()
  267. * @see book_submit()
  268. */
  269. function book_form_alter(&$form, $form_state, $form_id) {
  270. if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
  271. // Add elements to the node form
  272. $node = $form['#node'];
  273. $access = user_access('administer book outlines');
  274. if (!$access) {
  275. if (user_access('add content to books') && ((!empty($node->book['mlid']) && !empty($node->nid)) || book_type_is_allowed($node->type))) {
  276. // Already in the book hierarchy or this node type is allowed
  277. $access = TRUE;
  278. }
  279. }
  280. if ($access) {
  281. _book_add_form_elements($form, $node);
  282. $form['book']['pick-book'] = array(
  283. '#type' => 'submit',
  284. '#value' => t('Change book (update list of parents)'),
  285. // Submit the node form so the parent select options get updated.
  286. // This is typically only used when JS is disabled. Since the parent options
  287. // won't be changed via AJAX, a button is provided in the node form to submit
  288. // the form and generate options in the parent select corresponding to the
  289. // selected book. This is similar to what happens during a node preview.
  290. '#submit' => array('node_form_submit_build_node'),
  291. '#weight' => 20,
  292. );
  293. }
  294. }
  295. }
  296. /**
  297. * Build the parent selection form element for the node form or outline tab
  298. *
  299. * This function is also called when generating a new set of options during the
  300. * AJAX callback, so an array is returned that can be used to replace an existing
  301. * form element.
  302. */
  303. function _book_parent_select($book_link) {
  304. if (variable_get('menu_override_parent_selector', FALSE)) {
  305. return array();
  306. }
  307. // Offer a message or a drop-down to choose a different parent page.
  308. $form = array(
  309. '#type' => 'hidden',
  310. '#value' => -1,
  311. '#prefix' => '<div id="edit-book-plid-wrapper">',
  312. '#suffix' => '</div>',
  313. );
  314. if ($book_link['nid'] === $book_link['bid']) {
  315. // This is a book - at the top level.
  316. if ($book_link['original_bid'] === $book_link['bid']) {
  317. $form['#prefix'] .= '<em>'. t('This is the top-level page in this book.') .'</em>';
  318. }
  319. else {
  320. $form['#prefix'] .= '<em>'. t('This will be the top-level page in this book.') .'</em>';
  321. }
  322. }
  323. elseif (!$book_link['bid']) {
  324. $form['#prefix'] .= '<em>'. t('No book selected.') .'</em>';
  325. }
  326. else {
  327. $form = array(
  328. '#type' => 'select',
  329. '#title' => t('Parent item'),
  330. '#default_value' => $book_link['plid'],
  331. '#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)),
  332. '#options' => book_toc($book_link['bid'], array($book_link['mlid']), $book_link['parent_depth_limit']),
  333. '#attributes' => array('class' => 'book-title-select'),
  334. );
  335. }
  336. return $form;
  337. }
  338. /**
  339. * Build the common elements of the book form for the node and outline forms.
  340. */
  341. function _book_add_form_elements(&$form, $node) {
  342. // Need this for AJAX.
  343. $form['#cache'] = TRUE;
  344. drupal_add_js("if (Drupal.jsEnabled) { $(document).ready(function() { $('#edit-book-pick-book').css('display', 'none'); }); }", 'inline');
  345. $form['book'] = array(
  346. '#type' => 'fieldset',
  347. '#title' => t('Book outline'),
  348. '#weight' => 10,
  349. '#collapsible' => TRUE,
  350. '#collapsed' => TRUE,
  351. '#tree' => TRUE,
  352. '#attributes' => array('class' => 'book-outline-form'),
  353. );
  354. foreach (array('menu_name', 'mlid', 'nid', 'router_path', 'has_children', 'options', 'module', 'original_bid', 'parent_depth_limit') as $key) {
  355. $form['book'][$key] = array(
  356. '#type' => 'value',
  357. '#value' => $node->book[$key],
  358. );
  359. }
  360. $form['book']['plid'] = _book_parent_select($node->book);
  361. $form['book']['weight'] = array(
  362. '#type' => 'weight',
  363. '#title' => t('Weight'),
  364. '#default_value' => $node->book['weight'],
  365. '#delta' => 15,
  366. '#weight' => 5,
  367. '#description' => t('Pages at a given level are ordered first by weight and then by title.'),
  368. );
  369. $options = array();
  370. $nid = isset($node->nid) ? $node->nid : 'new';
  371. if (isset($node->nid) && ($nid == $node->book['original_bid']) && ($node->book['parent_depth_limit'] == 0)) {
  372. // This is the top level node in a maximum depth book and thus cannot be moved.
  373. $options[$node->nid] = $node->title;
  374. }
  375. else {
  376. foreach (book_get_books() as $book) {
  377. $options[$book['nid']] = $book['title'];
  378. }
  379. }
  380. if (user_access('create new books') && ($nid == 'new' || ($nid != $node->book['original_bid']))) {
  381. // The node can become a new book, if it is not one already.
  382. $options = array($nid => '<'. t('create a new book') .'>') + $options;
  383. }
  384. if (!$node->book['mlid']) {
  385. // The node is not currently in a the hierarchy.
  386. $options = array(0 => '<'. t('none') .'>') + $options;
  387. }
  388. // Add a drop-down to select the destination book.
  389. $form['book']['bid'] = array(
  390. '#type' => 'select',
  391. '#title' => t('Book'),
  392. '#default_value' => $node->book['bid'],
  393. '#options' => $options,
  394. '#access' => (bool)$options,
  395. '#description' => t('Your page will be a part of the selected book.'),
  396. '#weight' => -5,
  397. '#attributes' => array('class' => 'book-title-select'),
  398. '#ahah' => array(
  399. 'path' => 'book/js/form',
  400. 'wrapper' => 'edit-book-plid-wrapper',
  401. 'effect' => 'slide',
  402. ),
  403. );
  404. }
  405. /**
  406. * Common helper function to handles additions and updates to the book outline.
  407. *
  408. * Performs all additions and updates to the book outline through node addition,
  409. * node editing, node deletion, or the outline tab.
  410. */
  411. function _book_update_outline(&$node) {
  412. if (empty($node->book['bid'])) {
  413. return FALSE;
  414. }
  415. $new = empty($node->book['mlid']);
  416. $node->book['link_path'] = 'node/'. $node->nid;
  417. $node->book['link_title'] = $node->title;
  418. $node->book['parent_mismatch'] = FALSE; // The normal case.
  419. if ($node->book['bid'] == $node->nid) {
  420. $node->book['plid'] = 0;
  421. $node->book['menu_name'] = book_menu_name($node->nid);
  422. }
  423. else {
  424. // Check in case the parent is not is this book; the book takes precedence.
  425. if (!empty($node->book['plid'])) {
  426. $parent = db_fetch_array(db_query("SELECT * FROM {book} WHERE mlid = %d", $node->book['plid']));
  427. }
  428. if (empty($node->book['plid']) || !$parent || $parent['bid'] != $node->book['bid']) {
  429. $node->book['plid'] = db_result(db_query("SELECT mlid FROM {book} WHERE nid = %d", $node->book['bid']));
  430. $node->book['parent_mismatch'] = TRUE; // Likely when JS is disabled.
  431. }
  432. }
  433. if (menu_link_save($node->book)) {
  434. if ($new) {
  435. // Insert new.
  436. db_query("INSERT INTO {book} (nid, mlid, bid) VALUES (%d, %d, %d)", $node->nid, $node->book['mlid'], $node->book['bid']);
  437. }
  438. else {
  439. if ($node->book['bid'] != db_result(db_query("SELECT bid FROM {book} WHERE nid = %d", $node->nid))) {
  440. // Update the bid for this page and all children.
  441. book_update_bid($node->book);
  442. }
  443. }
  444. return TRUE;
  445. }
  446. // Failed to save the menu link
  447. return FALSE;
  448. }
  449. /**
  450. * Update the bid for a page and its children when it is moved to a new book.
  451. *
  452. * @param $book_link
  453. * A fully loaded menu link that is part of the book hierarchy.
  454. */
  455. function book_update_bid($book_link) {
  456. for ($i = 1; $i <= MENU_MAX_DEPTH && $book_link["p$i"]; $i++) {
  457. $match[] = "p$i = %d";
  458. $args[] = $book_link["p$i"];
  459. }
  460. $result = db_query("SELECT mlid FROM {menu_links} WHERE ". implode(' AND ', $match), $args);
  461. $mlids = array();
  462. while ($a = db_fetch_array($result)) {
  463. $mlids[] = $a['mlid'];
  464. }
  465. if ($mlids) {
  466. db_query("UPDATE {book} SET bid = %d WHERE mlid IN (". implode(',', $mlids) .")", $book_link['bid']);
  467. }
  468. }
  469. /**
  470. * Get the book menu tree for a page, and return it as a linear array.
  471. *
  472. * @param $book_link
  473. * A fully loaded menu link that is part of the book hierarchy.
  474. * @return
  475. * A linear array of menu links in the order that the links are shown in the
  476. * menu, so the previous and next pages are the elements before and after the
  477. * element corresponding to $node. The children of $node (if any) will come
  478. * immediately after it in the array.
  479. */
  480. function book_get_flat_menu($book_link) {
  481. static $flat = array();
  482. if (!isset($flat[$book_link['mlid']])) {
  483. // Call menu_tree_all_data() to take advantage of the menu system's caching.
  484. $tree = menu_tree_all_data($book_link['menu_name'], $book_link);
  485. $flat[$book_link['mlid']] = array();
  486. _book_flatten_menu($tree, $flat[$book_link['mlid']]);
  487. }
  488. return $flat[$book_link['mlid']];
  489. }
  490. /**
  491. * Recursive helper function for book_get_flat_menu().
  492. */
  493. function _book_flatten_menu($tree, &$flat) {
  494. foreach ($tree as $data) {
  495. if (!$data['link']['hidden']) {
  496. $flat[$data['link']['mlid']] = $data['link'];
  497. if ($data['below']) {
  498. _book_flatten_menu($data['below'], $flat);
  499. }
  500. }
  501. }
  502. }
  503. /**
  504. * Fetches the menu link for the previous page of the book.
  505. */
  506. function book_prev($book_link) {
  507. // If the parent is zero, we are at the start of a book.
  508. if ($book_link['plid'] == 0) {
  509. return NULL;
  510. }
  511. $flat = book_get_flat_menu($book_link);
  512. // Assigning the array to $flat resets the array pointer for use with each().
  513. $curr = NULL;
  514. do {
  515. $prev = $curr;
  516. list($key, $curr) = each($flat);
  517. } while ($key && $key != $book_link['mlid']);
  518. if ($key == $book_link['mlid']) {
  519. // The previous page in the book may be a child of the previous visible link.
  520. if ($prev['depth'] == $book_link['depth'] && $prev['has_children']) {
  521. // The subtree will have only one link at the top level - get its data.
  522. $data = array_shift(book_menu_subtree_data($prev));
  523. // The link of interest is the last child - iterate to find the deepest one.
  524. while ($data['below']) {
  525. $data = end($data['below']);
  526. }
  527. return $data['link'];
  528. }
  529. else {
  530. return $prev;
  531. }
  532. }
  533. }
  534. /**
  535. * Fetches the menu link for the next page of the book.
  536. */
  537. function book_next($book_link) {
  538. $flat = book_get_flat_menu($book_link);
  539. // Assigning the array to $flat resets the array pointer for use with each().
  540. do {
  541. list($key, $curr) = each($flat);
  542. } while ($key && $key != $book_link['mlid']);
  543. if ($key == $book_link['mlid']) {
  544. return current($flat);
  545. }
  546. }
  547. /**
  548. * Format the menu links for the child pages of the current page.
  549. */
  550. function book_children($book_link) {
  551. $flat = book_get_flat_menu($book_link);
  552. $children = array();
  553. if ($book_link['has_children']) {
  554. // Walk through the array until we find the current page.
  555. do {
  556. $link = array_shift($flat);
  557. } while ($link && ($link['mlid'] != $book_link['mlid']));
  558. // Continue though the array and collect the links whose parent is this page.
  559. while (($link = array_shift($flat)) && $link['plid'] == $book_link['mlid']) {
  560. $data['link'] = $link;
  561. $data['below'] = '';
  562. $children[] = $data;
  563. }
  564. }
  565. return $children ? menu_tree_output($children) : '';
  566. }
  567. /**
  568. * Generate the corresponding menu name from a book ID.
  569. */
  570. function book_menu_name($bid) {
  571. return 'book-toc-'. $bid;
  572. }
  573. /**
  574. * Build an active trail to show in the breadcrumb.
  575. */
  576. function book_build_active_trail($book_link) {
  577. static $trail;
  578. if (!isset($trail)) {
  579. $trail = array();
  580. $trail[] = array('title' => t('Home'), 'href' => '<front>', 'localized_options' => array());
  581. $tree = menu_tree_all_data($book_link['menu_name'], $book_link);
  582. $curr = array_shift($tree);
  583. while ($curr) {
  584. if ($curr['link']['href'] == $book_link['href']) {
  585. $trail[] = $curr['link'];
  586. $curr = FALSE;
  587. }
  588. else {
  589. if ($curr['below'] && $curr['link']['in_active_trail']) {
  590. $trail[] = $curr['link'];
  591. $tree = $curr['below'];
  592. }
  593. $curr = array_shift($tree);
  594. }
  595. }
  596. }
  597. return $trail;
  598. }
  599. /**
  600. * Implementation of hook_nodeapi().
  601. *
  602. * Appends book navigation to all nodes in the book, and handles book outline
  603. * insertions and updates via the node form.
  604. */
  605. function book_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  606. switch ($op) {
  607. case 'load':
  608. // Note - we cannot use book_link_load() because it will call node_load()
  609. $info['book'] = db_fetch_array(db_query('SELECT * FROM {book} b INNER JOIN {menu_links} ml ON b.mlid = ml.mlid WHERE b.nid = %d', $node->nid));
  610. if ($info['book']) {
  611. $info['book']['href'] = $info['book']['link_path'];
  612. $info['book']['title'] = $info['book']['link_title'];
  613. $info['book']['options'] = unserialize($info['book']['options']);
  614. return $info;
  615. }
  616. break;
  617. case 'view':
  618. if (!$teaser) {
  619. if (!empty($node->book['bid']) && $node->build_mode == NODE_BUILD_NORMAL) {
  620. $node->content['book_navigation'] = array(
  621. '#value' => theme('book_navigation', $node->book),
  622. '#weight' => 100,
  623. );
  624. if ($page) {
  625. menu_set_active_trail(book_build_active_trail($node->book));
  626. menu_set_active_menu_name($node->book['menu_name']);
  627. }
  628. }
  629. }
  630. break;
  631. case 'presave':
  632. // Always save a revision for non-administrators.
  633. if (!empty($node->book['bid']) && !user_access('administer nodes')) {
  634. $node->revision = 1;
  635. }
  636. // Make sure a new node gets a new menu link.
  637. if (empty($node->nid)) {
  638. $node->book['mlid'] = NULL;
  639. }
  640. break;
  641. case 'insert':
  642. case 'update':
  643. if (!empty($node->book['bid'])) {
  644. if ($node->book['bid'] == 'new') {
  645. // New nodes that are their own book.
  646. $node->book['bid'] = $node->nid;
  647. }
  648. $node->book['nid'] = $node->nid;
  649. $node->book['menu_name'] = book_menu_name($node->book['bid']);
  650. _book_update_outline($node);
  651. }
  652. break;
  653. case 'delete':
  654. if (!empty($node->book['bid'])) {
  655. if ($node->nid == $node->book['bid']) {
  656. // Handle deletion of a top-level post.
  657. $result = db_query("SELECT b.nid FROM {menu_links} ml INNER JOIN {book} b on b.mlid = ml.mlid WHERE ml.plid = %d", $node->book['mlid']);
  658. while ($child = db_fetch_array($result)) {
  659. $child_node = node_load($child['nid']);
  660. $child_node->book['bid'] = $child_node->nid;
  661. _book_update_outline($child_node);
  662. }
  663. }
  664. menu_link_delete($node->book['mlid']);
  665. db_query('DELETE FROM {book} WHERE mlid = %d', $node->book['mlid']);
  666. }
  667. break;
  668. case 'prepare':
  669. // Prepare defaults for the add/edit form.
  670. if (empty($node->book) && (user_access('add content to books') || user_access('administer book outlines'))) {
  671. $node->book = array();
  672. if (empty($node->nid) && isset($_GET['parent']) && is_numeric($_GET['parent'])) {
  673. // Handle "Add child page" links:
  674. $parent = book_link_load($_GET['parent']);
  675. if ($parent && $parent['access']) {
  676. $node->book['bid'] = $parent['bid'];
  677. $node->book['plid'] = $parent['mlid'];
  678. $node->book['menu_name'] = $parent['menu_name'];
  679. }
  680. }
  681. // Set defaults.
  682. $node->book += _book_link_defaults(!empty($node->nid) ? $node->nid : 'new');
  683. }
  684. else {
  685. if (isset($node->book['bid']) && !isset($node->book['original_bid'])) {
  686. $node->book['original_bid'] = $node->book['bid'];
  687. }
  688. }
  689. // Find the depth limit for the parent select.
  690. if (isset($node->book['bid']) && !isset($node->book['parent_depth_limit'])) {
  691. $node->book['parent_depth_limit'] = _book_parent_depth_limit($node->book);
  692. }
  693. break;
  694. }
  695. }
  696. /**
  697. * Find the depth limit for items in the parent select.
  698. */
  699. function _book_parent_depth_limit($book_link) {
  700. return MENU_MAX_DEPTH - 1 - (($book_link['mlid'] && $book_link['has_children']) ? menu_link_children_relative_depth($book_link) : 0);
  701. }
  702. /**
  703. * Form altering function for the confirm form for a single node deletion.
  704. */
  705. function book_form_node_delete_confirm_alter(&$form, $form_state) {
  706. $node = node_load($form['nid']['#value']);
  707. if (isset($node->book) && $node->book['has_children']) {
  708. $form['book_warning'] = array(
  709. '#value' => '<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>',
  710. '#weight' => -10,
  711. );
  712. }
  713. }
  714. /**
  715. * Return an array with default values for a book link.
  716. */
  717. function _book_link_defaults($nid) {
  718. 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());
  719. }
  720. /**
  721. * Process variables for book-navigation.tpl.php.
  722. *
  723. * The $variables array contains the following arguments:
  724. * - $book_link
  725. *
  726. * @see book-navigation.tpl.php
  727. */
  728. function template_preprocess_book_navigation(&$variables) {
  729. $book_link = $variables['book_link'];
  730. // Provide extra variables for themers. Not needed by default.
  731. $variables['book_id'] = $book_link['bid'];
  732. $variables['book_title'] = check_plain($book_link['link_title']);
  733. $variables['book_url'] = 'node/'. $book_link['bid'];
  734. $variables['current_depth'] = $book_link['depth'];
  735. $variables['tree'] = '';
  736. if ($book_link['mlid']) {
  737. $variables['tree'] = book_children($book_link);
  738. if ($prev = book_prev($book_link)) {
  739. $prev_href = url($prev['href']);
  740. drupal_add_link(array('rel' => 'prev', 'href' => $prev_href));
  741. $variables['prev_url'] = $prev_href;
  742. $variables['prev_title'] = check_plain($prev['title']);
  743. }
  744. if ($book_link['plid'] && $parent = book_link_load($book_link['plid'])) {
  745. $parent_href = url($parent['href']);
  746. drupal_add_link(array('rel' => 'up', 'href' => $parent_href));
  747. $variables['parent_url'] = $parent_href;
  748. $variables['parent_title'] = check_plain($parent['title']);
  749. }
  750. if ($next = book_next($book_link)) {
  751. $next_href = url($next['href']);
  752. drupal_add_link(array('rel' => 'next', 'href' => $next_href));
  753. $variables['next_url'] = $next_href;
  754. $variables['next_title'] = check_plain($next['title']);
  755. }
  756. }
  757. $variables['has_links'] = FALSE;
  758. // Link variables to filter for values and set state of the flag variable.
  759. $links = array('prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title');
  760. foreach ($links as $link) {
  761. if (isset($variables[$link])) {
  762. // Flag when there is a value.
  763. $variables['has_links'] = TRUE;
  764. }
  765. else {
  766. // Set empty to prevent notices.
  767. $variables[$link] = '';
  768. }
  769. }
  770. }
  771. /**
  772. * A recursive helper function for book_toc().
  773. */
  774. function _book_toc_recurse($tree, $indent, &$toc, $exclude, $depth_limit) {
  775. foreach ($tree as $data) {
  776. if ($data['link']['depth'] > $depth_limit) {
  777. // Don't iterate through any links on this level.
  778. break;
  779. }
  780. if (!in_array($data['link']['mlid'], $exclude)) {
  781. $toc[$data['link']['mlid']] = $indent .' '. truncate_utf8($data['link']['title'], 30, TRUE, TRUE);
  782. if ($data['below']) {
  783. _book_toc_recurse($data['below'], $indent .'--', $toc, $exclude, $depth_limit);
  784. }
  785. }
  786. }
  787. }
  788. /**
  789. * Returns an array of book pages in table of contents order.
  790. *
  791. * @param $bid
  792. * The ID of the book whose pages are to be listed.
  793. * @param $exclude
  794. * Optional array of mlid values. Any link whose mlid is in this array
  795. * will be excluded (along with its children).
  796. * @param $depth_limit
  797. * Any link deeper than this value will be excluded (along with its children).
  798. * @return
  799. * An array of mlid, title pairs for use as options for selecting a book page.
  800. */
  801. function book_toc($bid, $exclude = array(), $depth_limit) {
  802. $tree = menu_tree_all_data(book_menu_name($bid));
  803. $toc = array();
  804. _book_toc_recurse($tree, '', $toc, $exclude, $depth_limit);
  805. return $toc;
  806. }
  807. /**
  808. * Process variables for book-export-html.tpl.php.
  809. *
  810. * The $variables array contains the following arguments:
  811. * - $title
  812. * - $contents
  813. * - $depth
  814. *
  815. * @see book-export-html.tpl.php
  816. */
  817. function template_preprocess_book_export_html(&$variables) {
  818. global $base_url, $language;
  819. $variables['title'] = check_plain($variables['title']);
  820. $variables['base_url'] = $base_url;
  821. $variables['language'] = $language;
  822. $variables['language_rtl'] = ($language->direction == LANGUAGE_RTL);
  823. $variables['head'] = drupal_get_html_head();
  824. }
  825. /**
  826. * Traverse the book tree to build printable or exportable output.
  827. *
  828. * During the traversal, the $visit_func() callback is applied to each
  829. * node, and is called recursively for each child of the node (in weight,
  830. * title order).
  831. *
  832. * @param $tree
  833. * A subtree of the book menu hierarchy, rooted at the current page.
  834. * @param $visit_func
  835. * A function callback to be called upon visiting a node in the tree.
  836. * @return
  837. * The output generated in visiting each node.
  838. */
  839. function book_export_traverse($tree, $visit_func) {
  840. $output = '';
  841. foreach ($tree as $data) {
  842. // Note- access checking is already performed when building the tree.
  843. if ($node = node_load($data['link']['nid'], FALSE)) {
  844. $children = '';
  845. if ($data['below']) {
  846. $children = book_export_traverse($data['below'], $visit_func);
  847. }
  848. if (function_exists($visit_func)) {
  849. $output .= call_user_func($visit_func, $node, $children);
  850. }
  851. else {
  852. // Use the default function.
  853. $output .= book_node_export($node, $children);
  854. }
  855. }
  856. }
  857. return $output;
  858. }
  859. /**
  860. * Generates printer-friendly HTML for a node.
  861. *
  862. * @see book_export_traverse()
  863. *
  864. * @param $node
  865. * The node to generate output for.
  866. * @param $children
  867. * All the rendered child nodes within the current node.
  868. * @return
  869. * The HTML generated for the given node.
  870. */
  871. function book_node_export($node, $children = '') {
  872. $node->build_mode = NODE_BUILD_PRINT;
  873. $node = node_build_content($node, FALSE, FALSE);
  874. $node->body = drupal_render($node->content);
  875. return theme('book_node_export_html', $node, $children);
  876. }
  877. /**
  878. * Process variables for book-node-export-html.tpl.php.
  879. *
  880. * The $variables array contains the following arguments:
  881. * - $node
  882. * - $children
  883. *
  884. * @see book-node-export-html.tpl.php
  885. */
  886. function template_preprocess_book_node_export_html(&$variables) {
  887. $variables['depth'] = $variables['node']->book['depth'];
  888. $variables['title'] = check_plain($variables['node']->title);
  889. $variables['content'] = $variables['node']->body;
  890. }
  891. /**
  892. * Determine if a given node type is in the list of types allowed for books.
  893. */
  894. function book_type_is_allowed($type) {
  895. return in_array($type, variable_get('book_allowed_types', array('book')));
  896. }
  897. /**
  898. * Implementation of hook_node_type().
  899. *
  900. * Update book module's persistent variables if the machine-readable name of a
  901. * node type is changed.
  902. */
  903. function book_node_type($op, $type) {
  904. switch ($op) {
  905. case 'update':
  906. if (!empty($type->old_type) && $type->old_type != $type->type) {
  907. // Update the list of node types that are allowed to be added to books.
  908. $allowed_types = variable_get('book_allowed_types', array('book'));
  909. $key = array_search($type->old_type, $allowed_types);
  910. if ($key !== FALSE) {
  911. $allowed_types[$type->type] = $allowed_types[$key] ? $type->type : 0;
  912. unset($allowed_types[$key]);
  913. variable_set('book_allowed_types', $allowed_types);
  914. }
  915. // Update the setting for the "Add child page" link.
  916. if (variable_get('book_child_type', 'book') == $type->old_type) {
  917. variable_set('book_child_type', $type->type);
  918. }
  919. }
  920. break;
  921. }
  922. }
  923. /**
  924. * Implementation of hook_help().
  925. */
  926. function book_help($path, $arg) {
  927. switch ($path) {
  928. case 'admin/help#book':
  929. $output = '<p>'. t('The book module is suited for creating structured, multi-page hypertexts such as site resource guides, manuals, and Frequently Asked Questions (FAQs). It permits a document to have chapters, sections, subsections, etc. Authors with suitable permissions can add pages to a collaborative book, placing them into the existing document by adding them to a table of contents menu.') .'</p>';
  930. $output .= '<p>'. t('Pages in the book hierarchy have navigation elements at the bottom of the page for moving through the text. These links lead to the previous and next pages in the book, and to the level above the current page in the book\'s structure. More comprehensive navigation may be provided by enabling the <em>book navigation block</em> on the <a href="@admin-block">blocks administration page</a>.', array('@admin-block' => url('admin/build/block'))) .'</p>';
  931. $output .= '<p>'. t('Users can select the <em>printer-friendly version</em> link visible at the bottom of a book page to generate a printer-friendly display of the page and all of its subsections. ') .'</p>';
  932. $output .= '<p>'. t("Users with the <em>administer book outlines</em> permission can add a post of any content type to a book, by selecting the appropriate book while editing the post or by using the interface available on the post's <em>outline</em> tab.") .'</p>';
  933. $output .= '<p>'. t('Administrators can view a list of all books on the <a href="@admin-node-book">book administration page</a>. The <em>Outline</em> page for each book allows section titles to be edited or rearranged.', array('@admin-node-book' => url('admin/content/book'))) .'</p>';
  934. $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@book">Book module</a>.', array('@book' => 'http://drupal.org/handbook/modules/book/')) .'</p>';
  935. return $output;
  936. case 'admin/content/book':
  937. return '<p>'. t('The book module offers a means to organize a collection of related posts, collectively known as a book. When viewed, these posts automatically display links to adjacent book pages, providing a simple navigation system for creating and reviewing structured content.') .'</p>';
  938. case 'node/%/outline':
  939. return '<p>'. t('The outline feature allows you to include posts 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>';
  940. }
  941. }
  942. /**
  943. * Like menu_link_load(), but adds additional data from the {book} table.
  944. *
  945. * Do not call when loading a node, since this function may call node_load().
  946. */
  947. function book_link_load($mlid) {
  948. if ($item = db_fetch_array(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 = %d", $mlid))) {
  949. _menu_link_translate($item);
  950. return $item;
  951. }
  952. return FALSE;
  953. }
  954. /**
  955. * Get the data representing a subtree of the book hierarchy.
  956. *
  957. * The root of the subtree will be the link passed as a parameter, so the
  958. * returned tree will contain this item and all its descendents in the menu tree.
  959. *
  960. * @param $item
  961. * A fully loaded menu link.
  962. * @return
  963. * An subtree of menu links in an array, in the order they should be rendered.
  964. */
  965. function book_menu_subtree_data($item) {
  966. static $tree = array();
  967. // Generate a cache ID (cid) specific for this $menu_name and $item.
  968. $cid = 'links:'. $item['menu_name'] .':subtree-cid:'. $item['mlid'];
  969. if (!isset($tree[$cid])) {
  970. $cache = cache_get($cid, 'cache_menu');
  971. if ($cache && isset($cache->data)) {
  972. // If the cache entry exists, it will just be the cid for the actual data.
  973. // This avoids duplication of large amounts of data.
  974. $cache = cache_get($cache->data, 'cache_menu');
  975. if ($cache && isset($cache->data)) {
  976. $data = $cache->data;
  977. }
  978. }
  979. // If the subtree data was not in the cache, $data will be NULL.
  980. if (!isset($data)) {
  981. $match = array("menu_name = '%s'");
  982. $args = array($item['menu_name']);
  983. $i = 1;
  984. while ($i <= MENU_MAX_DEPTH && $item["p$i"]) {
  985. $match[] = "p$i = %d";
  986. $args[] = $item["p$i"];
  987. $i++;
  988. }
  989. $sql = "
  990. SELECT b.*, m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, ml.*
  991. FROM {menu_links} ml INNER JOIN {menu_router} m ON m.path = ml.router_path
  992. INNER JOIN {book} b ON ml.mlid = b.mlid
  993. WHERE ". implode(' AND ', $match) ."
  994. ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC";
  995. $data['tree'] = menu_tree_data(db_query($sql, $args), array(), $item['depth']);
  996. $data['node_links'] = array();
  997. menu_tree_collect_node_links($data['tree'], $data['node_links']);
  998. // Compute the real cid for book subtree data.
  999. $tree_cid = 'links:'. $item['menu_name'] .':subtree-data:'. md5(serialize($data));
  1000. // Cache the data, if it is not already in the cache.
  1001. if (!cache_get($tree_cid, 'cache_menu')) {
  1002. cache_set($tree_cid, $data, 'cache_menu');
  1003. }
  1004. // Cache the cid of the (shared) data using the menu and item-specific cid.
  1005. cache_set($cid, $tree_cid, 'cache_menu');
  1006. }
  1007. // Check access for the current user to each item in the tree.
  1008. menu_tree_check_access($data['tree'], $data['node_links']);
  1009. $tree[$cid] = $data['tree'];
  1010. }
  1011. return $tree[$cid];
  1012. }