book.module 47 KB

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