3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Local library file for Lesson. These are non-standard functions that are used
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
27 /** Make sure this isn't being directly accessed */
28 defined('MOODLE_INTERNAL') || die();
30 /** Include the files that are required by this module */
31 require_once($CFG->dirroot.'/course/moodleform_mod.php');
32 require_once($CFG->dirroot . '/mod/lesson/lib.php');
33 require_once($CFG->libdir . '/filelib.php');
36 define('LESSON_THISPAGE', 0);
37 /** Next page -> any page not seen before */
38 define("LESSON_UNSEENPAGE", 1);
39 /** Next page -> any page not answered correctly */
40 define("LESSON_UNANSWEREDPAGE", 2);
41 /** Jump to Next Page */
42 define("LESSON_NEXTPAGE", -1);
44 define("LESSON_EOL", -9);
45 /** Jump to an unseen page within a branch and end of branch or end of lesson */
46 define("LESSON_UNSEENBRANCHPAGE", -50);
47 /** Jump to Previous Page */
48 define("LESSON_PREVIOUSPAGE", -40);
49 /** Jump to a random page within a branch and end of branch or end of lesson */
50 define("LESSON_RANDOMPAGE", -60);
51 /** Jump to a random Branch */
52 define("LESSON_RANDOMBRANCH", -70);
54 define("LESSON_CLUSTERJUMP", -80);
56 define("LESSON_UNDEFINED", -99);
58 /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
59 define("LESSON_MAX_EVENT_LENGTH", "432000");
61 /** Answer format is HTML */
62 define("LESSON_ANSWER_HTML", "HTML");
64 //////////////////////////////////////////////////////////////////////////////////////
65 /// Any other lesson functions go here. Each of them must have a name that
66 /// starts with lesson_
69 * Checks to see if a LESSON_CLUSTERJUMP or
70 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
72 * This function is only executed when a teacher is
73 * checking the navigation for a lesson.
75 * @param stdClass $lesson Id of the lesson that is to be checked.
76 * @return boolean True or false.
78 function lesson_display_teacher_warning($lesson) {
81 // get all of the lesson answers
82 $params = array ("lessonid" => $lesson->id);
83 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
84 // no answers, then not using cluster or unseen
87 // just check for the first one that fulfills the requirements
88 foreach ($lessonanswers as $lessonanswer) {
89 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
94 // if no answers use either of the two jumps
99 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
101 * will return the pageid of a random unseen page that is within a branch
103 * @param lesson $lesson
104 * @param int $userid Id of the user.
105 * @param int $pageid Id of the page from which we are jumping.
106 * @return int Id of the next page.
108 function lesson_unseen_question_jump($lesson, $user, $pageid) {
111 // get the number of retakes
112 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
116 // get all the lesson_attempts aka what the user has seen
117 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
118 foreach($viewedpages as $viewed) {
119 $seenpages[] = $viewed->pageid;
122 $seenpages = array();
125 // get the lesson pages
126 $lessonpages = $lesson->load_all_pages();
128 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
129 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
132 // go up the pages till branch table
133 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
134 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
137 $pageid = $lessonpages[$pageid]->prevpageid;
140 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
142 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
144 foreach($pagesinbranch as $page) {
145 if (!in_array($page->id, $seenpages)) {
146 $unseen[] = $page->id;
150 if(count($unseen) == 0) {
151 if(isset($pagesinbranch)) {
152 $temp = end($pagesinbranch);
153 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
155 // there are no pages inside the branch, so return the next page
156 $nextpage = $lessonpages[$pageid]->nextpageid;
158 if ($nextpage == 0) {
164 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
169 * Handles the unseen branch table jump.
171 * @param lesson $lesson
172 * @param int $userid User id.
173 * @return int Will return the page id of a branch table or end of lesson
175 function lesson_unseen_branch_jump($lesson, $userid) {
178 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
182 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $retakes);
183 if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
185 print_error('cannotfindrecords', 'lesson');
188 // get the lesson pages
189 $lessonpages = $lesson->load_all_pages();
191 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
192 // which is the branch table that starts the unseenbranch function
194 foreach ($seenbranches as $seenbranch) {
195 if (!$seenbranch->flag) {
196 $seen[$seenbranch->pageid] = $seenbranch->pageid;
198 $start = $seenbranch->pageid;
202 // this function searches through the lesson pages to find all the branch tables
203 // that follow the flagged branch table
204 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
205 $branchtables = array();
206 while ($pageid != 0) { // grab all of the branch table till eol
207 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
208 $branchtables[] = $lessonpages[$pageid]->id;
210 $pageid = $lessonpages[$pageid]->nextpageid;
213 foreach ($branchtables as $branchtable) {
214 // load all of the unseen branch tables into unseen
215 if (!array_key_exists($branchtable, $seen)) {
216 $unseen[] = $branchtable;
219 if (count($unseen) > 0) {
220 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
222 return LESSON_EOL; // has viewed all of the branch tables
227 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
229 * @param lesson $lesson
230 * @param int $pageid The id of the page that we are jumping from (?)
231 * @return int The pageid of a random page that is within a branch table
233 function lesson_random_question_jump($lesson, $pageid) {
236 // get the lesson pages
237 $params = array ("lessonid" => $lesson->id);
238 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
239 print_error('cannotfindpages', 'lesson');
242 // go up the pages till branch table
243 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
245 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
248 $pageid = $lessonpages[$pageid]->prevpageid;
251 // get the pages within the branch
252 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
254 if(count($pagesinbranch) == 0) {
255 // there are no pages inside the branch, so return the next page
256 return $lessonpages[$pageid]->nextpageid;
258 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
263 * Calculates a user's grade for a lesson.
265 * @param object $lesson The lesson that the user is taking.
266 * @param int $retries The attempt number.
267 * @param int $userid Id of the user (optional, default current user).
268 * @return object { nquestions => number of questions answered
269 attempts => number of question attempts
270 total => max points possible
271 earned => points earned by student
272 grade => calculated percentage grade
273 nmanual => number of manually graded questions
274 manualpoints => point value for manually graded questions }
276 function lesson_grade($lesson, $ntries, $userid = 0) {
279 if (empty($userid)) {
283 // Zero out everything
294 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
295 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
296 userid = :userid AND retry = :retry", $params, "timeseen")) {
297 // group each try with its page
298 $attemptset = array();
299 foreach ($useranswers as $useranswer) {
300 $attemptset[$useranswer->pageid][] = $useranswer;
303 // Drop all attempts that go beyond max attempts for the lesson
304 foreach ($attemptset as $key => $set) {
305 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
308 // get only the pages and their answers that the user answered
309 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
310 array_unshift($parameters, $lesson->id);
311 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
312 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
314 // Number of pages answered
315 $nquestions = count($pages);
317 foreach ($attemptset as $attempts) {
318 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
319 if ($lesson->custom) {
320 $attempt = end($attempts);
321 // If essay question, handle it, otherwise add to score
322 if ($page->requires_manual_grading()) {
323 $useranswerobj = unserialize($attempt->useranswer);
324 if (isset($useranswerobj->score)) {
325 $earned += $useranswerobj->score;
328 $manualpoints += $answers[$attempt->answerid]->score;
329 } else if (!empty($attempt->answerid)) {
330 $earned += $page->earned_score($answers, $attempt);
333 foreach ($attempts as $attempt) {
334 $earned += $attempt->correct;
336 $attempt = end($attempts); // doesn't matter which one
337 // If essay question, increase numbers
338 if ($page->requires_manual_grading()) {
343 // Number of times answered
344 $nviewed += count($attempts);
347 if ($lesson->custom) {
348 $bestscores = array();
349 // Find the highest possible score per page to get our total
350 foreach ($answers as $answer) {
351 if(!isset($bestscores[$answer->pageid])) {
352 $bestscores[$answer->pageid] = $answer->score;
353 } else if ($bestscores[$answer->pageid] < $answer->score) {
354 $bestscores[$answer->pageid] = $answer->score;
357 $total = array_sum($bestscores);
359 // Check to make sure the student has answered the minimum questions
360 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
361 // Nope, increase number viewed by the amount of unanswered questions
362 $total = $nviewed + ($lesson->minquestions - $nquestions);
369 if ($total) { // not zero
370 $thegrade = round(100 * $earned / $total, 5);
373 // Build the grade information object
374 $gradeinfo = new stdClass;
375 $gradeinfo->nquestions = $nquestions;
376 $gradeinfo->attempts = $nviewed;
377 $gradeinfo->total = $total;
378 $gradeinfo->earned = $earned;
379 $gradeinfo->grade = $thegrade;
380 $gradeinfo->nmanual = $nmanual;
381 $gradeinfo->manualpoints = $manualpoints;
387 * Determines if a user can view the left menu. The determining factor
388 * is whether a user has a grade greater than or equal to the lesson setting
391 * @param object $lesson Lesson object of the current lesson
392 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
394 function lesson_displayleftif($lesson) {
395 global $CFG, $USER, $DB;
397 if (!empty($lesson->displayleftif)) {
398 // get the current user's max grade for this lesson
399 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
400 if ($maxgrade = $DB->get_record_sql('SELECT userid, MAX(grade) AS maxgrade FROM {lesson_grades} WHERE userid = :userid AND lessonid = :lessonid GROUP BY userid', $params)) {
401 if ($maxgrade->maxgrade < $lesson->displayleftif) {
402 return 0; // turn off the displayleft
405 return 0; // no grades
409 // if we get to here, keep the original state of displayleft lesson setting
410 return $lesson->displayleft;
418 * @return unknown_type
420 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
421 $bc = lesson_menu_block_contents($cm->id, $lesson);
423 $regions = $page->blocks->get_regions();
424 $firstregion = reset($regions);
425 $page->blocks->add_fake_block($bc, $firstregion);
428 $bc = lesson_mediafile_block_contents($cm->id, $lesson);
430 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
433 if (!empty($timer)) {
434 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
436 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
442 * If there is a media file associated with this
443 * lesson, return a block_contents that displays it.
445 * @param int $cmid Course Module ID for this lesson
446 * @param object $lesson Full lesson record object
447 * @return block_contents
449 function lesson_mediafile_block_contents($cmid, $lesson) {
451 if (empty($lesson->mediafile)) {
456 $options['menubar'] = 0;
457 $options['location'] = 0;
458 $options['left'] = 5;
460 $options['scrollbars'] = 1;
461 $options['resizable'] = 1;
462 $options['width'] = $lesson->mediawidth;
463 $options['height'] = $lesson->mediaheight;
465 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
466 $action = new popup_action('click', $link, 'lessonmediafile', $options);
467 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
469 $bc = new block_contents();
470 $bc->title = get_string('linkedmedia', 'lesson');
471 $bc->attributes['class'] = 'mediafile block';
472 $bc->content = $content;
478 * If a timed lesson and not a teacher, then
479 * return a block_contents containing the clock.
481 * @param int $cmid Course Module ID for this lesson
482 * @param object $lesson Full lesson record object
483 * @param object $timer Full timer record object
484 * @return block_contents
486 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
487 // Display for timed lessons and for students only
488 $context = context_module::instance($cmid);
489 if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) {
493 $content = '<div id="lesson-timer">';
494 $content .= $lesson->time_remaining($timer->starttime);
495 $content .= '</div>';
497 $clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit);
498 $page->requires->data_for_js('clocksettings', $clocksettings, true);
499 $page->requires->strings_for_js(array('timeisup'), 'lesson');
500 $page->requires->js('/mod/lesson/timer.js');
501 $page->requires->js_init_call('show_clock');
503 $bc = new block_contents();
504 $bc->title = get_string('timeremaining', 'lesson');
505 $bc->attributes['class'] = 'clock block';
506 $bc->content = $content;
512 * If left menu is turned on, then this will
513 * print the menu in a block
515 * @param int $cmid Course Module ID for this lesson
516 * @param lesson $lesson Full lesson record object
519 function lesson_menu_block_contents($cmid, $lesson) {
522 if (!$lesson->displayleft) {
526 $pages = $lesson->load_all_pages();
527 foreach ($pages as $page) {
528 if ((int)$page->prevpageid === 0) {
533 $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
535 if (!$pageid || !$pages) {
539 $content = '<a href="#maincontent" class="accesshide">' .
540 get_string('skip', 'lesson') .
541 "</a>\n<div class=\"menuwrapper\">\n<ul>\n";
543 while ($pageid != 0) {
544 $page = $pages[$pageid];
546 // Only process branch tables with display turned on
547 if ($page->displayinmenublock && $page->display) {
548 if ($page->id == $currentpageid) {
549 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
551 $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
555 $pageid = $page->nextpageid;
557 $content .= "</ul>\n</div>\n";
559 $bc = new block_contents();
560 $bc->title = get_string('lessonmenu', 'lesson');
561 $bc->attributes['class'] = 'menu block';
562 $bc->content = $content;
568 * Adds header buttons to the page for the lesson
571 * @param object $context
572 * @param bool $extraeditbuttons
573 * @param int $lessonpageid
575 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
576 global $CFG, $PAGE, $OUTPUT;
577 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
578 if ($lessonpageid === null) {
579 print_error('invalidpageid', 'lesson');
581 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
582 $url = new moodle_url('/mod/lesson/editpage.php', array(
584 'pageid' => $lessonpageid,
586 'returnto' => $PAGE->url->out(false)
588 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
594 * This is a function used to detect media types and generate html code.
596 * @global object $CFG
597 * @global object $PAGE
598 * @param object $lesson
599 * @param object $context
600 * @return string $code the html code of media
602 function lesson_get_media_html($lesson, $context) {
603 global $CFG, $PAGE, $OUTPUT;
604 require_once("$CFG->libdir/resourcelib.php");
606 // get the media file link
607 if (strpos($lesson->mediafile, '://') !== false) {
608 $url = new moodle_url($lesson->mediafile);
610 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
611 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
613 $title = $lesson->mediafile;
615 $clicktoopen = html_writer::link($url, get_string('download'));
617 $mimetype = resourcelib_guess_url_mimetype($url);
619 $extension = resourcelib_get_extension($url->out(false));
621 $mediamanager = core_media_manager::instance();
622 $embedoptions = array(
623 core_media_manager::OPTION_TRUSTED => true,
624 core_media_manager::OPTION_BLOCK => true
627 // find the correct type and print it out
628 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
629 $code = resourcelib_embed_image($url, $title);
631 } else if ($mediamanager->can_embed_url($url, $embedoptions)) {
632 // Media (audio/video) file.
633 $code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions);
636 // anything else - just try object tag enlarged as much as possible
637 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
644 * Logic to happen when a/some group(s) has/have been deleted in a course.
646 * @param int $courseid The course ID.
647 * @param int $groupid The group id if it is known
650 function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
653 $params = array('courseid' => $courseid);
655 $params['groupid'] = $groupid;
656 // We just update the group that was deleted.
657 $sql = "SELECT o.id, o.lessonid
658 FROM {lesson_overrides} o
659 JOIN {lesson} lesson ON lesson.id = o.lessonid
660 WHERE lesson.course = :courseid
661 AND o.groupid = :groupid";
663 // No groupid, we update all orphaned group overrides for all lessons in course.
664 $sql = "SELECT o.id, o.lessonid
665 FROM {lesson_overrides} o
666 JOIN {lesson} lesson ON lesson.id = o.lessonid
667 LEFT JOIN {groups} grp ON grp.id = o.groupid
668 WHERE lesson.course = :courseid
669 AND o.groupid IS NOT NULL
672 $records = $DB->get_records_sql_menu($sql, $params);
674 return; // Nothing to do.
676 $DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
680 * Abstract class that page type's MUST inherit from.
682 * This is the abstract class that ALL add page type forms must extend.
683 * You will notice that all but two of the methods this class contains are final.
684 * Essentially the only thing that extending classes can do is extend custom_definition.
685 * OR if it has a special requirement on creation it can extend construction_override
688 * @copyright 2009 Sam Hemelryk
689 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
691 abstract class lesson_add_page_form_base extends moodleform {
694 * This is the classic define that is used to identify this pagetype.
695 * Will be one of LESSON_*
701 * The simple string that describes the page type e.g. truefalse, multichoice
707 * An array of options used in the htmleditor
710 protected $editoroptions = array();
713 * True if this is a standard page of false if it does something special.
714 * Questions are standard pages, branch tables are not
717 protected $standard = true;
720 * Answer format supported by question type.
722 protected $answerformat = '';
725 * Response format supported by question type.
727 protected $responseformat = '';
730 * Each page type can and should override this to add any custom elements to
731 * the basic form that they want
733 public function custom_definition() {}
736 * Returns answer format used by question type.
738 public function get_answer_format() {
739 return $this->answerformat;
743 * Returns response format used by question type.
745 public function get_response_format() {
746 return $this->responseformat;
750 * Used to determine if this is a standard page or a special page
753 public final function is_standard() {
754 return (bool)$this->standard;
758 * Add the required basic elements to the form.
760 * This method adds the basic elements to the form including title and contents
761 * and then calls custom_definition();
763 public final function definition() {
764 $mform = $this->_form;
765 $editoroptions = $this->_customdata['editoroptions'];
767 $mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
769 if (!empty($this->_customdata['returnto'])) {
770 $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']);
771 $mform->setType('returnto', PARAM_URL);
774 $mform->addElement('hidden', 'id');
775 $mform->setType('id', PARAM_INT);
777 $mform->addElement('hidden', 'pageid');
778 $mform->setType('pageid', PARAM_INT);
780 if ($this->standard === true) {
781 $mform->addElement('hidden', 'qtype');
782 $mform->setType('qtype', PARAM_INT);
784 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
785 $mform->setType('title', PARAM_TEXT);
786 $mform->addRule('title', get_string('required'), 'required', null, 'client');
788 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
789 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
790 $mform->setType('contents_editor', PARAM_RAW);
791 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
794 $this->custom_definition();
796 if ($this->_customdata['edit'] === true) {
797 $mform->addElement('hidden', 'edit', 1);
798 $mform->setType('edit', PARAM_BOOL);
799 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
800 } else if ($this->qtype === 'questiontype') {
801 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
803 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
808 * Convenience function: Adds a jumpto select element
810 * @param string $name
811 * @param string|null $label
812 * @param int $selected The page to select by default
814 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
815 $title = get_string("jump", "lesson");
816 if ($label === null) {
820 $name = "jumpto[$name]";
822 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
823 $this->_form->setDefault($name, $selected);
824 $this->_form->addHelpButton($name, 'jumps', 'lesson');
828 * Convenience function: Adds a score input element
830 * @param string $name
831 * @param string|null $label
832 * @param mixed $value The default value
834 protected final function add_score($name, $label=null, $value=null) {
835 if ($label === null) {
836 $label = get_string("score", "lesson");
840 $name = "score[$name]";
842 $this->_form->addElement('text', $name, $label, array('size'=>5));
843 $this->_form->setType($name, PARAM_INT);
844 if ($value !== null) {
845 $this->_form->setDefault($name, $value);
847 $this->_form->addHelpButton($name, 'score', 'lesson');
849 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion.
850 if (!$this->_customdata['lesson']->custom) {
851 $this->_form->freeze($name);
856 * Convenience function: Adds an answer editor
858 * @param int $count The count of the element to add
859 * @param string $label, null means default
860 * @param bool $required
861 * @param string $format
864 protected final function add_answer($count, $label = null, $required = false, $format= '') {
865 if ($label === null) {
866 $label = get_string('answer', 'lesson');
869 if ($format == LESSON_ANSWER_HTML) {
870 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label,
871 array('rows' => '4', 'columns' => '80'),
872 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
873 $this->_form->setType('answer_editor['.$count.']', PARAM_RAW);
874 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
876 $this->_form->addElement('text', 'answer_editor['.$count.']', $label,
877 array('size' => '50', 'maxlength' => '200'));
878 $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT);
882 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
886 * Convenience function: Adds an response editor
888 * @param int $count The count of the element to add
889 * @param string $label, null means default
890 * @param bool $required
893 protected final function add_response($count, $label = null, $required = false) {
894 if ($label === null) {
895 $label = get_string('response', 'lesson');
897 $this->_form->addElement('editor', 'response_editor['.$count.']', $label,
898 array('rows' => '4', 'columns' => '80'),
899 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes']));
900 $this->_form->setType('response_editor['.$count.']', PARAM_RAW);
901 $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML));
904 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
909 * A function that gets called upon init of this object by the calling script.
911 * This can be used to process an immediate action if required. Currently it
912 * is only used in special cases by non-standard page types.
916 public function construction_override($pageid, lesson $lesson) {
924 * Class representation of a lesson
926 * This class is used the interact with, and manage a lesson once instantiated.
927 * If you need to fetch a lesson object you can do so by calling
930 * lesson::load($lessonid);
932 * $lessonrecord = $DB->get_record('lesson', $lessonid);
933 * $lesson = new lesson($lessonrecord);
936 * The class itself extends lesson_base as all classes within the lesson module should
938 * These properties are from the database
939 * @property int $id The id of this lesson
940 * @property int $course The ID of the course this lesson belongs to
941 * @property string $name The name of this lesson
942 * @property int $practice Flag to toggle this as a practice lesson
943 * @property int $modattempts Toggle to allow the user to go back and review answers
944 * @property int $usepassword Toggle the use of a password for entry
945 * @property string $password The password to require users to enter
946 * @property int $dependency ID of another lesson this lesson is dependent on
947 * @property string $conditions Conditions of the lesson dependency
948 * @property int $grade The maximum grade a user can achieve (%)
949 * @property int $custom Toggle custom scoring on or off
950 * @property int $ongoing Toggle display of an ongoing score
951 * @property int $usemaxgrade How retakes are handled (max=1, mean=0)
952 * @property int $maxanswers The max number of answers or branches
953 * @property int $maxattempts The maximum number of attempts a user can record
954 * @property int $review Toggle use or wrong answer review button
955 * @property int $nextpagedefault Override the default next page
956 * @property int $feedback Toggles display of default feedback
957 * @property int $minquestions Sets a minimum value of pages seen when calculating grades
958 * @property int $maxpages Maximum number of pages this lesson can contain
959 * @property int $retake Flag to allow users to retake a lesson
960 * @property int $activitylink Relate this lesson to another lesson
961 * @property string $mediafile File to pop up to or webpage to display
962 * @property int $mediaheight Sets the height of the media file popup
963 * @property int $mediawidth Sets the width of the media file popup
964 * @property int $mediaclose Toggle display of a media close button
965 * @property int $slideshow Flag for whether branch pages should be shown as slideshows
966 * @property int $width Width of slideshow
967 * @property int $height Height of slideshow
968 * @property string $bgcolor Background colour of slideshow
969 * @property int $displayleft Display a left menu
970 * @property int $displayleftif Sets the condition on which the left menu is displayed
971 * @property int $progressbar Flag to toggle display of a lesson progress bar
972 * @property int $available Timestamp of when this lesson becomes available
973 * @property int $deadline Timestamp of when this lesson is no longer available
974 * @property int $timemodified Timestamp when lesson was last modified
976 * These properties are calculated
977 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
978 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
980 * @copyright 2009 Sam Hemelryk
981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
983 class lesson extends lesson_base {
986 * The id of the first page (where prevpageid = 0) gets set and retrieved by
987 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
990 protected $firstpageid = null;
992 * The id of the last page (where nextpageid = 0) gets set and retrieved by
993 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
996 protected $lastpageid = null;
998 * An array used to cache the pages associated with this lesson after the first
999 * time they have been loaded.
1000 * A note to developers: If you are going to be working with MORE than one or
1001 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
1002 * in order to save excess database queries.
1003 * @var array An array of lesson_page objects
1005 protected $pages = array();
1007 * Flag that gets set to true once all of the pages associated with the lesson
1011 protected $loadedallpages = false;
1014 * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code>
1018 protected $cm = null;
1021 * Context object gets set and retrieved by directly calling <code>$lesson->context;</code>
1022 * @see get_context()
1025 protected $context = null;
1028 * Constructor method
1030 * @param object $properties
1031 * @param stdClass $cm course module object
1034 public function __construct($properties, $cm = null) {
1035 parent::__construct($properties);
1040 * Simply generates a lesson object given an array/object of properties
1041 * Overrides {@see lesson_base->create()}
1043 * @param object|array $properties
1046 public static function create($properties) {
1047 return new lesson($properties);
1051 * Generates a lesson object from the database given its id
1053 * @param int $lessonid
1056 public static function load($lessonid) {
1059 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
1060 print_error('invalidcoursemodule');
1062 return new lesson($lesson);
1066 * Deletes this lesson from the database
1068 public function delete() {
1070 require_once($CFG->libdir.'/gradelib.php');
1071 require_once($CFG->dirroot.'/calendar/lib.php');
1073 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1074 $context = context_module::instance($cm->id);
1076 $this->delete_all_overrides();
1078 $DB->delete_records("lesson", array("id"=>$this->properties->id));
1079 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
1080 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
1081 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
1082 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
1083 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
1084 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
1085 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
1086 foreach($events as $event) {
1087 $event = calendar_event::load($event);
1092 // Delete files associated with this module.
1093 $fs = get_file_storage();
1094 $fs->delete_area_files($context->id);
1096 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
1101 * Deletes a lesson override from the database and clears any corresponding calendar events
1103 * @param int $overrideid The id of the override being deleted
1104 * @return bool true on success
1106 public function delete_override($overrideid) {
1109 require_once($CFG->dirroot . '/calendar/lib.php');
1111 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1113 $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST);
1115 // Delete the events.
1116 $conds = array('modulename' => 'lesson',
1117 'instance' => $this->properties->id);
1118 if (isset($override->userid)) {
1119 $conds['userid'] = $override->userid;
1121 $conds['groupid'] = $override->groupid;
1123 $events = $DB->get_records('event', $conds);
1124 foreach ($events as $event) {
1125 $eventold = calendar_event::load($event);
1126 $eventold->delete();
1129 $DB->delete_records('lesson_overrides', array('id' => $overrideid));
1131 // Set the common parameters for one of the events we will be triggering.
1133 'objectid' => $override->id,
1134 'context' => context_module::instance($cm->id),
1136 'lessonid' => $override->lessonid
1139 // Determine which override deleted event to fire.
1140 if (!empty($override->userid)) {
1141 $params['relateduserid'] = $override->userid;
1142 $event = \mod_lesson\event\user_override_deleted::create($params);
1144 $params['other']['groupid'] = $override->groupid;
1145 $event = \mod_lesson\event\group_override_deleted::create($params);
1148 // Trigger the override deleted event.
1149 $event->add_record_snapshot('lesson_overrides', $override);
1156 * Deletes all lesson overrides from the database and clears any corresponding calendar events
1158 public function delete_all_overrides() {
1161 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id');
1162 foreach ($overrides as $override) {
1163 $this->delete_override($override->id);
1168 * Updates the lesson properties with override information for a user.
1170 * Algorithm: For each lesson setting, if there is a matching user-specific override,
1171 * then use that otherwise, if there are group-specific overrides, return the most
1172 * lenient combination of them. If neither applies, leave the quiz setting unchanged.
1174 * Special case: if there is more than one password that applies to the user, then
1175 * lesson->extrapasswords will contain an array of strings giving the remaining
1178 * @param int $userid The userid.
1180 public function update_effective_access($userid) {
1183 // Check for user override.
1184 $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid));
1187 $override = new stdClass();
1188 $override->available = null;
1189 $override->deadline = null;
1190 $override->timelimit = null;
1191 $override->review = null;
1192 $override->maxattempts = null;
1193 $override->retake = null;
1194 $override->password = null;
1197 // Check for group overrides.
1198 $groupings = groups_get_user_groups($this->properties->course, $userid);
1200 if (!empty($groupings[0])) {
1201 // Select all overrides that apply to the User's groups.
1202 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0]));
1203 $sql = "SELECT * FROM {lesson_overrides}
1204 WHERE groupid $extra AND lessonid = ?";
1205 $params[] = $this->properties->id;
1206 $records = $DB->get_records_sql($sql, $params);
1208 // Combine the overrides.
1209 $availables = array();
1210 $deadlines = array();
1211 $timelimits = array();
1213 $attempts = array();
1215 $passwords = array();
1217 foreach ($records as $gpoverride) {
1218 if (isset($gpoverride->available)) {
1219 $availables[] = $gpoverride->available;
1221 if (isset($gpoverride->deadline)) {
1222 $deadlines[] = $gpoverride->deadline;
1224 if (isset($gpoverride->timelimit)) {
1225 $timelimits[] = $gpoverride->timelimit;
1227 if (isset($gpoverride->review)) {
1228 $reviews[] = $gpoverride->review;
1230 if (isset($gpoverride->maxattempts)) {
1231 $attempts[] = $gpoverride->maxattempts;
1233 if (isset($gpoverride->retake)) {
1234 $retakes[] = $gpoverride->retake;
1236 if (isset($gpoverride->password)) {
1237 $passwords[] = $gpoverride->password;
1240 // If there is a user override for a setting, ignore the group override.
1241 if (is_null($override->available) && count($availables)) {
1242 $override->available = min($availables);
1244 if (is_null($override->deadline) && count($deadlines)) {
1245 if (in_array(0, $deadlines)) {
1246 $override->deadline = 0;
1248 $override->deadline = max($deadlines);
1251 if (is_null($override->timelimit) && count($timelimits)) {
1252 if (in_array(0, $timelimits)) {
1253 $override->timelimit = 0;
1255 $override->timelimit = max($timelimits);
1258 if (is_null($override->review) && count($reviews)) {
1259 $override->review = max($reviews);
1261 if (is_null($override->maxattempts) && count($attempts)) {
1262 $override->maxattempts = max($attempts);
1264 if (is_null($override->retake) && count($retakes)) {
1265 $override->retake = max($retakes);
1267 if (is_null($override->password) && count($passwords)) {
1268 $override->password = array_shift($passwords);
1269 if (count($passwords)) {
1270 $override->extrapasswords = $passwords;
1276 // Merge with lesson defaults.
1277 $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake');
1278 foreach ($keys as $key) {
1279 if (isset($override->{$key})) {
1280 $this->properties->{$key} = $override->{$key};
1284 // Special handling of lesson usepassword and password.
1285 if (isset($override->password)) {
1286 if ($override->password == '') {
1287 $this->properties->usepassword = 0;
1289 $this->properties->usepassword = 1;
1290 $this->properties->password = $override->password;
1291 if (isset($override->extrapasswords)) {
1292 $this->properties->extrapasswords = $override->extrapasswords;
1299 * Fetches messages from the session that may have been set in previous page
1303 * // Do not call this method directly instead use
1304 * $lesson->messages;
1309 protected function get_messages() {
1312 $messages = array();
1313 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1314 $messages = $SESSION->lesson_messages[$this->properties->id];
1315 unset($SESSION->lesson_messages[$this->properties->id]);
1322 * Get all of the attempts for the current user.
1324 * @param int $retries
1325 * @param bool $correct Optional: only fetch correct attempts
1326 * @param int $pageid Optional: only fetch attempts at the given page
1327 * @param int $userid Optional: defaults to the current user if not set
1328 * @return array|false
1330 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) {
1332 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries);
1334 $params['correct'] = 1;
1336 if ($pageid !== null) {
1337 $params['pageid'] = $pageid;
1339 if ($userid === null) {
1340 $params['userid'] = $USER->id;
1342 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC');
1346 * Returns the first page for the lesson or false if there isn't one.
1348 * This method should be called via the magic method __get();
1350 * $firstpage = $lesson->firstpage;
1353 * @return lesson_page|bool Returns the lesson_page specialised object or false
1355 protected function get_firstpage() {
1356 $pages = $this->load_all_pages();
1357 if (count($pages) > 0) {
1358 foreach ($pages as $page) {
1359 if ((int)$page->prevpageid === 0) {
1368 * Returns the last page for the lesson or false if there isn't one.
1370 * This method should be called via the magic method __get();
1372 * $lastpage = $lesson->lastpage;
1375 * @return lesson_page|bool Returns the lesson_page specialised object or false
1377 protected function get_lastpage() {
1378 $pages = $this->load_all_pages();
1379 if (count($pages) > 0) {
1380 foreach ($pages as $page) {
1381 if ((int)$page->nextpageid === 0) {
1390 * Returns the id of the first page of this lesson. (prevpageid = 0)
1393 protected function get_firstpageid() {
1395 if ($this->firstpageid == null) {
1396 if (!$this->loadedallpages) {
1397 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0));
1398 if (!$firstpageid) {
1399 print_error('cannotfindfirstpage', 'lesson');
1401 $this->firstpageid = $firstpageid;
1403 $firstpage = $this->get_firstpage();
1404 $this->firstpageid = $firstpage->id;
1407 return $this->firstpageid;
1411 * Returns the id of the last page of this lesson. (nextpageid = 0)
1414 public function get_lastpageid() {
1416 if ($this->lastpageid == null) {
1417 if (!$this->loadedallpages) {
1418 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0));
1420 print_error('cannotfindlastpage', 'lesson');
1422 $this->lastpageid = $lastpageid;
1424 $lastpageid = $this->get_lastpage();
1425 $this->lastpageid = $lastpageid->id;
1429 return $this->lastpageid;
1433 * Gets the next page id to display after the one that is provided.
1434 * @param int $nextpageid
1437 public function get_next_page($nextpageid) {
1439 $allpages = $this->load_all_pages();
1440 if ($this->properties->nextpagedefault) {
1441 // in Flash Card mode...first get number of retakes
1442 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id));
1445 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) {
1446 foreach ($allpages as $nextpage) {
1447 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) {
1452 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) {
1453 foreach ($allpages as $nextpage) {
1454 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) {
1461 if ($this->properties->maxpages) {
1462 // check number of pages viewed (in the lesson)
1463 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) {
1467 return $nextpage->id;
1470 // In a normal lesson mode
1471 foreach ($allpages as $nextpage) {
1472 if ((int)$nextpage->id === (int)$nextpageid) {
1473 return $nextpage->id;
1480 * Sets a message against the session for this lesson that will displayed next
1481 * time the lesson processes messages
1483 * @param string $message
1484 * @param string $class
1485 * @param string $align
1488 public function add_message($message, $class="notifyproblem", $align='center') {
1491 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) {
1492 $SESSION->lesson_messages = array();
1493 $SESSION->lesson_messages[$this->properties->id] = array();
1494 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
1495 $SESSION->lesson_messages[$this->properties->id] = array();
1498 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align);
1504 * Check if the lesson is accessible at the present time
1505 * @return bool True if the lesson is accessible, false otherwise
1507 public function is_accessible() {
1508 $available = $this->properties->available;
1509 $deadline = $this->properties->deadline;
1510 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline));
1514 * Starts the lesson time for the current user
1515 * @return bool Returns true
1517 public function start_timer() {
1520 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1523 // Trigger lesson started event.
1524 $event = \mod_lesson\event\lesson_started::create(array(
1525 'objectid' => $this->properties()->id,
1526 'context' => context_module::instance($cm->id),
1527 'courseid' => $this->properties()->course
1531 $USER->startlesson[$this->properties->id] = true;
1532 $startlesson = new stdClass;
1533 $startlesson->lessonid = $this->properties->id;
1534 $startlesson->userid = $USER->id;
1535 $startlesson->starttime = time();
1536 $startlesson->lessontime = time();
1537 $DB->insert_record('lesson_timer', $startlesson);
1538 if ($this->properties->timelimit) {
1539 $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center');
1545 * Updates the timer to the current time and returns the new timer object
1546 * @param bool $restart If set to true the timer is restarted
1547 * @param bool $continue If set to true AND $restart=true then the timer
1548 * will continue from a previous attempt
1549 * @return stdClass The new timer
1551 public function update_timer($restart=false, $continue=false, $endreached =false) {
1554 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1557 // get time information for this user
1558 $params = array("lessonid" => $this->properties->id, "userid" => $USER->id);
1559 if (!$timer = $DB->get_records('lesson_timer', $params, 'starttime DESC', '*', 0, 1)) {
1560 $this->start_timer();
1561 $timer = $DB->get_records('lesson_timer', $params, 'starttime DESC', '*', 0, 1);
1563 $timer = current($timer); // This will get the latest start time record.
1567 // continue a previous test, need to update the clock (think this option is disabled atm)
1568 $timer->starttime = time() - ($timer->lessontime - $timer->starttime);
1570 // Trigger lesson resumed event.
1571 $event = \mod_lesson\event\lesson_resumed::create(array(
1572 'objectid' => $this->properties->id,
1573 'context' => context_module::instance($cm->id),
1574 'courseid' => $this->properties->course
1579 // starting over, so reset the clock
1580 $timer->starttime = time();
1582 // Trigger lesson restarted event.
1583 $event = \mod_lesson\event\lesson_restarted::create(array(
1584 'objectid' => $this->properties->id,
1585 'context' => context_module::instance($cm->id),
1586 'courseid' => $this->properties->course
1593 $timer->lessontime = time();
1594 $timer->completed = $endreached;
1595 $DB->update_record('lesson_timer', $timer);
1597 // Update completion state.
1598 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1600 $course = get_course($cm->course);
1601 $completion = new completion_info($course);
1602 if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) {
1603 $completion->update_state($cm, COMPLETION_COMPLETE);
1609 * Updates the timer to the current time then stops it by unsetting the user var
1610 * @return bool Returns true
1612 public function stop_timer() {
1614 unset($USER->startlesson[$this->properties->id]);
1616 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course,
1619 // Trigger lesson ended event.
1620 $event = \mod_lesson\event\lesson_ended::create(array(
1621 'objectid' => $this->properties()->id,
1622 'context' => context_module::instance($cm->id),
1623 'courseid' => $this->properties()->course
1627 return $this->update_timer(false, false, true);
1631 * Checks to see if the lesson has pages
1633 public function has_pages() {
1635 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id));
1636 return ($pagecount>0);
1640 * Returns the link for the related activity
1641 * @return array|false
1643 public function link_for_activitylink() {
1645 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink));
1647 $modname = $DB->get_field('modules', 'name', array('id' => $module->module));
1649 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance));
1650 if ($instancename) {
1651 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', array('id'=>$this->properties->activitylink)),
1652 get_string('activitylinkname', 'lesson', $instancename),
1653 array('class'=>'centerpadded lessonbutton standardbutton'));
1661 * Loads the requested page.
1663 * This function will return the requested page id as either a specialised
1664 * lesson_page object OR as a generic lesson_page.
1665 * If the page has been loaded previously it will be returned from the pages
1666 * array, otherwise it will be loaded from the database first
1668 * @param int $pageid
1669 * @return lesson_page A lesson_page object or an object that extends it
1671 public function load_page($pageid) {
1672 if (!array_key_exists($pageid, $this->pages)) {
1673 $manager = lesson_page_type_manager::get($this);
1674 $this->pages[$pageid] = $manager->load_page($pageid, $this);
1676 return $this->pages[$pageid];
1680 * Loads ALL of the pages for this lesson
1682 * @return array An array containing all pages from this lesson
1684 public function load_all_pages() {
1685 if (!$this->loadedallpages) {
1686 $manager = lesson_page_type_manager::get($this);
1687 $this->pages = $manager->load_all_pages($this);
1688 $this->loadedallpages = true;
1690 return $this->pages;
1694 * Duplicate the lesson page.
1696 * @param int $pageid Page ID of the page to duplicate.
1699 public function duplicate_page($pageid) {
1701 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
1702 $context = context_module::instance($cm->id);
1704 $page = $this->load_page($pageid);
1705 $properties = $page->properties();
1706 // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here.
1707 if (!$properties->qoption) {
1708 unset($properties->qoption);
1710 if (!$properties->layout) {
1711 unset($properties->layout);
1713 if (!$properties->display) {
1714 unset($properties->display);
1717 $properties->pageid = $pageid;
1718 // Add text and format into the format required to create a new page.
1719 $properties->contents_editor = array(
1720 'text' => $properties->contents,
1721 'format' => $properties->contentsformat
1723 $answers = $page->get_answers();
1724 // Answers need to be added to $properties.
1726 $answerids = array();
1727 foreach ($answers as $answer) {
1728 // Needs to be rearranged to work with the create function.
1729 $properties->answer_editor[$i] = array(
1730 'text' => $answer->answer,
1731 'format' => $answer->answerformat
1734 $properties->response_editor[$i] = array(
1735 'text' => $answer->response,
1736 'format' => $answer->responseformat
1738 $answerids[] = $answer->id;
1740 $properties->jumpto[$i] = $answer->jumpto;
1741 $properties->score[$i] = $answer->score;
1745 // Create the duplicate page.
1746 $newlessonpage = lesson_page::create($properties, $this, $context, $PAGE->course->maxbytes);
1747 $newanswers = $newlessonpage->get_answers();
1748 // Copy over the file areas as well.
1749 $this->copy_page_files('page_contents', $pageid, $newlessonpage->id, $context->id);
1751 foreach ($newanswers as $answer) {
1752 if (isset($answer->answer) && strpos($answer->answer, '@@PLUGINFILE@@') !== false) {
1753 $this->copy_page_files('page_answers', $answerids[$j], $answer->id, $context->id);
1755 if (isset($answer->response) && !is_array($answer->response) && strpos($answer->response, '@@PLUGINFILE@@') !== false) {
1756 $this->copy_page_files('page_responses', $answerids[$j], $answer->id, $context->id);
1763 * Copy the files from one page to another.
1765 * @param string $filearea Area that the files are stored.
1766 * @param int $itemid Item ID.
1767 * @param int $newitemid The item ID for the new page.
1768 * @param int $contextid Context ID for this page.
1771 protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) {
1772 $fs = get_file_storage();
1773 $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid);
1774 foreach ($files as $file) {
1775 $fieldupdates = array('itemid' => $newitemid);
1776 $fs->create_file_from_storedfile($fieldupdates, $file);
1781 * Determines if a jumpto value is correct or not.
1783 * returns true if jumpto page is (logically) after the pageid page or
1784 * if the jumpto value is a special value. Returns false in all other cases.
1786 * @param int $pageid Id of the page from which you are jumping from.
1787 * @param int $jumpto The jumpto number.
1788 * @return boolean True or false after a series of tests.
1790 public function jumpto_is_correct($pageid, $jumpto) {
1793 // first test the special values
1797 } elseif ($jumpto == LESSON_NEXTPAGE) {
1799 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
1801 } elseif ($jumpto == LESSON_RANDOMPAGE) {
1803 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
1805 } elseif ($jumpto == LESSON_EOL) {
1809 $pages = $this->load_all_pages();
1810 $apageid = $pages[$pageid]->nextpageid;
1811 while ($apageid != 0) {
1812 if ($jumpto == $apageid) {
1815 $apageid = $pages[$apageid]->nextpageid;
1821 * Returns the time a user has remaining on this lesson
1822 * @param int $starttime Starttime timestamp
1825 public function time_remaining($starttime) {
1826 $timeleft = $starttime + $this->properties->timelimit - time();
1827 $hours = floor($timeleft/3600);
1828 $timeleft = $timeleft - ($hours * 3600);
1829 $minutes = floor($timeleft/60);
1830 $secs = $timeleft - ($minutes * 60);
1832 if ($minutes < 10) {
1833 $minutes = "0$minutes";
1840 $output[] = $minutes;
1842 $output = implode(':', $output);
1847 * Interprets LESSON_CLUSTERJUMP jumpto value.
1849 * This will select a page randomly
1850 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson
1851 * and the page selected will be a page that has not been viewed already
1852 * and if any pages are within a branch table or end of branch then only 1 page within
1853 * the branch table or end of branch will be randomly selected (sub clustering).
1855 * @param int $pageid Id of the current page from which we are jumping from.
1856 * @param int $userid Id of the user.
1857 * @return int The id of the next page.
1859 public function cluster_jump($pageid, $userid=null) {
1862 if ($userid===null) {
1863 $userid = $USER->id;
1865 // get the number of retakes
1866 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) {
1869 // get all the lesson_attempts aka what the user has seen
1870 $seenpages = array();
1871 if ($attempts = $this->get_attempts($retakes)) {
1872 foreach ($attempts as $attempt) {
1873 $seenpages[$attempt->pageid] = $attempt->pageid;
1878 // get the lesson pages
1879 $lessonpages = $this->load_all_pages();
1880 // find the start of the cluster
1881 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
1882 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) {
1885 $pageid = $lessonpages[$pageid]->prevpageid;
1888 $clusterpages = array();
1889 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER));
1891 foreach ($clusterpages as $key=>$cluster) {
1892 // Remove the page if it is in a branch table or is an endofbranch.
1893 if ($this->is_sub_page_of_type($cluster->id,
1894 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))
1895 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) {
1896 unset($clusterpages[$key]);
1897 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) {
1898 // If branchtable, check to see if any pages inside have been viewed.
1899 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1901 foreach ($branchpages as $branchpage) {
1902 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed.
1906 if ($flag && count($branchpages) > 0) {
1907 // Add branch table.
1908 $unseen[] = $cluster;
1910 } elseif ($cluster->is_unseen($seenpages)) {
1911 $unseen[] = $cluster;
1915 if (count($unseen) > 0) {
1916 // it does not contain elements, then use exitjump, otherwise find out next page/branch
1917 $nextpage = $unseen[rand(0, count($unseen)-1)];
1918 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) {
1919 // if branch table, then pick a random page inside of it
1920 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
1921 return $branchpages[rand(0, count($branchpages)-1)]->id;
1922 } else { // otherwise, return the page's id
1923 return $nextpage->id;
1926 // seen all there is to see, leave the cluster
1927 if (end($clusterpages)->nextpageid == 0) {
1930 $clusterendid = $pageid;
1931 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page.
1932 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1935 $clusterendid = $lessonpages[$clusterendid]->nextpageid;
1937 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id));
1938 if ($exitjump == LESSON_NEXTPAGE) {
1939 $exitjump = $lessonpages[$clusterendid]->nextpageid;
1941 if ($exitjump == 0) {
1943 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) {
1946 if (!array_key_exists($exitjump, $lessonpages)) {
1948 foreach ($lessonpages as $page) {
1949 if ($page->id === $clusterendid) {
1951 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) {
1952 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id));
1953 if ($exitjump == LESSON_NEXTPAGE) {
1954 $exitjump = $lessonpages[$page->id]->nextpageid;
1960 if (!array_key_exists($exitjump, $lessonpages)) {
1970 * Finds all pages that appear to be a subtype of the provided pageid until
1971 * an end point specified within $ends is encountered or no more pages exist
1973 * @param int $pageid
1974 * @param array $ends An array of LESSON_PAGE_* types that signify an end of
1976 * @return array An array of specialised lesson_page objects
1978 public function get_sub_pages_of($pageid, array $ends) {
1979 $lessonpages = $this->load_all_pages();
1980 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table
1984 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) {
1987 $pages[] = $lessonpages[$pageid];
1988 $pageid = $lessonpages[$pageid]->nextpageid;
1995 * Checks to see if the specified page[id] is a subpage of a type specified in
1996 * the $types array, until either there are no more pages of we find a type
1997 * corresponding to that of a type specified in $ends
1999 * @param int $pageid The id of the page to check
2000 * @param array $types An array of types that would signify this page was a subpage
2001 * @param array $ends An array of types that mean this is not a subpage
2004 public function is_sub_page_of_type($pageid, array $types, array $ends) {
2005 $pages = $this->load_all_pages();
2006 $pageid = $pages[$pageid]->prevpageid; // move up one
2008 array_unshift($ends, 0);
2009 // go up the pages till branch table
2011 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) {
2013 } else if (in_array($pages[$pageid]->qtype, $types)) {
2016 $pageid = $pages[$pageid]->prevpageid;
2021 * Move a page resorting all other pages.
2023 * @param int $pageid
2027 public function resort_pages($pageid, $after) {
2030 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
2031 $context = context_module::instance($cm->id);
2033 $pages = $this->load_all_pages();
2035 if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) {
2036 print_error('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id");
2039 $pagetomove = clone($pages[$pageid]);
2040 unset($pages[$pageid]);
2044 $pageids['p0'] = $pageid;
2046 foreach ($pages as $page) {
2047 $pageids[] = $page->id;
2048 if ($page->id == $after) {
2049 $pageids[] = $pageid;
2053 $pageidsref = $pageids;
2056 $next = next($pageidsref);
2057 foreach ($pageids as $pid) {
2058 if ($pid === $pageid) {
2059 $page = $pagetomove;
2061 $page = $pages[$pid];
2063 if ($page->prevpageid != $prev || $page->nextpageid != $next) {
2064 $page->move($next, $prev);
2066 if ($pid === $pageid) {
2067 // We will trigger an event.
2068 $pageupdated = array('next' => $next, 'prev' => $prev);
2073 $next = next($pageidsref);
2079 // Trigger an event: page moved.
2080 if (!empty($pageupdated)) {
2081 $eventparams = array(
2082 'context' => $context,
2083 'objectid' => $pageid,
2085 'pagetype' => $page->get_typestring(),
2086 'prevpageid' => $pageupdated['prev'],
2087 'nextpageid' => $pageupdated['next']
2090 $event = \mod_lesson\event\page_moved::create($eventparams);
2097 * Return the lesson context object.
2099 * @return stdClass context
2102 public function get_context() {
2103 if ($this->context == null) {
2104 $this->context = context_module::instance($this->get_cm()->id);
2106 return $this->context;
2110 * Set the lesson course module object.
2112 * @param stdClass $cm course module objct
2115 private function set_cm($cm) {
2120 * Return the lesson course module object.
2122 * @return stdClass course module
2125 public function get_cm() {
2126 if ($this->cm == null) {
2127 $this->cm = get_coursemodule_from_instance('lesson', $this->properties->id);
2133 * Check if the user can manage the lesson activity.
2135 * @return bool true if the user can manage the lesson
2138 public function can_manage() {
2139 return has_capability('mod/lesson:manage', $this->get_context());
2143 * Check if time restriction is applied.
2145 * @return mixed false if there aren't restrictions or an object with the restriction information
2148 public function get_time_restriction_status() {
2149 if ($this->can_manage()) {
2153 if (!$this->is_accessible()) {
2154 if ($this->properties->deadline != 0 && time() > $this->properties->deadline) {
2155 $status = ['reason' => 'lessonclosed', 'time' => $this->properties->deadline];
2157 $status = ['reason' => 'lessonopen', 'time' => $this->properties->available];
2159 return (object) $status;
2165 * Check if password restriction is applied.
2167 * @param string $userpassword the user password to check (if the restriction is set)
2168 * @return mixed false if there aren't restrictions or an object with the restriction information
2171 public function get_password_restriction_status($userpassword) {
2173 if ($this->can_manage()) {
2177 if ($this->properties->usepassword && empty($USER->lessonloggedin[$this->id])) {
2178 $correctpass = false;
2179 if (!empty($userpassword) &&
2180 (($this->properties->password == md5(trim($userpassword))) || ($this->properties->password == trim($userpassword)))) {
2181 // With or without md5 for backward compatibility (MDL-11090).
2182 $correctpass = true;
2183 $USER->lessonloggedin[$this->id] = true;
2184 } else if (isset($this->properties->extrapasswords)) {
2185 // Group overrides may have additional passwords.
2186 foreach ($this->properties->extrapasswords as $password) {
2187 if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) {
2188 $correctpass = true;
2189 $USER->lessonloggedin[$this->id] = true;
2193 return !$correctpass;
2199 * Check if dependencies restrictions are applied.
2201 * @return mixed false if there aren't restrictions or an object with the restriction information
2204 public function get_dependencies_restriction_status() {
2206 if ($this->can_manage()) {
2210 if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties->dependency))) {
2211 // Lesson exists, so we can proceed.
2212 $conditions = unserialize($this->properties->conditions);
2213 // Assume false for all.
2215 // Check for the timespent condition.
2216 if ($conditions->timespent) {
2218 if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2219 // Go through all the times and test to see if any of them satisfy the condition.
2220 foreach ($attempttimes as $attempttime) {
2221 $duration = $attempttime->lessontime - $attempttime->starttime;
2222 if ($conditions->timespent < $duration / 60) {
2228 $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent);
2231 // Check for the gradebetterthan condition.
2232 if ($conditions->gradebetterthan) {
2233 $gradebetterthan = false;
2234 if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) {
2235 // Go through all the grades and test to see if any of them satisfy the condition.
2236 foreach ($studentgrades as $studentgrade) {
2237 if ($studentgrade->grade >= $conditions->gradebetterthan) {
2238 $gradebetterthan = true;
2242 if (!$gradebetterthan) {
2243 $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan);
2246 // Check for the completed condition.
2247 if ($conditions->completed) {
2248 if (!$DB->count_records('lesson_grades', array('userid' => $USER->id, 'lessonid' => $dependentlesson->id))) {
2249 $errors[] = get_string('completederror', 'lesson');
2252 if (!empty($errors)) {
2253 return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson];
2262 * Abstract class to provide a core functions to the all lesson classes
2264 * This class should be abstracted by ALL classes with the lesson module to ensure
2265 * that all classes within this module can be interacted with in the same way.
2267 * This class provides the user with a basic properties array that can be fetched
2268 * or set via magic methods, or alternatively by defining methods get_blah() or
2269 * set_blah() within the extending object.
2271 * @copyright 2009 Sam Hemelryk
2272 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2274 abstract class lesson_base {
2277 * An object containing properties
2280 protected $properties;
2284 * @param stdClass $properties
2286 public function __construct($properties) {
2287 $this->properties = (object)$properties;
2291 * Magic property method
2293 * Attempts to call a set_$key method if one exists otherwise falls back
2294 * to simply set the property
2296 * @param string $key
2297 * @param mixed $value
2299 public function __set($key, $value) {
2300 if (method_exists($this, 'set_'.$key)) {
2301 $this->{'set_'.$key}($value);
2303 $this->properties->{$key} = $value;
2309 * Attempts to call a get_$key method to return the property and ralls over
2310 * to return the raw property
2315 public function __get($key) {
2316 if (method_exists($this, 'get_'.$key)) {
2317 return $this->{'get_'.$key}();
2319 return $this->properties->{$key};
2323 * Stupid PHP needs an isset magic method if you use the get magic method and
2324 * still want empty calls to work.... blah ~!
2326 * @param string $key
2329 public function __isset($key) {
2330 if (method_exists($this, 'get_'.$key)) {
2331 $val = $this->{'get_'.$key}();
2332 return !empty($val);
2334 return !empty($this->properties->{$key});
2337 //NOTE: E_STRICT does not allow to change function signature!
2340 * If implemented should create a new instance, save it in the DB and return it
2342 //public static function create() {}
2344 * If implemented should load an instance from the DB and return it
2346 //public static function load() {}
2348 * Fetches all of the properties of the object
2351 public function properties() {
2352 return $this->properties;
2358 * Abstract class representation of a page associated with a lesson.
2360 * This class should MUST be extended by all specialised page types defined in
2361 * mod/lesson/pagetypes/.
2362 * There are a handful of abstract methods that need to be defined as well as
2363 * severl methods that can optionally be defined in order to make the page type
2364 * operate in the desired way
2366 * Database properties
2367 * @property int $id The id of this lesson page
2368 * @property int $lessonid The id of the lesson this page belongs to
2369 * @property int $prevpageid The id of the page before this one
2370 * @property int $nextpageid The id of the next page in the page sequence
2371 * @property int $qtype Identifies the page type of this page
2372 * @property int $qoption Used to record page type specific options
2373 * @property int $layout Used to record page specific layout selections
2374 * @property int $display Used to record page specific display selections
2375 * @property int $timecreated Timestamp for when the page was created
2376 * @property int $timemodified Timestamp for when the page was last modified
2377 * @property string $title The title of this page
2378 * @property string $contents The rich content shown to describe the page
2379 * @property int $contentsformat The format of the contents field
2381 * Calculated properties
2382 * @property-read array $answers An array of answers for this page
2383 * @property-read bool $displayinmenublock Toggles display in the left menu block
2384 * @property-read array $jumps An array containing all the jumps this page uses
2385 * @property-read lesson $lesson The lesson this page belongs to
2386 * @property-read int $type The type of the page [question | structure]
2387 * @property-read typeid The unique identifier for the page type
2388 * @property-read typestring The string that describes this page type
2391 * @copyright 2009 Sam Hemelryk
2392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2394 abstract class lesson_page extends lesson_base {
2397 * A reference to the lesson this page belongs to
2400 protected $lesson = null;
2402 * Contains the answers to this lesson_page once loaded
2405 protected $answers = null;
2407 * This sets the type of the page, can be one of the constants defined below
2410 protected $type = 0;
2413 * Constants used to identify the type of the page
2415 const TYPE_QUESTION = 0;
2416 const TYPE_STRUCTURE = 1;
2419 * This method should return the integer used to identify the page type within
2420 * the database and throughout code. This maps back to the defines used in 1.x
2424 abstract protected function get_typeid();
2426 * This method should return the string that describes the pagetype
2430 abstract protected function get_typestring();
2433 * This method gets called to display the page to the user taking the lesson
2435 * @param object $renderer
2436 * @param object $attempt
2439 abstract public function display($renderer, $attempt);
2442 * Creates a new lesson_page within the database and returns the correct pagetype
2443 * object to use to interact with the new lesson
2447 * @param object $properties
2448 * @param lesson $lesson
2449 * @return lesson_page Specialised object that extends lesson_page
2451 final public static function create($properties, lesson $lesson, $context, $maxbytes) {
2453 $newpage = new stdClass;
2454 $newpage->title = $properties->title;
2455 $newpage->contents = $properties->contents_editor['text'];
2456 $newpage->contentsformat = $properties->contents_editor['format'];
2457 $newpage->lessonid = $lesson->id;
2458 $newpage->timecreated = time();
2459 $newpage->qtype = $properties->qtype;
2460 $newpage->qoption = (isset($properties->qoption))?1:0;
2461 $newpage->layout = (isset($properties->layout))?1:0;
2462 $newpage->display = (isset($properties->display))?1:0;
2463 $newpage->prevpageid = 0; // this is a first page
2464 $newpage->nextpageid = 0; // this is the only page
2466 if ($properties->pageid) {
2467 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid');
2469 print_error('cannotfindpages', 'lesson');
2471 $newpage->prevpageid = $prevpage->id;
2472 $newpage->nextpageid = $prevpage->nextpageid;
2474 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id');
2476 // This is the first page, there are existing pages put this at the start
2477 $newpage->nextpageid = $nextpage->id;
2481 $newpage->id = $DB->insert_record("lesson_pages", $newpage);
2483 $editor = new stdClass;
2484 $editor->id = $newpage->id;
2485 $editor->contents_editor = $properties->contents_editor;
2486 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id);
2487 $DB->update_record("lesson_pages", $editor);
2489 if ($newpage->prevpageid > 0) {
2490 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid));
2492 if ($newpage->nextpageid > 0) {
2493 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid));
2496 $page = lesson_page::load($newpage, $lesson);
2497 $page->create_answers($properties);
2499 // Trigger an event: page created.
2500 $eventparams = array(
2501 'context' => $context,
2502 'objectid' => $newpage->id,
2504 'pagetype' => $page->get_typestring()
2507 $event = \mod_lesson\event\page_created::create($eventparams);
2508 $snapshot = clone($newpage);
2509 $snapshot->timemodified = 0;
2510 $event->add_record_snapshot('lesson_pages', $snapshot);
2513 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess');
2519 * This method loads a page object from the database and returns it as a
2520 * specialised object that extends lesson_page
2525 * @param lesson $lesson
2526 * @return lesson_page Specialised lesson_page object
2528 final public static function load($id, lesson $lesson) {
2531 if (is_object($id) && !empty($id->qtype)) {
2534 $page = $DB->get_record("lesson_pages", array("id" => $id));
2536 print_error('cannotfindpages', 'lesson');
2539 $manager = lesson_page_type_manager::get($lesson);
2541 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype);
2542 if (!class_exists($class)) {
2543 $class = 'lesson_page';
2546 return new $class($page, $lesson);
2550 * Deletes a lesson_page from the database as well as any associated records.
2554 final public function delete() {
2557 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
2558 $context = context_module::instance($cm->id);
2560 // Delete files associated with attempts.
2561 $fs = get_file_storage();
2562 if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) {
2563 foreach ($attempts as $attempt) {
2564 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id);
2568 // Then delete all the associated records...
2569 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id));
2571 $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id));
2572 // ...now delete the answers...
2573 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id));
2574 // ..and the page itself
2575 $DB->delete_records("lesson_pages", array("id" => $this->properties->id));
2577 // Trigger an event: page deleted.
2578 $eventparams = array(
2579 'context' => $context,
2580 'objectid' => $this->properties->id,
2582 'pagetype' => $this->get_typestring()
2585 $event = \mod_lesson\event\page_deleted::create($eventparams);
2586 $event->add_record_snapshot('lesson_pages', $this->properties);
2589 // Delete files associated with this page.
2590 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id);
2591 $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $this->properties->id);
2592 $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $this->properties->id);
2594 // repair the hole in the linkage
2595 if (!$this->properties->prevpageid && !$this->properties->nextpageid) {
2596 //This is the only page, no repair needed
2597 } elseif (!$this->properties->prevpageid) {
2598 // this is the first page...
2599 $page = $this->lesson->load_page($this->properties->nextpageid);
2600 $page->move(null, 0);
2601 } elseif (!$this->properties->nextpageid) {
2602 // this is the last page...
2603 $page = $this->lesson->load_page($this->properties->prevpageid);
2606 // page is in the middle...
2607 $prevpage = $this->lesson->load_page($this->properties->prevpageid);
2608 $nextpage = $this->lesson->load_page($this->properties->nextpageid);
2610 $prevpage->move($nextpage->id);
2611 $nextpage->move(null, $prevpage->id);
2617 * Moves a page by updating its nextpageid and prevpageid values within
2621 * @param int $nextpageid
2622 * @param int $prevpageid
2624 final public function move($nextpageid=null, $prevpageid=null) {
2626 if ($nextpageid === null) {
2627 $nextpageid = $this->properties->nextpageid;
2629 if ($prevpageid === null) {
2630 $prevpageid = $this->properties->prevpageid;
2632 $obj = new stdClass;
2633 $obj->id = $this->properties->id;
2634 $obj->prevpageid = $prevpageid;
2635 $obj->nextpageid = $nextpageid;
2636 $DB->update_record('lesson_pages', $obj);
2640 * Returns the answers that are associated with this page in the database
2645 final public function get_answers() {
2647 if ($this->answers === null) {
2648 $this->answers = array();
2649 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id');
2651 // It is possible that a lesson upgraded from Moodle 1.9 still
2652 // contains questions without any answers [MDL-25632].
2653 // debugging(get_string('cannotfindanswer', 'lesson'));
2656 foreach ($answers as $answer) {
2657 $this->answers[count($this->answers)] = new lesson_page_answer($answer);
2660 return $this->answers;
2664 * Returns the lesson this page is associated with
2668 final protected function get_lesson() {
2669 return $this->lesson;
2673 * Returns the type of page this is. Not to be confused with page type
2677 final protected function get_type() {
2682 * Records an attempt at this page
2685 * @global moodle_database $DB
2686 * @param stdClass $context
2687 * @return stdClass Returns the result of the attempt
2689 final public function record_attempt($context) {
2690 global $DB, $USER, $OUTPUT, $PAGE;
2693 * This should be overridden by each page type to actually check the response
2694 * against what ever custom criteria they have defined
2696 $result = $this->check_answer();
2698 $result->attemptsremaining = 0;
2699 $result->maxattemptsreached = false;
2701 if ($result->noanswer) {
2702 $result->newpageid = $this->properties->id; // display same page again
2703 $result->feedback = get_string('noanswer', 'lesson');
2705 if (!has_capability('mod/lesson:manage', $context)) {
2706 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2708 // Get the number of attempts that have been made on this question for this student and retake,
2709 $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson->id,
2710 'userid' => $USER->id, 'pageid' => $this->properties->id, 'retry' => $nretakes));
2712 // Check if they have reached (or exceeded) the maximum number of attempts allowed.
2713 if ($nattempts >= $this->lesson->maxattempts) {
2714 $result->maxattemptsreached = true;
2715 $result->feedback = get_string('maximumnumberofattemptsreached', 'lesson');
2716 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
2720 // record student's attempt
2721 $attempt = new stdClass;
2722 $attempt->lessonid = $this->lesson->id;
2723 $attempt->pageid = $this->properties->id;
2724 $attempt->userid = $USER->id;
2725 $attempt->answerid = $result->answerid;
2726 $attempt->retry = $nretakes;
2727 $attempt->correct = $result->correctanswer;
2728 if($result->userresponse !== null) {
2729 $attempt->useranswer = $result->userresponse;
2732 $attempt->timeseen = time();
2733 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record
2734 $userisreviewing = false;
2735 if (isset($USER->modattempts[$this->lesson->id])) {
2736 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high
2737 $userisreviewing = true;
2740 // Only insert a record if we are not reviewing the lesson.
2741 if (!$userisreviewing) {
2742 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) {
2743 $attempt->id = $DB->insert_record("lesson_attempts", $attempt);
2744 // Trigger an event: question answered.
2745 $eventparams = array(
2746 'context' => context_module::instance($PAGE->cm->id),
2747 'objectid' => $this->properties->id,
2749 'pagetype' => $this->get_typestring()
2752 $event = \mod_lesson\event\question_answered::create($eventparams);
2753 $event->add_record_snapshot('lesson_attempts', $attempt);
2756 // Increase the number of attempts made.
2760 // "number of attempts remaining" message if $this->lesson->maxattempts > 1
2761 // displaying of message(s) is at the end of page for more ergonomic display
2762 if (!$result->correctanswer && ($result->newpageid == 0)) {
2763 // retreive the number of attempts left counter for displaying at bottom of feedback page
2764 if ($nattempts >= $this->lesson->maxattempts) {
2765 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2766 $result->maxattemptsreached = true;
2768 $result->newpageid = LESSON_NEXTPAGE;
2769 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt
2770 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts;
2774 // TODO: merge this code with the jump code below. Convert jumpto page into a proper page id
2775 if ($result->newpageid == 0) {
2776 $result->newpageid = $this->properties->id;
2777 } elseif ($result->newpageid == LESSON_NEXTPAGE) {
2778 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid);
2781 // Determine default feedback if necessary
2782 if (empty($result->response)) {
2783 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) {
2784 // These conditions have been met:
2785 // 1. The lesson manager has not supplied feedback to the student
2786 // 2. Not displaying default feedback
2787 // 3. The user did provide an answer
2788 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question)
2790 $result->nodefaultresponse = true; // This will cause a redirect below
2791 } else if ($result->isessayquestion) {
2792 $result->response = get_string('defaultessayresponse', 'lesson');
2793 } else if ($result->correctanswer) {
2794 $result->response = get_string('thatsthecorrectanswer', 'lesson');
2796 $result->response = get_string('thatsthewronganswer', 'lesson');
2800 if ($result->response) {
2801 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) {
2802 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id));
2803 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id));
2804 if ($qattempts == 1) {
2805 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback');
2807 $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback');
2810 $result->feedback = '';
2812 $class = 'response';
2813 if ($result->correctanswer) {
2814 $class .= ' correct'; // CSS over-ride this if they exist (!important).
2815 } else if (!$result->isessayquestion) {
2816 $class .= ' incorrect'; // CSS over-ride this if they exist (!important).
2818 $options = new stdClass;
2819 $options->noclean = true;
2820 $options->para = true;
2821 $options->overflowdiv = true;
2822 $options->context = $context;
2824 $result->feedback .= $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options),
2825 'generalbox boxaligncenter');
2826 if (isset($result->studentanswerformat)) {
2827 // This is the student's answer so it should be cleaned.
2828 $studentanswer = format_text($result->studentanswer, $result->studentanswerformat,
2829 array('context' => $context, 'para' => true));
2831 $studentanswer = format_string($result->studentanswer);
2833 $result->feedback .= '<div class="correctanswer generalbox"><em>'
2834 . get_string("youranswer", "lesson").'</em> : ' . $studentanswer;
2835 if (isset($result->responseformat)) {
2836 $result->response = file_rewrite_pluginfile_urls($result->response, 'pluginfile.php', $context->id,
2837 'mod_lesson', 'page_responses', $result->answerid);
2838 $result->feedback .= $OUTPUT->box(format_text($result->response, $result->responseformat, $options)
2841 $result->feedback .= $OUTPUT->box($result->response, $class);
2843 $result->feedback .= '</div>';
2851 * Returns the string for a jump name
2854 * @param int $jumpto Jump code or page ID
2857 final protected function get_jump_name($jumpto) {
2859 static $jumpnames = array();
2861 if (!array_key_exists($jumpto, $jumpnames)) {
2862 if ($jumpto == LESSON_THISPAGE) {
2863 $jumptitle = get_string('thispage', 'lesson');
2864 } elseif ($jumpto == LESSON_NEXTPAGE) {
2865 $jumptitle = get_string('nextpage', 'lesson');
2866 } elseif ($jumpto == LESSON_EOL) {
2867 $jumptitle = get_string('endoflesson', 'lesson');
2868 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
2869 $jumptitle = get_string('unseenpageinbranch', 'lesson');
2870 } elseif ($jumpto == LESSON_PREVIOUSPAGE) {
2871 $jumptitle = get_string('previouspage', 'lesson');
2872 } elseif ($jumpto == LESSON_RANDOMPAGE) {
2873 $jumptitle = get_string('randompageinbranch', 'lesson');
2874 } elseif ($jumpto == LESSON_RANDOMBRANCH) {
2875 $jumptitle = get_string('randombranch', 'lesson');
2876 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
2877 $jumptitle = get_string('clusterjump', 'lesson');
2879 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) {
2880 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>';
2883 $jumpnames[$jumpto] = format_string($jumptitle,true);
2886 return $jumpnames[$jumpto];
2890 * Constructor method
2891 * @param object $properties
2892 * @param lesson $lesson
2894 public function __construct($properties, lesson $lesson) {
2895 parent::__construct($properties);
2896 $this->lesson = $lesson;
2900 * Returns the score for the attempt
2901 * This may be overridden by page types that require manual grading
2902 * @param array $answers
2903 * @param object $attempt
2906 public function earned_score($answers, $attempt) {
2907 return $answers[$attempt->answerid]->score;
2911 * This is a callback method that can be override and gets called when ever a page
2914 * @param bool $canmanage True if the user has the manage cap
2917 public function callback_on_view($canmanage) {
2922 * save editor answers files and update answer record
2924 * @param object $context
2925 * @param int $maxbytes
2926 * @param object $answer
2927 * @param object $answereditor
2928 * @param object $responseeditor
2930 public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') {
2932 if (isset($answereditor['itemid'])) {
2933 $answer->answer = file_save_draft_area_files($answereditor['itemid'],
2934 $context->id, 'mod_lesson', 'page_answers', $answer->id,
2935 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
2936 $answer->answer, null);
2937 $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id));
2939 if (isset($responseeditor['itemid'])) {
2940 $answer->response = file_save_draft_area_files($responseeditor['itemid'],
2941 $context->id, 'mod_lesson', 'page_responses', $answer->id,
2942 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes),
2943 $answer->response, null);
2944 $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id));
2949 * Rewrite urls in response and optionality answer of a question answer
2951 * @param object $answer
2952 * @param bool $rewriteanswer must rewrite answer
2953 * @return object answer with rewritten urls
2955 public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
2958 $context = context_module::instance($PAGE->cm->id);
2959 if ($rewriteanswer) {
2960 $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
2961 'mod_lesson', 'page_answers', $answer->id);
2963 $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
2964 'mod_lesson', 'page_responses', $answer->id);
2970 * Updates a lesson page and its answers within the database
2972 * @param object $properties
2975 public function update($properties, $context = null, $maxbytes = null) {
2977 $answers = $this->get_answers();
2978 $properties->id = $this->properties->id;
2979 $properties->lessonid = $this->lesson->id;
2980 if (empty($properties->qoption)) {
2981 $properties->qoption = '0';
2983 if (empty($context)) {
2984 $context = $PAGE->context;
2986 if ($maxbytes === null) {
2987 $maxbytes = get_user_max_upload_file_size($context);
2989 $properties->timemodified = time();
2990 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id);
2991 $DB->update_record("lesson_pages", $properties);
2993 // Trigger an event: page updated.
2994 \mod_lesson\event\page_updated::create_from_lesson_page($this, $context)->trigger();
2996 if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) {
2997 // These page types have only one answer to save the jump and score.
2998 if (count($answers) > 1) {
2999 $answer = array_shift($answers);
3000 foreach ($answers as $a) {
3001 $DB->delete_record('lesson_answers', array('id' => $a->id));
3003 } else if (count($answers) == 1) {
3004 $answer = array_shift($answers);
3006 $answer = new stdClass;
3007 $answer->lessonid = $properties->lessonid;
3008 $answer->pageid = $properties->id;
3009 $answer->timecreated = time();
3012 $answer->timemodified = time();
3013 if (isset($properties->jumpto[0])) {
3014 $answer->jumpto = $properties->jumpto[0];
3016 if (isset($properties->score[0])) {
3017 $answer->score = $properties->score[0];
3019 if (!empty($answer->id)) {
3020 $DB->update_record("lesson_answers", $answer->properties());
3022 $DB->insert_record("lesson_answers", $answer);
3025 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
3026 if (!array_key_exists($i, $this->answers)) {
3027 $this->answers[$i] = new stdClass;
3028 $this->answers[$i]->lessonid = $this->lesson->id;
3029 $this->answers[$i]->pageid = $this->id;
3030 $this->answers[$i]->timecreated = $this->timecreated;
3033 if (isset($properties->answer_editor[$i])) {
3034 if (is_array($properties->answer_editor[$i])) {
3035 // Multichoice and true/false pages have an HTML editor.
3036 $this->answers[$i]->answer = $properties->answer_editor[$i]['text'];
3037 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format'];
3039 // Branch tables, shortanswer and mumerical pages have only a text field.
3040 $this->answers[$i]->answer = $properties->answer_editor[$i];
3041 $this->answers[$i]->answerformat = FORMAT_MOODLE;
3045 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
3046 $this->answers[$i]->response = $properties->response_editor[$i]['text'];
3047 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format'];
3050 if (isset($this->answers[$i]->answer) && $this->answers[$i]->answer != '') {
3051 if (isset($properties->jumpto[$i])) {
3052 $this->answers[$i]->jumpto = $properties->jumpto[$i];
3054 if ($this->lesson->custom && isset($properties->score[$i])) {
3055 $this->answers[$i]->score = $properties->score[$i];
3057 if (!isset($this->answers[$i]->id)) {
3058 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]);
3060 $DB->update_record("lesson_answers", $this->answers[$i]->properties());
3063 // Save files in answers and responses.
3064 if (isset($properties->response_editor[$i])) {
3065 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
3066 $properties->answer_editor[$i], $properties->response_editor[$i]);
3068 $this->save_answers_files($context, $maxbytes, $this->answers[$i],
3069 $properties->answer_editor[$i]);
3072 } else if (isset($this->answers[$i]->id)) {
3073 $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id));
3074 unset($this->answers[$i]);
3082 * Can be set to true if the page requires a static link to create a new instance
3083 * instead of simply being included in the dropdown
3084 * @param int $previd
3087 public function add_page_link($previd) {
3092 * Returns true if a page has been viewed before
3094 * @param array|int $param Either an array of pages that have been seen or the
3095 * number of retakes a user has had
3098 public function is_unseen($param) {
3100 if (is_array($param)) {
3101 $seenpages = $param;
3102 return (!array_key_exists($this->properties->id, $seenpages));
3105 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) {
3113 * Checks to see if a page has been answered previously
3114 * @param int $nretakes
3117 public function is_unanswered($nretakes) {
3119 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) {
3126 * Creates answers within the database for this lesson_page. Usually only ever
3127 * called when creating a new page instance
3128 * @param object $properties
3131 public function create_answers($properties) {
3133 // now add the answers
3134 $newanswer = new stdClass;
3135 $newanswer->lessonid = $this->lesson->id;
3136 $newanswer->pageid = $this->properties->id;
3137 $newanswer->timecreated = $this->properties->timecreated;
3139 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course);
3140 $context = context_module::instance($cm->id);
3144 for ($i = 0; $i < $this->lesson->maxanswers; $i++) {
3145 $answer = clone($newanswer);
3147 if (isset($properties->answer_editor[$i])) {
3148 if (is_array($properties->answer_editor[$i])) {
3149 // Multichoice and true/false pages have an HTML editor.
3150 $answer->answer = $properties->answer_editor[$i]['text'];
3151 $answer->answerformat = $properties->answer_editor[$i]['format'];
3153 // Branch tables, shortanswer and mumerical pages have only a text field.
3154 $answer->answer = $properties->answer_editor[$i];
3155 $answer->answerformat = FORMAT_MOODLE;
3158 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) {
3159 $answer->response = $properties->response_editor[$i]['text'];
3160 $answer->responseformat = $properties->response_editor[$i]['format'];
3163 if (isset($answer->answer) && $answer->answer != '') {
3164 if (isset($properties->jumpto[$i])) {
3165 $answer->jumpto = $properties->jumpto[$i];
3167 if ($this->lesson->custom && isset($properties->score[$i])) {
3168 $answer->score = $properties->score[$i];
3170 $answer->id = $DB->insert_record("lesson_answers", $answer);
3171 if (isset($properties->response_editor[$i])) {
3172 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
3173 $properties->answer_editor[$i], $properties->response_editor[$i]);
3175 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer,
3176 $properties->answer_editor[$i]);
3178 $answers[$answer->id] = new lesson_page_answer($answer);
3184 $this->answers = $answers;
3189 * This method MUST be overridden by all question page types, or page types that
3190 * wish to score a page.
3192 * The structure of result should always be the same so it is a good idea when
3193 * overriding this method on a page type to call
3195 * $result = parent::check_answer();
3197 * before modifying it as required.
3201 public function check_answer() {
3202 $result = new stdClass;
3203 $result->answerid = 0;
3204 $result->noanswer = false;
3205 $result->correctanswer = false;
3206 $result->isessayquestion = false; // use this to turn off review button on essay questions
3207 $result->response = '';
3208 $result->newpageid = 0; // stay on the page
3209 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page
3210 $result->userresponse = null;
3211 $result->feedback = '';
3212 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off
3217 * True if the page uses a custom option
3219 * Should be override and set to true if the page uses a custom option.
3223 public function has_option() {
3228 * Returns the maximum number of answers for this page given the maximum number
3229 * of answers permitted by the lesson.
3231 * @param int $default
3234 public function max_answers($default) {
3239 * Returns the properties of this lesson page as an object
3242 public function properties() {
3243 $properties = clone($this->properties);
3244 if ($this->answers === null) {
3245 $this->get_answers();
3247 if (count($this->answers)>0) {
3249 $qtype = $properties->qtype;
3250 foreach ($this->answers as $answer) {
3251 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat);
3252 if ($qtype != LESSON_PAGE_MATCHING) {
3253 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat);
3255 $properties->{'response_editor['.$count.']'} = $answer->response;
3257 $properties->{'jumpto['.$count.']'} = $answer->jumpto;
3258 $properties->{'score['.$count.']'} = $answer->score;
3266 * Returns an array of options to display when choosing the jumpto for a page/answer
3268 * @param int $pageid
3269 * @param lesson $lesson
3272 public static function get_jumptooptions($pageid, lesson $lesson) {
3275 $jump[0] = get_string("thispage", "lesson");
3276 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson");
3277 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson");
3278 $jump[LESSON_EOL] = get_string("endoflesson", "lesson");
3284 $pages = $lesson->load_all_pages();
3285 if ($pages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))) {
3286 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson");
3287 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson");
3289 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) {
3290 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson");
3292 if (!optional_param('firstpage', 0, PARAM_INT)) {
3293 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0));
3296 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid));
3297 $jump[$apageid] = strip_tags(format_string($title,true));
3298 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid));
3300 // last page reached
3308 * Returns the contents field for the page properly formatted and with plugin
3309 * file url's converted
3312 public function get_contents() {
3314 if (!empty($this->properties->contents)) {
3315 if (!isset($this->properties->contentsformat)) {
3316 $this->properties->contentsformat = FORMAT_HTML;
3318 $context = context_module::instance($PAGE->cm->id);
3319 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson',
3320 'page_contents', $this->properties->id); // Must do this BEFORE format_text()!
3321 return format_text($contents, $this->properties->contentsformat,
3322 array('context' => $context, 'noclean' => true,
3323 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here.
3330 * Set to true if this page should display in the menu block
3333 protected function get_displayinmenublock() {
3338 * Get the string that describes the options of this page type
3341 public function option_description_string() {
3346 * Updates a table with the answers for this page
3347 * @param html_table $table
3348 * @return html_table
3350 public function display_answers(html_table $table) {
3351 $answers = $this->get_answers();
3353 foreach ($answers as $answer) {
3355 $cells[] = "<span class=\"label\">".get_string("jump", "lesson")." $i<span>: ";
3356 $cells[] = $this->get_jump_name($answer->jumpto);
3357 $table->data[] = new html_table_row($cells);
3359 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;';
3367 * Determines if this page should be grayed out on the management/report screens
3368 * @return int 0 or 1
3370 protected function get_grayout() {
3375 * Adds stats for this page to the &pagestats object. This should be defined
3376 * for all page types that grade
3377 * @param array $pagestats
3381 public function stats(array &$pagestats, $tries) {
3386 * Formats the answers of this page for a report
3388 * @param object $answerpage
3389 * @param object $answerdata
3390 * @param object $useranswer
3391 * @param array $pagestats
3392 * @param int $i Count of first level answers
3393 * @param int $n Count of second level answers
3394 * @return object The answer page for this
3396 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) {
3397 $answers = $this->get_answers();
3398 $formattextdefoptions = new stdClass;
3399 $formattextdefoptions->para = false; //I'll use it widely in this page
3400 foreach ($answers as $answer) {
3401 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto));
3402 $answerdata->answers[] = array($data, "");
3403 $answerpage->answerdata = $answerdata;