MDL-81326 mod_book: Deprecate book_get_nav_classes
[moodle.git] / mod / book / lib.php
blob32254d72ed578d40b134aadae8c2e6bc459bbabb
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Book module core interaction API
20 * @package mod_book
21 * @copyright 2004-2011 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die;
27 require_once(__DIR__ . '/deprecatedlib.php');
29 /**
30 * Returns list of available numbering types
31 * @return array
33 function book_get_numbering_types() {
34 global $CFG; // required for the include
36 require_once(__DIR__.'/locallib.php');
38 return array (
39 BOOK_NUM_NONE => get_string('numbering0', 'mod_book'),
40 BOOK_NUM_NUMBERS => get_string('numbering1', 'mod_book'),
41 BOOK_NUM_BULLETS => get_string('numbering2', 'mod_book'),
42 BOOK_NUM_INDENTED => get_string('numbering3', 'mod_book')
46 /**
47 * Add book instance.
49 * @param stdClass $data
50 * @param stdClass $mform
51 * @return int new book instance id
53 function book_add_instance($data, $mform) {
54 global $DB;
56 $data->timecreated = time();
57 $data->timemodified = $data->timecreated;
58 if (!isset($data->customtitles)) {
59 $data->customtitles = 0;
62 $id = $DB->insert_record('book', $data);
64 $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
65 \core_completion\api::update_completion_date_event($data->coursemodule, 'book', $id, $completiontimeexpected);
67 return $id;
70 /**
71 * Update book instance.
73 * @param stdClass $data
74 * @param stdClass $mform
75 * @return bool true
77 function book_update_instance($data, $mform) {
78 global $DB;
80 $data->timemodified = time();
81 $data->id = $data->instance;
82 if (!isset($data->customtitles)) {
83 $data->customtitles = 0;
86 $DB->update_record('book', $data);
88 $book = $DB->get_record('book', array('id'=>$data->id));
89 $DB->set_field('book', 'revision', $book->revision+1, array('id'=>$book->id));
91 $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
92 \core_completion\api::update_completion_date_event($data->coursemodule, 'book', $book->id, $completiontimeexpected);
94 return true;
97 /**
98 * Delete book instance by activity id
100 * @param int $id
101 * @return bool success
103 function book_delete_instance($id) {
104 global $DB;
106 if (!$book = $DB->get_record('book', array('id'=>$id))) {
107 return false;
110 $cm = get_coursemodule_from_instance('book', $id);
111 \core_completion\api::update_completion_date_event($cm->id, 'book', $id, null);
113 $DB->delete_records('book_chapters', array('bookid'=>$book->id));
114 $DB->delete_records('book', array('id'=>$book->id));
116 return true;
120 * Given a course and a time, this module should find recent activity
121 * that has occurred in book activities and print it out.
123 * @param stdClass $course
124 * @param bool $viewfullnames
125 * @param int $timestart
126 * @return bool true if there was output, or false is there was none
128 function book_print_recent_activity($course, $viewfullnames, $timestart) {
129 return false; // True if anything was printed, otherwise false
133 * This function is used by the reset_course_userdata function in moodlelib.
134 * @param $data the data submitted from the reset course.
135 * @return array status array
137 function book_reset_userdata($data) {
138 global $DB;
139 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
140 // See MDL-9367.
142 $status = [];
144 if (!empty($data->reset_book_tags)) {
145 // Loop through the books and remove the tags from the chapters.
146 if ($books = $DB->get_records('book', array('course' => $data->courseid))) {
147 foreach ($books as $book) {
148 if (!$cm = get_coursemodule_from_instance('book', $book->id)) {
149 continue;
152 $context = context_module::instance($cm->id);
153 core_tag_tag::delete_instances('mod_book', null, $context->id);
158 $status[] = [
159 'component' => get_string('modulenameplural', 'book'),
160 'item' => get_string('tagsdeleted', 'book'),
161 'error' => false
165 return $status;
169 * The elements to add the course reset form.
171 * @param MoodleQuickForm $mform
173 function book_reset_course_form_definition(&$mform) {
174 $mform->addElement('header', 'bookheader', get_string('modulenameplural', 'book'));
175 $mform->addElement('checkbox', 'reset_book_tags', get_string('removeallbooktags', 'book'));
179 * No cron in book.
181 * @return bool
183 function book_cron () {
184 return true;
188 * No grading in book.
190 * @param int $bookid
191 * @return null
193 function book_grades($bookid) {
194 return null;
198 * Checks if scale is being used by any instance of book
200 * This is used to find out if scale used anywhere
202 * @param int $scaleid
203 * @return bool true if the scale is used by any book
205 function book_scale_used_anywhere($scaleid) {
206 return false;
210 * Return read actions.
212 * Note: This is not used by new logging system. Event with
213 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
214 * be considered as view action.
216 * @return array
218 function book_get_view_actions() {
219 global $CFG; // necessary for includes
221 $return = array('view', 'view all');
223 $plugins = core_component::get_plugin_list('booktool');
224 foreach ($plugins as $plugin => $dir) {
225 if (file_exists("$dir/lib.php")) {
226 require_once("$dir/lib.php");
228 $function = 'booktool_'.$plugin.'_get_view_actions';
229 if (function_exists($function)) {
230 if ($actions = $function()) {
231 $return = array_merge($return, $actions);
236 return $return;
240 * Return write actions.
242 * Note: This is not used by new logging system. Event with
243 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
244 * will be considered as post action.
246 * @return array
248 function book_get_post_actions() {
249 global $CFG; // necessary for includes
251 $return = array('update');
253 $plugins = core_component::get_plugin_list('booktool');
254 foreach ($plugins as $plugin => $dir) {
255 if (file_exists("$dir/lib.php")) {
256 require_once("$dir/lib.php");
258 $function = 'booktool_'.$plugin.'_get_post_actions';
259 if (function_exists($function)) {
260 if ($actions = $function()) {
261 $return = array_merge($return, $actions);
266 return $return;
270 * Supported features
272 * @param string $feature FEATURE_xx constant for requested feature
273 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
275 function book_supports($feature) {
276 switch($feature) {
277 case FEATURE_MOD_ARCHETYPE: return MOD_ARCHETYPE_RESOURCE;
278 case FEATURE_GROUPS: return false;
279 case FEATURE_GROUPINGS: return false;
280 case FEATURE_MOD_INTRO: return true;
281 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
282 case FEATURE_GRADE_HAS_GRADE: return false;
283 case FEATURE_GRADE_OUTCOMES: return false;
284 case FEATURE_BACKUP_MOODLE2: return true;
285 case FEATURE_SHOW_DESCRIPTION: return true;
286 case FEATURE_MOD_PURPOSE: return MOD_PURPOSE_CONTENT;
288 default: return null;
293 * Adds module specific settings to the settings block
295 * @param settings_navigation $settingsnav The settings navigation object
296 * @param navigation_node $booknode The node to add module settings to
297 * @return void
299 function book_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $booknode) {
300 global $USER, $OUTPUT;
302 if ($booknode->children->count() > 0) {
303 $firstkey = $booknode->children->get_key_list()[0];
304 } else {
305 $firstkey = null;
308 $params = $settingsnav->get_page()->url->params();
310 if ($settingsnav->get_page()->cm->modname === 'book' and !empty($params['id']) and !empty($params['chapterid'])
311 and has_capability('mod/book:edit', $settingsnav->get_page()->cm->context)) {
312 if (!empty($USER->editing)) {
313 $string = get_string("turneditingoff");
314 $edit = '0';
315 } else {
316 $string = get_string("turneditingon");
317 $edit = '1';
319 $url = new moodle_url('/mod/book/view.php', array('id'=>$params['id'], 'chapterid'=>$params['chapterid'], 'edit'=>$edit, 'sesskey'=>sesskey()));
320 $editnode = navigation_node::create($string, $url, navigation_node::TYPE_SETTING);
321 $editnode->set_show_in_secondary_navigation(false);
322 $booknode->add_node($editnode, $firstkey);
323 if (!$settingsnav->get_page()->theme->haseditswitch) {
324 $settingsnav->get_page()->set_button($OUTPUT->single_button($url, $string));
328 $plugins = core_component::get_plugin_list('booktool');
329 foreach ($plugins as $plugin => $dir) {
330 if (file_exists("$dir/lib.php")) {
331 require_once("$dir/lib.php");
333 $function = 'booktool_'.$plugin.'_extend_settings_navigation';
334 if (function_exists($function)) {
335 $function($settingsnav, $booknode);
342 * Lists all browsable file areas
343 * @param object $course
344 * @param object $cm
345 * @param object $context
346 * @return array
348 function book_get_file_areas($course, $cm, $context) {
349 $areas = array();
350 $areas['chapter'] = get_string('chapters', 'mod_book');
351 return $areas;
355 * File browsing support for book module chapter area.
356 * @param object $browser
357 * @param object $areas
358 * @param object $course
359 * @param object $cm
360 * @param object $context
361 * @param string $filearea
362 * @param int $itemid
363 * @param string $filepath
364 * @param string $filename
365 * @return object file_info instance or null if not found
367 function book_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
368 global $CFG, $DB;
370 // note: 'intro' area is handled in file_browser automatically
372 if (!has_capability('mod/book:read', $context)) {
373 return null;
376 if ($filearea !== 'chapter') {
377 return null;
380 require_once(__DIR__.'/locallib.php');
382 if (is_null($itemid)) {
383 return new book_file_info($browser, $course, $cm, $context, $areas, $filearea);
386 $fs = get_file_storage();
387 $filepath = is_null($filepath) ? '/' : $filepath;
388 $filename = is_null($filename) ? '.' : $filename;
389 if (!$storedfile = $fs->get_file($context->id, 'mod_book', $filearea, $itemid, $filepath, $filename)) {
390 return null;
393 // modifications may be tricky - may cause caching problems
394 $canwrite = has_capability('mod/book:edit', $context);
396 $chaptername = $DB->get_field('book_chapters', 'title', array('bookid'=>$cm->instance, 'id'=>$itemid));
397 $chaptername = format_string($chaptername, true, array('context'=>$context));
399 $urlbase = $CFG->wwwroot.'/pluginfile.php';
400 return new file_info_stored($browser, $context, $storedfile, $urlbase, $chaptername, true, true, $canwrite, false);
404 * Serves the book attachments. Implements needed access control ;-)
406 * @param stdClass $course course object
407 * @param cm_info $cm course module object
408 * @param context $context context object
409 * @param string $filearea file area
410 * @param array $args extra arguments
411 * @param bool $forcedownload whether or not force download
412 * @param array $options additional options affecting the file serving
413 * @return bool false if file not found, does not return if found - just send the file
415 function book_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
416 global $CFG, $DB;
418 if ($context->contextlevel != CONTEXT_MODULE) {
419 return false;
422 require_course_login($course, true, $cm);
424 if ($filearea !== 'chapter') {
425 return false;
428 if (!has_capability('mod/book:read', $context)) {
429 return false;
432 $chid = (int)array_shift($args);
434 if (!$book = $DB->get_record('book', array('id'=>$cm->instance))) {
435 return false;
438 if (!$chapter = $DB->get_record('book_chapters', array('id'=>$chid, 'bookid'=>$book->id))) {
439 return false;
442 if ($chapter->hidden and !has_capability('mod/book:viewhiddenchapters', $context)) {
443 return false;
446 // Download the contents of a chapter as an html file.
447 if ($args[0] == 'index.html') {
448 $filename = "index.html";
450 // We need to rewrite the pluginfile URLs so the media filters can work.
451 $content = file_rewrite_pluginfile_urls($chapter->content, 'webservice/pluginfile.php', $context->id, 'mod_book', 'chapter',
452 $chapter->id);
453 $formatoptions = new stdClass;
454 $formatoptions->noclean = true;
455 $formatoptions->overflowdiv = true;
456 $formatoptions->context = $context;
458 $content = format_text($content, $chapter->contentformat, $formatoptions);
460 // Remove @@PLUGINFILE@@/.
461 $options = array('reverse' => true);
462 $content = file_rewrite_pluginfile_urls($content, 'webservice/pluginfile.php', $context->id, 'mod_book', 'chapter',
463 $chapter->id, $options);
464 $content = str_replace('@@PLUGINFILE@@/', '', $content);
466 $titles = "";
467 // Format the chapter titles.
468 if (!$book->customtitles) {
469 require_once(__DIR__.'/locallib.php');
470 $chapters = book_preload_chapters($book);
472 if (!$chapter->subchapter) {
473 $currtitle = book_get_chapter_title($chapter->id, $chapters, $book, $context);
474 // Note that we can't use the $OUTPUT->heading() in WS_SERVER mode.
475 $titles = "<h3>$currtitle</h3>";
476 } else {
477 $currtitle = book_get_chapter_title($chapters[$chapter->id]->parent, $chapters, $book, $context);
478 $currsubtitle = book_get_chapter_title($chapter->id, $chapters, $book, $context);
479 // Note that we can't use the $OUTPUT->heading() in WS_SERVER mode.
480 $titles = "<h3>$currtitle</h3>";
481 $titles .= "<h4>$currsubtitle</h4>";
485 $content = $titles . $content;
487 send_file($content, $filename, 0, 0, true, true);
488 } else {
489 $fs = get_file_storage();
490 $relativepath = implode('/', $args);
491 $fullpath = "/$context->id/mod_book/chapter/$chid/$relativepath";
492 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
493 return false;
496 // Nasty hack because we do not have file revisions in book yet.
497 $lifetime = $CFG->filelifetime;
498 if ($lifetime > 60 * 10) {
499 $lifetime = 60 * 10;
502 // Finally send the file.
503 send_stored_file($file, $lifetime, 0, $forcedownload, $options);
508 * Return a list of page types
510 * @param string $pagetype current page type
511 * @param stdClass $parentcontext Block's parent context
512 * @param stdClass $currentcontext Current context of block
513 * @return array
515 function book_page_type_list($pagetype, $parentcontext, $currentcontext) {
516 $module_pagetype = array('mod-book-*'=>get_string('page-mod-book-x', 'mod_book'));
517 return $module_pagetype;
521 * Export book resource contents
523 * @param stdClass $cm Course module object
524 * @param string $baseurl Base URL for file downloads
525 * @return array of file content
527 function book_export_contents($cm, $baseurl) {
528 global $DB;
530 $contents = array();
531 $context = context_module::instance($cm->id);
533 $book = $DB->get_record('book', array('id' => $cm->instance), '*', MUST_EXIST);
535 $fs = get_file_storage();
537 $chapters = $DB->get_records('book_chapters', array('bookid' => $book->id), 'pagenum');
539 $structure = array();
540 $currentchapter = 0;
542 foreach ($chapters as $chapter) {
543 if ($chapter->hidden && !has_capability('mod/book:viewhiddenchapters', $context)) {
544 continue;
547 // Generate the book structure.
548 $thischapter = array(
549 "title" => format_string($chapter->title, true, array('context' => $context)),
550 "href" => $chapter->id . "/index.html",
551 "level" => 0,
552 "hidden" => $chapter->hidden,
553 "subitems" => array()
556 // Main chapter.
557 if (!$chapter->subchapter) {
558 $currentchapter = $chapter->pagenum;
559 $structure[$currentchapter] = $thischapter;
560 } else {
561 // Subchapter.
562 $thischapter['level'] = 1;
563 $structure[$currentchapter]["subitems"][] = $thischapter;
566 // Export the chapter contents.
568 // Main content (html).
569 $filename = 'index.html';
570 $chapterindexfile = array();
571 $chapterindexfile['type'] = 'file';
572 $chapterindexfile['filename'] = $filename;
573 // Each chapter in a subdirectory.
574 $chapterindexfile['filepath'] = "/{$chapter->id}/";
575 $chapterindexfile['filesize'] = 0;
576 $chapterindexfile['fileurl'] = moodle_url::make_webservice_pluginfile_url(
577 $context->id, 'mod_book', 'chapter', $chapter->id, '/', 'index.html')->out(false);
578 $chapterindexfile['timecreated'] = $chapter->timecreated;
579 $chapterindexfile['timemodified'] = $chapter->timemodified;
580 $chapterindexfile['content'] = format_string($chapter->title, true, array('context' => $context));
581 $chapterindexfile['sortorder'] = 0;
582 $chapterindexfile['userid'] = null;
583 $chapterindexfile['author'] = null;
584 $chapterindexfile['license'] = null;
585 $chapterindexfile['tags'] = \core_tag\external\util::get_item_tags('mod_book', 'book_chapters', $chapter->id);
586 $contents[] = $chapterindexfile;
588 // Chapter files (images usually).
589 $files = $fs->get_area_files($context->id, 'mod_book', 'chapter', $chapter->id, 'sortorder DESC, id ASC', false);
590 foreach ($files as $fileinfo) {
591 $file = array();
592 $file['type'] = 'file';
593 $file['filename'] = $fileinfo->get_filename();
594 $file['filepath'] = "/{$chapter->id}" . $fileinfo->get_filepath();
595 $file['filesize'] = $fileinfo->get_filesize();
596 $file['fileurl'] = moodle_url::make_webservice_pluginfile_url(
597 $context->id, 'mod_book', 'chapter', $chapter->id,
598 $fileinfo->get_filepath(), $fileinfo->get_filename())->out(false);
599 $file['timecreated'] = $fileinfo->get_timecreated();
600 $file['timemodified'] = $fileinfo->get_timemodified();
601 $file['sortorder'] = $fileinfo->get_sortorder();
602 $file['userid'] = $fileinfo->get_userid();
603 $file['author'] = $fileinfo->get_author();
604 $file['license'] = $fileinfo->get_license();
605 $file['mimetype'] = $fileinfo->get_mimetype();
606 $file['isexternalfile'] = $fileinfo->is_external_file();
607 if ($file['isexternalfile']) {
608 $file['repositorytype'] = $fileinfo->get_repository_type();
610 $contents[] = $file;
614 // First content is the structure in encoded JSON format.
615 $structurefile = array();
616 $structurefile['type'] = 'content';
617 $structurefile['filename'] = 'structure';
618 $structurefile['filepath'] = "/";
619 $structurefile['filesize'] = 0;
620 $structurefile['fileurl'] = null;
621 $structurefile['timecreated'] = $book->timecreated;
622 $structurefile['timemodified'] = $book->timemodified;
623 $structurefile['content'] = json_encode(array_values($structure));
624 $structurefile['sortorder'] = 0;
625 $structurefile['userid'] = null;
626 $structurefile['author'] = null;
627 $structurefile['license'] = null;
629 // Add it as first element.
630 array_unshift($contents, $structurefile);
632 return $contents;
636 * Mark the activity completed (if required) and trigger the course_module_viewed event.
638 * @param stdClass $book book object
639 * @param stdClass $chapter chapter object
640 * @param bool $islaschapter is the las chapter of the book?
641 * @param stdClass $course course object
642 * @param stdClass $cm course module object
643 * @param stdClass $context context object
644 * @since Moodle 3.0
646 function book_view($book, $chapter, $islastchapter, $course, $cm, $context) {
648 // First case, we are just opening the book.
649 if (empty($chapter)) {
650 \mod_book\event\course_module_viewed::create_from_book($book, $context)->trigger();
652 } else {
653 \mod_book\event\chapter_viewed::create_from_chapter($book, $context, $chapter)->trigger();
655 if ($islastchapter) {
656 // We cheat a bit here in assuming that viewing the last page means the user viewed the whole book.
657 $completion = new completion_info($course);
658 $completion->set_module_viewed($cm);
664 * Check if the module has any update that affects the current user since a given time.
666 * @param cm_info $cm course module data
667 * @param int $from the time to check updates from
668 * @param array $filter if we need to check only specific updates
669 * @return stdClass an object with the different type of areas indicating if they were updated or not
670 * @since Moodle 3.2
672 function book_check_updates_since(cm_info $cm, $from, $filter = array()) {
673 global $DB;
675 $context = $cm->context;
676 $updates = new stdClass();
677 if (!has_capability('mod/book:read', $context)) {
678 return $updates;
680 $updates = course_check_module_updates_since($cm, $from, array('content'), $filter);
682 $select = 'bookid = :id AND (timecreated > :since1 OR timemodified > :since2)';
683 $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
684 if (!has_capability('mod/book:viewhiddenchapters', $context)) {
685 $select .= ' AND hidden = 0';
687 $updates->entries = (object) array('updated' => false);
688 $entries = $DB->get_records_select('book_chapters', $select, $params, '', 'id');
689 if (!empty($entries)) {
690 $updates->entries->updated = true;
691 $updates->entries->itemids = array_keys($entries);
694 return $updates;
698 * Get icon mapping for font-awesome.
700 function mod_book_get_fontawesome_icon_map() {
701 return [
702 'mod_book:chapter' => 'fa-bookmark-o',
703 'mod_book:nav_prev' => 'fa-arrow-left',
704 'mod_book:nav_sep' => 'fa-minus',
705 'mod_book:add' => 'fa-plus',
706 'mod_book:nav_next' => 'fa-arrow-right',
707 'mod_book:nav_exit' => 'fa-arrow-up',
712 * This function receives a calendar event and returns the action associated with it, or null if there is none.
714 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
715 * is not displayed on the block.
717 * @param calendar_event $event
718 * @param \core_calendar\action_factory $factory
719 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
720 * @return \core_calendar\local\event\entities\action_interface|null
722 function mod_book_core_calendar_provide_event_action(calendar_event $event,
723 \core_calendar\action_factory $factory,
724 int $userid = 0) {
725 global $USER;
727 if (empty($userid)) {
728 $userid = $USER->id;
731 $cm = get_fast_modinfo($event->courseid, $userid)->instances['book'][$event->instance];
733 if (!$cm->uservisible) {
734 // The module is not visible to the user for any reason.
735 return null;
738 $context = context_module::instance($cm->id);
740 if (!has_capability('mod/book:read', $context, $userid)) {
741 return null;
744 $completion = new \completion_info($cm->get_course());
746 $completiondata = $completion->get_data($cm, false, $userid);
748 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
749 return null;
752 return $factory->create_instance(
753 get_string('view'),
754 new \moodle_url('/mod/book/view.php', ['id' => $cm->id]),
756 true